forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdfeffbcTahinli2 months ago3180 commits

encode.rs21530 lines, 979.7 KiBHistoryRawDownload
1//! A key-frame picture encoder: a planar 4:2:0 picture in, an AV1 stream out.
2//!
3//! This is the layer that turns the pieces below it — the intra predictors of
4//! [`crate::intra`], the forward transform and quantizer of
5//! [`crate::transform`], and the tile writer of [`crate::tile`] — into
6//! something that takes a picture. Every block is 32x32 (its chroma 16x16),
7//! which is the subset the tile writer codes, and each one picks its luma mode
8//! from the seven non-directional ones by rate-distortion; chroma searches
9//! its own `uv_mode` over the seven that read no further than the row above
10//! and the column to the left, its transform type derived from that mode the
11//! way the decoder derives it. Block sizes are what a loop above this would
12//! choose between.
13//!
14//! The encoder carries its own reconstruction, because prediction reads it: a
15//! block predicts from the reconstructed samples above and to its left, exactly
16//! as the decoder will. That makes the reconstruction a claim about what a
17//! decoder produces, and it is gated as one — sample for sample against ffmpeg.
18
19use crate::decode::WithRef;
20use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
21use ec_av1_syntax::{
22 CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams,
23 LoopRestorationParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, TxMode,
24};
25use ec_core::{Error, Result};
26
27use crate::cdf;
28use crate::cdf_state::TxbSet;
29use crate::frame::frame_obu;
30use crate::intra::{
31 D67_PRED, DC_PRED, H_PRED, KEY_FRAME_MODES, PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED,
32 SMOOTH_V_PRED, V_PRED,
33};
34use crate::mc;
35use crate::motion;
36use crate::mvstack::{MiGrid, MiInfo, MvStack, NO_REF1, find_mv_stack, mv16};
37use crate::obu::temporal_delimiter;
38use crate::quant::ac_q;
39use crate::sequence::sequence_header_obu;
40use crate::tile::{
41 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
42};
43use crate::transform::{
44 TxType, dequant_and_inverse_typed_wh, forward_and_quantize_typed,
45 forward_and_quantize_typed_scaled,
46};
47#[cfg(test)]
48use crate::transform::forward_and_quantize;
49
50/// The side of the larger of the two luma blocks this encoder codes, in
51/// samples.
52const BLOCK: usize = 32;
53
54/// The side of the smaller one, which a 32x32 block may be split into four of.
55const SUB: usize = 16;
56
57/// The side of a superblock, which is what the partition tree starts from.
58pub(crate) const SUPERBLOCK: usize = 64;
59
60// lane-sb128 r1: the superblock size in samples the intra-reach rules
61// (`has_top_right`/`has_bottom_left`) are answered against. libaom masks the
62// block's mi position with `mi_size_wide[cm->seq_params->sb_size] - 1` and
63// tests the "top row"/"rightmost column" of THAT superblock, so a 128x128
64// superblock changes every answer inside it (the tables themselves are
65// already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`]
66// stays the encoder's own fixed 64.
67
68/// Sets the superblock size [`Reach`] answers against (64 or 128).
69pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) {
70 fctx.reach_sb_px.with(|c| c.set(px));
71}
72
73fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize {
74 fctx.reach_sb_px.with(|c| c.get())
75}
76
77/// How heavily the mode search weighs rate against squared error, in units of
78/// the quantizer's reconstruction step squared per bit.
79///
80/// Swept three times over his clips and three synthetic pictures
81/// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in
82/// the three lane reports). The first sweep, before the mode symbol was
83/// costed, put the best point at 0.05; costing it moved the point to 0.1. The
84/// third sweep, after the levels were costed through the writer's own CDFs
85/// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98%
86/// on film and -0.20% against -0.14% on screen capture.
87///
88/// The fourth sweep (lane-av1lambda) ran the BD gates themselves rather than
89/// those ladders, and 0.1 was far off the point: the rate term was carrying
90/// roughly twice the weight it is worth. 640x384 gate, BD-rate vs libaom /
91/// vs rav1e for 1080p film, 2160p film, screen capture:
92///
93/// | lambda | 1080p | 2160p | screen |
94/// |--------|-------|-------|--------|
95/// | 0.0125 | +78.0 / +31.3 | +90.8 / +46.5 | +57.2 / -0.3 |
96/// | 0.025 | +71.5 / +28.4 | +87.0 / +46.5 | +50.4 / -3.8 |
97/// | 0.0375 | +71.2 / +28.5 | +84.3 / +45.4 | +48.7 / -4.4 |
98/// | 0.05 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
99/// | 0.075 | +74.8 / +32.7 | +91.3 / +52.8 | +51.4 / -1.3 |
100/// | 0.1 | +79.2 / +36.9 | +97.7 / +58.8 | +53.1 / -0.4 |
101/// | 0.125 | +84.0 / +41.1 | +100.7 / +61.5 | +56.8 / +2.3 |
102/// | 0.15 | +86.0 / +42.9 | +104.4 / +65.2 | +59.5 / +4.2 |
103/// | 0.2 | +89.6 / +45.5 | +109.9 / +69.8 | +62.3 / +7.3 |
104///
105/// and on the native 1920x1024 crops, which is the table that decides:
106///
107/// | lambda | film 1080p | film 2160p | screen |
108/// |--------|------------|------------|--------|
109/// | 0.025 | +17.1 / -0.5 | +49.0 / +21.1 | +51.5 / -15.1 |
110/// | 0.0375 | +16.3 / -1.0 | +47.5 / +19.7 | +50.7 / -15.1 |
111/// | 0.05 | +17.0 / -0.3 | +47.0 / +19.2 | +51.6 / -14.2 |
112/// | 0.1 | +18.1 / +0.9 | +47.1 / +19.0 | +58.3 / -9.8 |
113///
114/// 0.0375 was the best point on two clips of three there and cost the "2160p
115/// film" row +0.4/+0.7, outside the +-0.3 band every other lever here is kept
116/// inside, so 0.05 shipped. BOTH of those tables' "film" rows are the
117/// `testsrc2` COLOUR BARS fixtures (see [`bd_rate_screen_native`]), ~90% of
118/// whose cells have no intra cost -- no real film supported the point.
119///
120/// FIFTH SWEEP (lane-av1resweep, 2026-09-07), on the native gate's two REAL
121/// film crops (film A 1080p, film B 2160p HDR) plus the capture, BD-rate vs
122/// libaom / vs rav1e, everything else at the shipped defaults:
123///
124/// | lambda | bars 1080p | bars 2160p | film A | film B | screen |
125/// |--------|------------|------------|--------|--------|--------|
126/// | 0.02 | +17.5 / -0.2 | +49.7 / +21.7 | +65.8 / +35.0 | +91.2 / +55.4 | +53.4 / -14.1 |
127/// | 0.0275 | +16.6 / -0.9 | +48.3 / +20.5 | +65.5 / +34.7 | +91.6 / +55.1 | +51.3 / -15.0 |
128/// | 0.035 | +16.1 / -1.3 | +47.5 / +19.7 | +66.4 / +35.2 | +94.2 / +56.9 | +50.8 / -15.1 |
129/// | 0.05 | +15.6 / -1.7 | +46.5 / +18.8 | +69.0 / +37.5 | +100.0 / +61.5 | +51.0 / -14.5 |
130/// | 0.07 | +16.6 / -0.5 | +46.8 / +18.8 | +72.3 / +40.4 | +108.5 / +68.8 | +54.4 / -12.4 |
131/// | 0.1 | +16.5 / -0.7 | +46.6 / +18.7 | +76.9 / +44.4 | +118.2 / +77.1 | +57.3 / -10.1 |
132///
133/// Real film wants roughly HALF the rate weight the bars asked for: the bowl
134/// on both film rows bottoms between 0.02 and 0.0275 and is 5-11 points deep
135/// against the shipped 0.05, while the bars rows walk the other way (they are
136/// recorded, not decided on). 0.02 breaks the capture (+2.4 vs libaom), so
137/// 0.0275 ships -- both films 3.5/8.4 points down vs libaom, the capture
138/// +0.3/-0.5 (at the +-0.3 band, and better than baseline once the var-tx
139/// defaults below are on: +50.1 / -15.4). It spends ~5% more encode wall.
140const LAMBDA_SCALE: f64 = 0.0275;
141
142/// The rate weight a HIDDEN frame (a pyramid ARF, coded but not shown) codes
143/// under, as a multiple of [`LAMBDA_SCALE`] (lane-arfcen).
144///
145/// The ARF-vs-ARF census says our top ARF codes residual over HALF its area
146/// (rav1e's, at the same display position, over 26-30%) and comes out 1.4-2.5x
147/// its bytes at the same PSNR, while every leaf that predicts from it is
148/// still 0.4 dB behind rav1e's -- i.e. the ARF's extra fidelity is bought at
149/// a rate weight fitted on shown frames and does not propagate. This is the
150/// one knob that prices a hidden frame's rate differently from its q, which
151/// the pyramid's q offsets cannot do (they move lambda and step together).
152const HIDDEN_LAMBDA_FACTOR: f64 = 1.0;
153
154/// [`HIDDEN_LAMBDA_FACTOR`], swept by `EC_AV1_LAMBDA_HIDDEN` in any build.
155fn hidden_lambda_factor() -> f64 {
156 match std::env::var("EC_AV1_LAMBDA_HIDDEN").ok().and_then(|v| v.parse().ok()) {
157 Some(f) => f,
158 None => HIDDEN_LAMBDA_FACTOR,
159 }
160}
161
162/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
163/// picks it is the thing running. A release build has no such knob.
164fn lambda_scale() -> f64 {
165 let swept = std::env::var("EC_AV1_LAMBDA")
166 .ok()
167 .and_then(|v| v.parse::<f64>().ok());
168 match swept {
169 Some(scale) if cfg!(test) => scale,
170 _ => LAMBDA_SCALE,
171 }
172}
173
174/// How a key frame's lambda differs from an inter frame's: libaom weighs the
175/// two apart (`rd_frame_type_factor`, key 128 against an inter frame's 144 out
176/// of 128), because every later frame predicts from the key frame, so an error
177/// left in it is paid for over the whole group. This encoder has no temporal
178/// propagation model at all, and this factor is the cheapest stand-in for one.
179/// Swept by `EC_AV1_LAMBDA_KEY` in a test build, like [`lambda_scale`].
180///
181/// MEASURED and NOT KEPT. 640x384 gate at [`LAMBDA_SCALE`] 0.05, BD vs
182/// libaom / vs rav1e:
183///
184/// | k_key | 1080p | 2160p | screen |
185/// |---|---|---|---|
186/// | 1.0 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
187/// | 0.85 | +71.5 / +29.4 | +87.0 / +48.3 | +49.7 / -3.9 |
188/// | 0.7 | +71.3 / +28.9 | +87.2 / +48.6 | +49.4 / -4.1 |
189/// | 0.5 | +71.4 / +28.9 | +88.7 / +49.6 | +50.1 / -3.4 |
190///
191/// The two films want the key frame coded finer and the screen capture wants
192/// the opposite, by about the same amount, and at native the whole lever is
193/// inside the +-0.3 band that decides nothing: k_key 0.7 reads +16.9 / -0.3,
194/// +47.2 / +19.2, +51.4 / -14.7 against 1.0's +17.0 / -0.3, +47.0 / +19.2,
195/// +51.6 / -14.2. A gate whose GOP is one key frame in twelve cannot see a
196/// per-frame-type weight; the real lever here is temporal propagation
197/// (libaom's `tpl`), which weighs each BLOCK by how much of it later frames
198/// predict from, not each frame.
199const KEY_LAMBDA_FACTOR: f64 = 1.0;
200
201/// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build.
202fn key_lambda_factor() -> f64 {
203 match std::env::var("EC_AV1_LAMBDA_KEY").ok().and_then(|v| v.parse::<f64>().ok()) {
204 Some(k) if cfg!(test) => k,
205 _ => KEY_LAMBDA_FACTOR,
206 }
207}
208
209// Every frame's predicted coefficient bits since the last
210// `take_predicted_bits`, in coding order -- the encoder half of
211// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement.
212#[cfg(test)]
213thread_local! {
214 static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) };
215}
216
217/// Records one frame's predicted coefficient bits.
218#[cfg(test)]
219fn record_predicted_bits(bits: f64) {
220 PREDICTED_BITS.with(|p| p.borrow_mut().push(bits));
221}
222
223/// Takes (and clears) what the frames encoded on this thread were predicted to
224/// spend on coefficients.
225#[cfg(test)]
226pub(crate) fn take_predicted_bits() -> Vec<f64> {
227 PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut()))
228}
229
230/// Whether a 16x16 inter leaf may split into four 8x8 ones of its own.
231pub(crate) const SPLIT_INTER_8: bool = true;
232
233/// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
234/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
235/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0`
236/// turns it off for an A/B on one build.
237/// Whether an INTER frame also carries `TxMode::Select`: an inter block's
238/// residual as one transform over the whole block or as the four transforms
239/// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every
240/// intra block inside the inter frame. ON since lane-av1tx2, which found why
241/// the streams desynced -- the writer counted the [`crate::decode::
242/// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the
243/// reader drops the term -- and measured the split search: BD-rate vs libaom
244/// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the
245/// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an
246/// A/B on one build.
247fn tx_select_inter() -> bool {
248 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
249 crate::envflags::var("EC_AV1_TX_SELECT_INTER")
250 .ok()
251 .map(|v| !matches!(v.as_str(), "0" | "off"))
252 });
253 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER))
254}
255
256/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`, control
257/// vs arm): the capture row goes +27.8/-26.0 -> +20.8/-30.1 -- seven points
258/// against libaom -- while BOTH film rows LOSE (film A +21.7/-4.4 ->
259/// +22.1/-4.0, film B +26.9/-0.6 -> +28.1/+0.7) and 2160p bars lose 0.8/1.1.
260/// The keep rule wants both films down, so this takes the same content gate
261/// palette, intrabc and the angle-delta refinement already stand behind: a
262/// non-screen frame is byte-identical to the encoder before the lane.
263///
264/// The transform types an intra luma transform unit of `set` may be coded
265/// with -- exactly the alphabet the writer's `tx_type` symbol names for that
266/// set, so a searched type is always one the tile can express (lane-txset).
267/// `DCT_DCT` first: it is the incumbent every other candidate has to beat.
268///
269/// Under this encoder's `reduced_tx_set` header bit every intra set at 16x16
270/// and below is `TX_SET_INTRA_2` (spec `get_tx_set`), the five types
271/// [`TxType::from_symbol`] names; 32x32 and 64x64 luma code no symbol at all,
272/// and inter luma reads the two-type `TX_SET_INTER_3`, left at `DCT_DCT`
273/// here.
274pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
275 const DCT: [TxType; 1] = [TxType::DctDct];
276 const INTRA1: [TxType; 7] = [
277 TxType::DctDct,
278 TxType::AdstAdst,
279 TxType::AdstDct,
280 TxType::DctAdst,
281 TxType::Idtx,
282 TxType::VDct,
283 TxType::HDct,
284 ];
285 const INTRA2: [TxType; 5] = [
286 TxType::DctDct,
287 TxType::AdstAdst,
288 TxType::AdstDct,
289 TxType::DctAdst,
290 TxType::Idtx,
291 ];
292 match set {
293 TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4
294 if intra_tx_search_on(screen) =>
295 {
296 &INTRA2
297 }
298 // lane-txi: a `reduced_tx_set == 0` frame's intra 8x8/4x4 reads the
299 // SEVEN-type `TX_SET_INTRA_1` (`decode::txbset_for`'s `Luma{8,4}Set1`;
300 // 16x16 stays `TX_SET_INTRA_2`, there is no `Luma16Set1`). The two
301 // extra members are the 1-D DCTs, and the order is the reader's own
302 // map (`decode::tx_type_from_symbol`, 8-wide CDF).
303 TxbSet::Luma8Set1 | TxbSet::Luma4Set1
304 if intra_tx_search_on(screen) =>
305 {
306 &INTRA1
307 }
308 _ => &DCT,
309 }
310}
311
312/// The transform types an INTER luma transform unit of `set` may be coded
313/// with (lane-txset2). Under this encoder's `reduced_tx_set` header bit every
314/// inter luma set at 16x16 and below is the two-type `TX_SET_INTER_3`
315/// (`IDTX`, `DCT_DCT`) and 32x32 is `EXT_TX_SET_DCT_IDTX` -- the same two
316/// types, a symbol the writer already codes and never varied. 64x64 codes no
317/// `tx_type` symbol at all, so it is not offered one.
318/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`): the
319/// capture row goes +20.8/-30.1 -> +20.1/-30.4 while the two synthetic bars
320/// rows lose TWENTY points (-1.0/-16.8 -> +23.1/+3.3 and +9.4/-12.7 ->
321/// +31.2/+3.7) and film B 0.3 -- the `local-rd-on-references` class at its
322/// loudest, and restricting the offer to 16x16 and below does not soften it
323/// (`le16`: +22.9/+3.1, +31.6/+4.0). So this takes the same content gate the
324/// intra search, palette and intrabc stand behind: a non-screen frame is
325/// byte-identical to the encoder before the lane.
326///
327/// `EC_AV1_TXSET_INTER`: `0`/`off`, `screen` (screen frames only), `le16`
328/// (16x16 and below, the sizes libaom's own census picks a non-`DCT_DCT`
329/// inter type on -- it never takes `IDTX` at 32x32 on film B), anything else
330/// on for every frame at every size.
331pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
332 const DCT: [TxType; 1] = [TxType::DctDct];
333 const INTER3: [TxType; 2] = [TxType::DctDct, TxType::Idtx];
334 const INTER_WIDE: [TxType; 7] = [
335 TxType::DctDct,
336 TxType::AdstAdst,
337 TxType::AdstDct,
338 TxType::DctAdst,
339 TxType::Idtx,
340 TxType::VDct,
341 TxType::HDct,
342 ];
343 let mode = inter_tx_type_search();
344 let on = match mode {
345 InterTxSearch::Off => false,
346 InterTxSearch::Screen => screen,
347 InterTxSearch::All | InterTxSearch::Le16 => true,
348 };
349 match set {
350 TxbSet::Luma32Inter if on && mode != InterTxSearch::Le16 => &INTER3,
351 TxbSet::Luma16Inter | TxbSet::Luma8Inter | TxbSet::Luma4Inter if on => &INTER3,
352 // lane-txi: a `reduced_tx_set == 0` frame's inter 16x16 reads the
353 // TWELVE-type `TX_SET_INTER_2` and its 8x8/4x4 `ALL16` (inter 32x32
354 // stays the two-type `DCT_IDTX`). The seven offered here are the
355 // members those two alphabets SHARE with the intra set -- the four
356 // DTT combinations, `IDTX` and the two 1-D DCTs -- which is the
357 // candidate list rav1e's speed 6 prunes to; the FLIPADST family and
358 // the 1-D ADSTs are codable and left unoffered (deferred).
359 TxbSet::Luma16InterSet1 | TxbSet::Luma8InterSet1 | TxbSet::Luma4InterSet1 if on => {
360 &INTER_WIDE
361 }
362 _ => &DCT,
363 }
364}
365
366/// lane-txi: does THIS frame code `reduced_tx_set = 0` (spec 5.9.2), i.e.
367/// the wider `tx_type` alphabets at intra 8x8/4x4 and inter 16x16 and below?
368/// `EC_AV1_TXSET_WIDE`: `0`/`off`, `screen` (screen frames only), anything
369/// else every frame; unset takes [`crate::speed::WIDE_TX_SET`], screen-gated
370/// like both halves of the type search itself.
371pub(crate) fn wide_tx_set(screen: bool) -> bool {
372 match WIDE_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
373 0 => return false,
374 1 => return true,
375 _ => {}
376 }
377 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
378 crate::envflags::var("EC_AV1_TXSET_WIDE").ok().map(|v| match v.as_str() {
379 "0" | "off" => InterTxSearch::Off,
380 "screen" => InterTxSearch::Screen,
381 _ => InterTxSearch::All,
382 })
383 });
384 match ENV.unwrap_or(if crate::speed::at(&crate::speed::WIDE_TX_SET) {
385 InterTxSearch::Screen
386 } else {
387 InterTxSearch::Off
388 }) {
389 InterTxSearch::Off => false,
390 InterTxSearch::Screen => screen,
391 _ => true,
392 }
393}
394
395/// A PROCESS-GLOBAL [`wide_tx_set`] override that wins over both the
396/// environment and the preset (`u8::MAX` = unset), the shape
397/// [`set_inter_tx_search`] has: the lever is OFF at every preset, so the
398/// witness that has to see the wider alphabets turns it on through this while
399/// holding [`crate::speed::knob_write`].
400static WIDE_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
401 std::sync::atomic::AtomicU8::new(u8::MAX);
402
403/// Sets [`WIDE_TX_OVERRIDE`]; `None` clears it.
404#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
405pub(crate) fn set_wide_tx_set(on: Option<bool>) {
406 WIDE_TX_OVERRIDE.store(
407 on.map_or(u8::MAX, u8::from),
408 std::sync::atomic::Ordering::Relaxed,
409 );
410}
411
412/// The luma [`TxbSet`] the SEARCH and its pricer name for a frame that codes
413/// `reduced_tx_set = 0`: the writer reads the bit once, off the frame's own
414/// [`crate::cdf_state::Cdfs`], but the trial that prices a type has to read
415/// the same alphabet or the two disagree on what a `tx_type` symbol costs.
416pub(crate) fn luma_set_for(set: TxbSet, screen: bool) -> TxbSet {
417 if wide_tx_set(screen) {
418 set.wide()
419 } else {
420 set
421 }
422}
423
424#[derive(Clone, Copy, PartialEq)]
425pub(crate) enum InterTxSearch {
426 Off,
427 Screen,
428 /// 16x16 and below only.
429 Le16,
430 All,
431}
432
433/// A PROCESS-GLOBAL [`inter_tx_type_search`] override that wins over both the
434/// environment and the preset (`u8::MAX` = unset), the shape
435/// [`set_deltaq_res`] has: the lever is OFF at every preset, so the witness
436/// that has to see a non-`DCT_DCT` inter unit turns it on through this while
437/// holding [`crate::speed::knob_write`].
438static INTER_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
439 std::sync::atomic::AtomicU8::new(u8::MAX);
440
441/// Sets [`INTER_TX_OVERRIDE`]; `None` clears it.
442#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
443pub(crate) fn set_inter_tx_search(on: Option<bool>) {
444 INTER_TX_OVERRIDE.store(
445 on.map_or(u8::MAX, u8::from),
446 std::sync::atomic::Ordering::Relaxed,
447 );
448}
449
450fn inter_tx_type_search() -> InterTxSearch {
451 match INTER_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
452 0 => return InterTxSearch::Off,
453 1 => return InterTxSearch::All,
454 _ => {}
455 }
456 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
457 crate::envflags::var("EC_AV1_TXSET_INTER").ok().map(|v| match v.as_str() {
458 "0" | "off" => InterTxSearch::Off,
459 "screen" => InterTxSearch::Screen,
460 "le16" => InterTxSearch::Le16,
461 _ => InterTxSearch::All,
462 })
463 });
464 ENV.unwrap_or_else(|| {
465 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH_INTER) {
466 InterTxSearch::Screen
467 } else {
468 InterTxSearch::Off
469 }
470 })
471}
472
473/// The inter luma [`TxbSet`] a `tx`-sided transform unit reads, `None` for the
474/// 64-point one (it codes no `tx_type` symbol).
475/// lane-txw history, resolved by lane-intertx: the INTER half of the
476/// widening was blocked by `refusal-from-own-desync` twice over. Half of it
477/// was this writer coding a `V_DCT`/`H_DCT` unit as `TX_CLASS_2D`
478/// (`tile::write_coeffs`, fixed by lane-txw, which unblocked the intra
479/// half). The other half was the CHROMA inheritance: an inter block's
480/// chroma transform type is the luma type reduced to the chroma size's set
481/// (`decode::reduce_inherited_chroma_tx_type`), and (a) the encoder never
482/// set `FrameCtx::reduced_tx_set_inter`, so [`recode_inter_chroma`] reduced
483/// against a STALE allowance, and (b) `tile::write_block_planes` coded
484/// every chroma plane as `DCT_DCT`, so an inherited 1-D type desynced the
485/// chroma exactly as luma did. lane-intertx fixed both -- the frame sets
486/// its own bit on the context (`encode_inter_frame`), the writer derives
487/// the chroma type from this frame's own header bit
488/// (`reduce_inherited_chroma_tx_type_flagged`) -- and the widened SEARCH
489/// names these sets through [`luma_set_for`] at its call sites, so the
490/// wider candidates are reachable and honestly priced. The intra half
491/// never needed either (an intra block's chroma type comes off its own UV
492/// mode, never off luma).
493fn inter_luma_set(tx: usize) -> Option<TxbSet> {
494 Some(match tx {
495 4 => TxbSet::Luma4Inter,
496 8 => TxbSet::Luma8Inter,
497 16 => TxbSet::Luma16Inter,
498 32 => TxbSet::Luma32Inter,
499 _ => return None,
500 })
501}
502
503fn tx_type_search() -> bool {
504 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
505 crate::envflags::var("EC_AV1_TXSET")
506 .ok()
507 .map(|v| !matches!(v.as_str(), "0" | "off"))
508 });
509 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH))
510}
511
512/// Whether an intra luma unit of this frame searches its own type at all:
513/// the preset lever ([`tx_type_search`]) under the screen content gate, which
514/// `EC_AV1_TXSET=all` ([`intra_tx_all_frames`]) lifts and the process-global
515/// [`set_intra_tx_search`] override wins over (the witness needs the search
516/// on a frame the detector called non-screen).
517fn intra_tx_search_on(screen: bool) -> bool {
518 match INTRA_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
519 0 => return false,
520 1 => return true,
521 _ => {}
522 }
523 (screen || intra_tx_all_frames()) && tx_type_search()
524}
525
526/// A PROCESS-GLOBAL [`intra_tx_search_on`] override (`u8::MAX` = unset), the
527/// shape [`set_inter_tx_search`] has.
528static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
529 std::sync::atomic::AtomicU8::new(u8::MAX);
530
531/// Sets [`INTRA_TX_OVERRIDE`]; `None` clears it.
532#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
533pub(crate) fn set_intra_tx_search(on: Option<bool>) {
534 INTRA_TX_OVERRIDE.store(
535 on.map_or(u8::MAX, u8::from),
536 std::sync::atomic::Ordering::Relaxed,
537 );
538}
539
540/// lane-txi: `EC_AV1_TXSET=all` offers the five-type intra set on EVERY
541/// frame -- the unconditional arm the gate measures -- instead of the screen
542/// content gate [`tx_type_candidates`] ships behind. Any other value keeps
543/// the gate (`0`/`off` still switches the search off entirely).
544fn intra_tx_all_frames() -> bool {
545 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
546 crate::envflags::var("EC_AV1_TXSET").is_ok_and(|v| v == "all")
547 });
548 *ENV
549}
550
551fn tx_select() -> bool {
552 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
553 crate::envflags::var("EC_AV1_TX_SELECT")
554 .ok()
555 .map(|v| !matches!(v.as_str(), "0" | "off"))
556 });
557 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY))
558}
559
560fn split_inter_8() -> bool {
561 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
562 Some(v) if cfg!(test) => v != "0",
563 _ => crate::speed::at(&crate::speed::SPLIT_8),
564 }
565}
566
567/// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
568/// NEARESTMV candidate it always had.
569pub(crate) const LEAF_NEW_MV: bool = true;
570
571/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
572/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
573/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
574/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
575pub(crate) const EXTRA_REF_NEW_MV: bool = true;
576
577/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
578/// own best vector before that reference's `NEWMV` search is skipped: a
579/// factor on the search cost scale, `1.0` meaning "as good or better".
580/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
581/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
582/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
583/// extra searches drop from +27% to +4% of the base count -- and on screen
584/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
585/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
586/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: 0.25
587/// reads +16.6/-0.6, +47.0/+19.1, +51.3/-14.3 and 0.5 reads +16.6/-0.7,
588/// +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, +47.0/+19.1,
589/// +51.3/-14.3 -- one row 0.1-0.2 down, two flat, inside the measurement's
590/// own noise. 0.35 stays; the lever that did move at the new rate weight is
591/// [`LEAF_SECOND_NEW_MARGIN`], not this one.
592const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
593
594/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
595fn extra_new_skip_margin() -> f64 {
596 match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
597 Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
598 _ => EXTRA_NEW_SKIP_MARGIN,
599 }
600}
601
602/// The margin on a LEAF's SECOND-reference motion search, the same early-out
603/// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference
604/// `NEWMV`: the search is skipped when that reference's own
605/// `NEAREST_NEARESTMV` vector already prices this many times better than the
606/// leaf's `LAST` search found. `0.0` never skips.
607///
608/// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs
609/// libaom (1080p/2160p/screen) against the extra `motion::search` calls at
610/// 2160p (38195 with no second-reference search at all):
611/// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093,
612/// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at
613/// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the
614/// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter
615/// of its extra searches; past it the calls double for another -0.3/-0.5.
616/// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is
617/// all `NEAREST_NEARESTMV` and no searched second vector ever wins there --
618/// so the margin is pure wall on that content (+10% searches at 0.8).
619///
620/// RE-SWEPT on lane-av1rejudge after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, on
621/// the native gate with local warp on, BD vs libaom / vs rav1e:
622///
623/// | margin | film 1080p | film 2160p | screen |
624/// |---|---|---|---|
625/// | 0.6 | +16.9 / -0.4 | +47.0 / +19.1 | +51.2 / -14.4 |
626/// | 0.8 (was) | +16.7 / -0.5 | +47.0 / +19.1 | +51.3 / -14.3 |
627/// | 1.2 | +16.2 / -1.1 | +46.6 / +18.8 | +51.3 / -14.4 |
628/// | 1.6 | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
629/// | 0.0 (never skip) | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
630///
631/// 1.2 is the floor of that bowl -- two rows 0.3-0.6 down on BOTH columns
632/// with screen flat -- and it beats never-skipping, i.e. the early-out is
633/// still worth having, just at a looser margin than the old rate weight
634/// wanted. It costs about 10% encoder wall on the two film clips (36.6s vs
635/// 32.6s at 2160p), which is the price of the extra second-reference
636/// searches.
637const LEAF_SECOND_NEW_MARGIN: f64 = 1.2;
638
639/// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the
640/// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`.
641fn leaf_second_new_margin() -> f64 {
642 match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() {
643 Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN),
644 None => LEAF_SECOND_NEW_MARGIN,
645 }
646}
647
648/// Whether a leaf searches its SECOND reference at all (lane-av1comp4).
649fn leaf_second_new_mv() -> bool {
650 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
651 Some(v) => v != "0",
652 None => crate::speed::at(&crate::speed::LEAF_SECOND),
653 }
654}
655
656/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
657/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
658/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
659/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
660/// was missing was the encoder ever forming one below 32x32.
661pub(crate) const LEAF_COMPOUND: bool = true;
662
663/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
664fn leaf_compound() -> bool {
665 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
666 Some(v) => v != "0",
667 None => crate::speed::at(&crate::speed::LEAF_COMPOUND),
668 }
669}
670
671/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
672fn leaf_new_mv() -> bool {
673 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
674 Some(v) if cfg!(test) => v != "0",
675 _ => LEAF_NEW_MV,
676 }
677}
678
679/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
680/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
681/// the true frame edge cut through was ever split there; inside the frame
682/// every block was coded whole, which left the partition decision the key
683/// frame already makes unmade for eleven frames out of twelve.
684pub(crate) const SPLIT_INTER_BLOCKS: bool = true;
685
686/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
687/// measurement that keeps it is running (test builds only, like
688/// [`lambda_scale`]).
689fn split_inter_blocks() -> bool {
690 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
691 Some(v) if cfg!(test) => v != "0",
692 _ => crate::speed::at(&crate::speed::SPLIT_INTER),
693 }
694}
695
696/// Whether the inter search offers the whole superblock as ONE 64x64 block
697/// (`PARTITION_NONE` at `BLOCK_64X64`), coded SKIP, against the four 32x32
698/// quadrants it would otherwise always split into.
699///
700/// The census (`lanes/census-filmB.md`) is what points here: rav1e speed 6
701/// codes 45.2% of its blocks at 64x64 -- 73.8% of its LEAF blocks, 99.2% of
702/// them skip at 328 bytes a frame -- while every block this encoder wrote was
703/// 32x32 or smaller, which put our mode+mv+partition+tx_size spend at 162,669
704/// bits against rav1e's 61,988, about 46% of the film B gap.
705///
706/// lane-tx64: no longer skip-only. The root also prices a REAL residual --
707/// one TX_64X64 luma transform (`transform.rs`'s forward network has always
708/// reached 64 points; what was missing was the block coder and the writer
709/// around it) and one TX_32X32 per chroma plane -- see [`b64_residual`],
710/// which carries that arm's own gate table. Still refused at the 64 root:
711/// compound references, a depth-1 4x32x32 var-tx tree, intra, and a
712/// superblock the true frame edge cuts through.
713///
714/// Switched off by `EC_AV1_B64=0` in any build; `EC_AV1_B64RES=0` keeps the
715/// root and restores the skip-only shape lane-b64 shipped.
716pub(crate) const B64_ROOT: bool = true;
717
718/// How many superblocks took the 64x64 root since the last
719/// [`take_b64_root_hits`], so a gate reports how often it fires rather than
720/// assuming it does (class `gate-blind-to-feature`).
721static B64_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
722
723/// The 64x64-root count since the last call, and zero it.
724pub fn take_b64_root_hits() -> usize {
725 B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
726}
727
728/// Whether the 128 superblock root offers its `PARTITION_NONE` candidate at
729/// all ([`search_root_128`]). On by default; `EC_AV1_B128=0` turns it off,
730/// which is the attribution arm for a 128-superblock stream: it separates
731/// what the SIZE costs from what the 128x128 BLOCK buys.
732fn b128_root() -> bool {
733 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
734 crate::envflags::var("EC_AV1_B128").ok().is_none_or(|v| v != "0")
735 });
736 *ENV
737}
738
739/// lane-b128r: whether the 128 root prices a REAL residual as well as the
740/// skip arm -- four TX_64X64 luma units interleaved with a TX_32X32 chroma
741/// pair per 64x64 mu chunk, var-tx depth 0 (the shape
742/// [`crate::tile::write_inter_block_128`] codes and `decode_inter_block`
743/// reads). Written, witnessed and byte-exact through both decoders, and
744/// **off by default** (`EC_AV1_B128RES=1` turns it on) because it is INERT
745/// on content: the RD takes it 0.7-1.9 times per frame against thousands of
746/// whole 128 roots (lane-b128res census, native 12-frame gate, every clip),
747/// and the BD effect is inside the noise on both gates -- long-GOP films
748/// -0.1/+0.1 and all five 12-frame rows within 0.1 of the off default.
749///
750/// The historical reason for the parking is CLOSED: the bars 2160p q=90
751/// frame 11 disagreement with ffmpeg (8 luma samples at the rows above a
752/// 128-superblock horizontal edge) was the CDEF search pricing a preset per
753/// 64x64 unit under a root that codes ONE literal for all four -- lane-
754/// edge128's `crate::tile::cdef_unit_owner` collapses the four to the one
755/// the decoder derives, and on this HEAD the same row re-measures three-way
756/// EXACT (encoder reconstruction == ffmpeg == `decode_stream`, every frame,
757/// every plane, both gates). The knob stays as the arm's gate, not as a
758/// defect flag.
759fn b128_residual() -> bool {
760 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
761 crate::envflags::var("EC_AV1_B128RES").ok().map(|v| v != "0")
762 });
763 (ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
764 && b128_root()
765}
766/// lane-rectres: whether the 128 root's RECTANGULAR pieces -- the two
767/// HORZ/VERT halves and the four AB shapes' three pieces (two 64x64 squares
768/// plus one half) -- price a REAL residual in the RD as well as the skip arm
769/// ([`search_root_128_rect`] / [`search_root_128_ab`], written through
770/// [`crate::tile::write_inter_block_128_rect`]). **Off by default**
771/// (`EC_AV1_RECTRES=1` turns it on): OFF is today's behavior bit for bit --
772/// no rect/AB piece can come out non-skip, so the writer's refusal is never
773/// reached. The residual shape is the whole 128 block's, halved or quartered
774/// per piece: one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
775/// mu chunk, var-tx depth 0 (exactly what the decoder's mu-chunk loop reads
776/// for any inter partition shape).
777fn rectres() -> bool {
778 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
779 crate::envflags::var("EC_AV1_RECTRES")
780 .ok()
781 .map(|v| v != "0")
782 });
783 ENV.unwrap_or(false) || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed)
784}
785
786/// Test-only: take the rect/AB pieces' residual arm whatever it costs, so a
787/// witness clip codes the shape rather than waiting for content on which the
788/// RD picks it (the same role [`FORCE_B128_RESIDUAL`] plays at the NONE
789/// root). Never read outside `#[cfg(test)]` builds.
790static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =
791 std::sync::atomic::AtomicBool::new(false);
792
793/// Arms [`FORCE_B128_RECTRES`] for the rest of the process.
794#[cfg(test)]
795pub(crate) fn force_b128_rectres(on: bool) {
796 FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed);
797}
798
799/// How many rect/AB pieces the search left WITH a residual rather than
800/// skipped, since the last [`take_b128_rectres_hits`] (class
801/// `gate-blind-to-feature`).
802static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize =
803 std::sync::atomic::AtomicUsize::new(0);
804
805/// The rect/AB-piece-residual count since the last call, and zero it.
806pub fn take_b128_rectres_hits() -> usize {
807 B128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
808}
809
810/// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64
811/// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`,
812/// `NEW_NEARESTMV` over the LAST+GOLDEN / LAST+ALTREF pairs), at the block's
813/// own 32x32-mi window. `EC_AV1_B128COMP=0` turns it off, which is this
814/// arm's attribution control; the writer has always had the path
815/// (`write_inter_block_128` calls `write_compound_block` for a block that
816/// names a second reference).
817fn b128_compound() -> bool {
818 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
819 crate::envflags::var("EC_AV1_B128COMP").ok().map(|v| v != "0")
820 });
821 ENV.unwrap_or(true) && b128_root()
822}
823
824/// How many 128 roots came out COMPOUND since the last
825/// [`take_b128_compound_hits`] (class `gate-blind-to-feature`).
826static B128_COMPOUND_HITS: std::sync::atomic::AtomicUsize =
827 std::sync::atomic::AtomicUsize::new(0);
828
829/// The compound-128 count since the last call, and zero it.
830pub fn take_b128_compound_hits() -> usize {
831 B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
832}
833
834/// lane-b128hv: whether the 128 superblock root offers its `PARTITION_HORZ`
835/// and `PARTITION_VERT` candidates -- two 128x64 / 64x128 inter blocks, the
836/// same skip-only single-reference/compound machinery the NONE arm ships,
837/// halved ([`search_root_128_rect`], `crate::tile::write_inter_block_128_rect`).
838/// `EC_AV1_B128HV=0` is this arm's attribution control.
839fn b128_rect() -> bool {
840 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
841 crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0")
842 });
843 ENV.unwrap_or(true) && b128_root()
844}
845
846/// lane-rectdq: whether the delta_q symbol group is priced on the root
847/// candidates that really code it. `EC_AV1_RECTDQ=0` is this fix's
848/// attribution control (the pre-lane pricing, where a 128 rect root and the
849/// four-superblock arm were both priced as if the group were free).
850fn rectdq() -> bool {
851 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
852 crate::envflags::var("EC_AV1_RECTDQ").ok().map(|v| v != "0")
853 });
854 ENV.unwrap_or(true)
855}
856
857/// lane-rectdq: what `crate::tile::write_delta_q` spends to move
858/// `CurrentQIndex` from `cur` to `target` at `1 << delta_q_res` steps of
859/// `res` -- the same three pieces that writer codes, in its order: the
860/// `delta_q_abs` symbol of `min(abs, 3)` against the DEFAULT table (the
861/// writer's own `cdfs.delta_q`, which every tile arms fresh, adapts from
862/// exactly this row), the escape literal pair when `abs >= 3`, and the sign
863/// bit when `abs != 0`. Zero when the plan is disarmed (`res <= 0`).
864pub(crate) fn delta_q_bits(target: i32, cur: i32, res: i32) -> f64 {
865 if res <= 0 {
866 return 0.0;
867 }
868 /// spec `DELTA_Q_SMALL`, as in the writer.
869 const DELTA_Q_SMALL: usize = 3;
870 let reduced = (target - cur) / res;
871 let abs = reduced.unsigned_abs() as usize;
872 // A pricing coder, not a sum of table entries: the escape's literal bits
873 // are equiprobable SYMBOLS whose narrowing carries the `EC_MIN_PROB`
874 // floor, so each really costs a little over one bit (class
875 // `price-the-narrowing-not-the-table`). Read off the same
876 // `SymbolEncoder::bits` account the writer's own coder keeps.
877 let mut enc = crate::msac::SymbolEncoder::pricer();
878 enc.reset_bits();
879 enc.symbol_fixed(abs.min(DELTA_Q_SMALL), &cdf::DELTA_Q);
880 if abs >= DELTA_Q_SMALL {
881 let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
882 enc.literal(rem_bits - 1, 3);
883 enc.literal(abs as u32 - ((1u32 << rem_bits) + 1), rem_bits);
884 }
885 if abs != 0 {
886 enc.literal(u32::from(reduced < 0), 1);
887 }
888 enc.bits()
889}
890
891/// [`delta_q_bits`] for the 128 superblock root at `(root_r, root_c)` (in 64
892/// superblock units): the group every root shape but a SKIPPED
893/// `PARTITION_NONE` root codes, since decode.rs' `whole_sb` asks for
894/// `side == write_w == write_h == sb_px` and neither a rect half nor a 64
895/// superblock under a 128 grid is that.
896///
897/// The target is the root's own cell of the `sb_q` grid, exactly the entry
898/// `write_delta_q` indexes. `CurrentQIndex` is NOT knowable in the search --
899/// the writer's `plan.cur` only advances at the roots that really code a
900/// group, and which those are is decided by this very comparison -- so the
901/// PREVIOUS 128 root's target in raster order stands in for it (the frame's
902/// `base_q_idx` at the first root of the frame, which is also the writer's
903/// own per-tile reset). Wrong only where a neighbouring root came out a
904/// skipped NONE block, and then only by the difference of two adjacent tpl
905/// cells.
906fn delta_q_bits_at_root(
907 sb_q: Option<&Vec<u8>>,
908 sb_cols: usize,
909 base_q_idx: u8,
910 res: i32,
911 (root_r, root_c): (usize, usize),
912) -> f64 {
913 if !rectdq() || res <= 0 {
914 return 0.0;
915 }
916 let Some(q) = sb_q.filter(|q| !q.is_empty()) else {
917 return 0.0;
918 };
919 let at = |r: usize, c: usize| i32::from(q[(r * sb_cols + c).min(q.len() - 1)]);
920 let target = at(root_r, root_c);
921 let cur = if root_c >= 2 {
922 at(root_r, root_c - 2)
923 } else if root_r >= 2 {
924 // The last 128 root of the row above, i.e. the previous one in the
925 // writer's raster walk.
926 at(root_r - 2, (sb_cols.saturating_sub(1)) & !1)
927 } else {
928 i32::from(base_q_idx)
929 };
930 delta_q_bits(target, cur, res)
931}
932
933/// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT)
934/// halves since the last take (class `gate-blind-to-feature`).
935static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
936/// The VERT twin of [`B128_HORZ_HITS`].
937static B128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
938
939/// The HORZ-128-root count since the last call, and zero it.
940pub fn take_b128_horz_hits() -> usize {
941 B128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
942}
943
944/// The VERT-128-root count since the last call, and zero it.
945pub fn take_b128_vert_hits() -> usize {
946 B128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
947}
948
949/// Test-only: force the 128 root's rect partition whatever it costs -- 0 off,
950/// 1 `PARTITION_HORZ`, 2 `PARTITION_VERT`. The witness needs it because
951/// synthetic content is where the shape is cheapest to decode-check and the
952/// RD there prefers one whole block; the gate census is the unforced count.
953static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
954
955/// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT).
956#[cfg(test)]
957pub(crate) fn force_b128_rect(which: u8) {
958 FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed);
959}
960
961/// lane-ab128: whether the 128 superblock root offers its four AB shapes --
962/// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one
963/// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128
964/// right) and `_VERT_B` (one 64x128 left, two 64x64 right). Every piece is
965/// the same skip-only single-reference/compound block the NONE and HORZ/VERT
966/// arms ship, at its own footprint ([`search_root_128_ab`],
967/// `crate::tile::write_inter_block_128_rect`). `EC_AV1_B128AB=0` is this
968/// arm's attribution control.
969///
970/// **Off by default** (`EC_AV1_B128AB=1` turns it on): measured on both gates
971/// and it does not pay. The shapes fire 0-2 roots a frame against ~1000 coded
972/// blocks (`EC_AV1_B128_CENSUS`), and every row is flat or 0.1 worse --
973/// long-GOP film A +22.0/-8.5 against a +21.9/-8.6 control, film B +75.8/+0.8
974/// against the same, 12-frame film A +18.1/-6.2 against +18.0/-6.3, film B
975/// +23.1/-3.3 against +23.0/-3.5, screen byte-identical (lane-ab128). The
976/// machinery is written, witnessed sample-exact through both decoders on all
977/// four shapes, and kept for the arm that makes it pay: a non-skip piece (the
978/// 64x64 pieces could carry the 64 root's residual, which is where libaom's
979/// AB shapes earn their keep) or a cheaper partition price.
980fn b128_ab() -> bool {
981 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
982 crate::envflags::var("EC_AV1_B128AB").ok().map(|v| v != "0")
983 });
984 ENV.unwrap_or(false) && b128_root()
985}
986
987/// How many 128 roots the search left as each AB shape since the last take,
988/// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order (class
989/// `gate-blind-to-feature`).
990static B128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
991 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
992
993/// The four per-shape AB-root counts since the last call, and zero them.
994pub fn take_b128_ab_hits() -> [usize; 4] {
995 std::array::from_fn(|i| B128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
996}
997
998/// Test-only: force the 128 root's AB shape whatever it costs -- 0 off, then
999/// 4..=7, the partition symbol itself ([`force_b128_rect`]'s twin; synthetic
1000/// content is where the shapes are cheapest to decode-check and the RD there
1001/// prefers one whole block).
1002static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1003
1004/// Arms [`FORCE_B128_AB`] for the rest of the process (0 off, else 4..=7).
1005#[cfg(test)]
1006pub(crate) fn force_b128_ab(which: u8) {
1007 FORCE_B128_AB.store(which, std::sync::atomic::Ordering::Relaxed);
1008}
1009
1010/// lane-ab128: the three pieces of an AB shape at a 128 root, in the order
1011/// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm
1012/// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B =
1013/// top half, BL, BR; VERT_A = TL, BL, right half; VERT_B = left half, TR, BR.
1014/// Each entry is the piece's own top-left in mode-info units and its
1015/// footprint in samples.
1016pub(crate) fn ab128_pieces(
1017 symbol: usize,
1018 (mi_row, mi_col): (usize, usize),
1019) -> [((usize, usize), (usize, usize)); 3] {
1020 const S: usize = SUPERBLOCK;
1021 let (r, c) = (mi_row, mi_col);
1022 let (r1, c1) = (mi_row + 16, mi_col + 16);
1023 match symbol {
1024 // PARTITION_HORZ_A
1025 4 => [((r, c), (S, S)), ((r, c1), (S, S)), ((r1, c), (S * 2, S))],
1026 // PARTITION_HORZ_B
1027 5 => [((r, c), (S * 2, S)), ((r1, c), (S, S)), ((r1, c1), (S, S))],
1028 // PARTITION_VERT_A
1029 6 => [((r, c), (S, S)), ((r1, c), (S, S)), ((r, c1), (S, S * 2))],
1030 // PARTITION_VERT_B
1031 _ => [((r, c), (S, S * 2)), ((r, c1), (S, S)), ((r1, c1), (S, S))],
1032 }
1033}
1034
1035/// Test-only: take the 128 root's residual arm whatever it costs, so a
1036/// witness clip codes the shape rather than waiting for content on which the
1037/// RD picks it (the same role [`force_sb128`] plays for the superblock size).
1038/// Never read outside `#[cfg(test)]` builds.
1039static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool =
1040 std::sync::atomic::AtomicBool::new(false);
1041
1042/// Test-only twin of [`FORCE_B128_RESIDUAL`] for the PARTITION decision: take
1043/// the 128 root whenever it produced a candidate at all, whatever its four
1044/// cells cost, so a witness codes the block it is about rather than waiting
1045/// for content on which the root also wins its own comparison.
1046static FORCE_B128_ROOT: std::sync::atomic::AtomicBool =
1047 std::sync::atomic::AtomicBool::new(false);
1048
1049/// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a
1050/// forced residual block only reaches the writer if its root is taken.
1051#[cfg(test)]
1052pub(crate) fn force_b128_residual(on: bool) {
1053 FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed);
1054 force_b128_root(on);
1055}
1056
1057/// Arms [`FORCE_B128_ROOT`] for the rest of the process.
1058#[cfg(test)]
1059pub(crate) fn force_b128_root(on: bool) {
1060 FORCE_B128_ROOT.store(on, std::sync::atomic::Ordering::Relaxed);
1061}
1062
1063/// How many 128 roots came out cheaper WITH a residual than skipped, since
1064/// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).
1065static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize =
1066 std::sync::atomic::AtomicUsize::new(0);
1067
1068/// The 128-residual count since the last call, and zero it.
1069pub fn take_b128_residual_hits() -> usize {
1070 B128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1071}
1072
1073/// How many 128x128 `PARTITION_NONE` roots the search took since the last
1074/// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result
1075/// is only attributable once the fire count is known.
1076static B128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1077
1078/// The 128x128-root count since the last call, and zero it.
1079pub fn take_b128_none_hits() -> usize {
1080 B128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1081}
1082
1083/// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq).
1084/// Preset-gated: it re-prices the block once per candidate level, so it buys
1085/// bits with wall (see `crate::speed::RDOQ` for the per-preset table).
1086///
1087/// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser --
1088/// which is what the byte pins are taken under when they name it.
1089fn rdoq_on() -> bool {
1090 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1091 crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0")
1092 });
1093 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ))
1094}
1095
1096/// The rate weight [`crate::tile::rdoq`] trades bits for squared error at, in
1097/// units of one squared AC quantiser step -- the search's own
1098/// [`LAMBDA_SCALE`], so the quantiser and the mode search speak one currency.
1099///
1100/// The per-frame factors the search multiplies onto it ([`key_lambda_factor`],
1101/// [`hidden_lambda_factor`], both 1.0 as shipped) and the per-superblock
1102/// temporal map ([`tpl_lambda_factors`]) are NOT threaded down here:
1103/// corner-cut, ceiling = a superblock the temporal map weighs away from the
1104/// frame average has its coefficients optimised at the frame's weight. The
1105/// upgrade is one `lambda` field on the trial call sites, which is the whole
1106/// mode-search argument list.
1107///
1108/// SWEPT (lane-rdoq, 12-frame `bd_rate_screen_native`, BD vs libaom
1109/// `cpu-used 6` on the three real rows). The bowl is a factor of TWO above
1110/// the mode search's own weight, and it is the same multiplier on all three
1111/// rows:
1112///
1113/// | `EC_AV1_RDOQ_LAMBDA` | film A | film B | screen |
1114/// |---|---|---|---|
1115/// | 0.7 | +27.6 | +39.5 | +29.6 |
1116/// | 1.0 | +26.3 | +37.5 | +29.1 |
1117/// | 1.3 | +25.6 | +37.0 | +28.8 |
1118/// | 1.6 | +24.6 | +35.9 | +28.7 |
1119/// | 2.2 (shipped) | +24.4 | +35.5 | +28.1 |
1120/// | 3.2 | +24.7 | +36.1 | +29.4 |
1121///
1122/// A coefficient's rate is worth twice here what the mode search prices it
1123/// at, and the likeliest reason is that the price is taken against tables
1124/// that have not adapted yet ([`crate::tile::coeff_bits`]): a block coded
1125/// late in a frame whose `txb_skip`/`base` tables have narrowed really costs
1126/// less than the pricer says, and this pass is the one decision taken per
1127/// COEFFICIENT, so it feels that error most. The honest fix is an adapted
1128/// price, not a fitted multiplier; this is the fitted multiplier, and its
1129/// bowl is measured rather than assumed.
1130const RDOQ_LAMBDA_MULT: f64 = 2.2;
1131
1132/// [`RDOQ_LAMBDA_MULT`], or what `EC_AV1_RDOQ_LAMBDA` names (the rate-term
1133/// calibration sweep).
1134fn rdoq_lambda() -> f64 {
1135 static MULT: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
1136 crate::envflags::var("EC_AV1_RDOQ_LAMBDA")
1137 .ok()
1138 .and_then(|v| v.parse().ok())
1139 .unwrap_or(RDOQ_LAMBDA_MULT)
1140 });
1141 lambda_scale() * *MULT
1142}
1143
1144/// [`B64_ROOT`], or what `EC_AV1_B64` names.
1145fn b64_root() -> bool {
1146 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1147 crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0")
1148 });
1149 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))
1150}
1151
1152/// The KEY frame's own 64x64 root (lane-i64): the whole superblock searched
1153/// as ONE intra block -- every mode the 32x32 search offers, one TX_64X64
1154/// luma transform (`TxbSet::Luma64`, whose coded quarter is the 32x32 corner)
1155/// and one TX_32X32 per chroma plane -- and compared against the four 32x32
1156/// quadrants at the same lambda, exactly the shape the inter root
1157/// ([`B64_ROOT`]) takes on an inter frame. The writer has always been able to
1158/// code one (`crate::tile::sb_coeff_key_frame_tile`'s `Superblock::Whole`);
1159/// nothing produced one, so the key frame -- 21.6% of a real film stream --
1160/// coded every superblock split while libaom and rav1e leave 45-54% of theirs
1161/// whole.
1162///
1163/// No CfL (spec `is_cfl_allowed` stops at 32x32, and `search_chroma` gates on
1164/// it), no filter intra (`filter_intra_size_class` has no 64 row) and no
1165/// transform-depth split (the writer's `Superblock::Whole` arm takes a 32x32
1166/// level grid, so only depth 0 is representable) -- the root is refused
1167/// outright on an `allow_intrabc` frame, whose quadrant searches carry DV
1168/// state a discarded trial would desync.
1169///
1170/// Switched off by `EC_AV1_I64=0` in any build.
1171pub(crate) const I64_ROOT: bool = true;
1172
1173/// How many key-frame superblocks were coded as one 64x64 intra block since
1174/// the last [`take_i64_root_hits`], so a gate reports the fire rate rather
1175/// than assuming it (class `gate-blind-to-feature`).
1176/// Index 1 is how many were OFFERED the trial at all, so a gate reads a
1177/// SHARE and not a bare count, and index 2 how many of the whole ones sat on
1178/// a superblock the true frame edge CUTS THROUGH (lane-corner) -- the
1179/// `gate-blind-to-feature` guard for the edge path, which no
1180/// superblock-aligned clip fires at all.
1181static I64_HITS: [std::sync::atomic::AtomicUsize; 3] =
1182 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
1183
1184/// The key-frame `(whole, offered, edge)` 64x64-intra-root counts since the
1185/// last call, and zero them.
1186pub fn take_i64_root_hits() -> [usize; 3] {
1187 std::array::from_fn(|i| I64_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1188}
1189
1190/// [`I64_ROOT`], or what `EC_AV1_I64` names.
1191fn i64_root() -> bool {
1192 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1193 crate::envflags::var("EC_AV1_I64").ok().map(|v| v != "0")
1194 });
1195 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::I64_ROOT))
1196}
1197
1198/// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the
1199/// winner's prediction through one TX_64X64 luma transform and two TX_32X32
1200/// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root
1201/// lane-b64 shipped, so the two can be measured against each other on the
1202/// same build.
1203///
1204/// MEASURED on the native gate (two arms of one build, baseline reproduced to
1205/// the tenth): both film rows improve on both columns -- film A
1206/// +43.0/+15.0 -> +42.9/+14.8, film B +64.7/+34.0 -> +63.3/+31.5 -- and
1207/// SCREEN CAPTURE loses +33.4/-23.8 -> +34.3/-23.4, outside the keep rule's
1208/// +-0.3 screen clause. So the caller gates this off on a screen frame
1209/// (`allow_screen_content_tools`), the same content gate the coding pyramid
1210/// takes: a desktop capture's 64x64 superblocks are flat runs whose skip arm
1211/// already codes them for nothing, and a residual there only spends bits the
1212/// intra/palette tools would have spent better.
1213///
1214/// CENSUS on film B (12 frames, q120, `EC_AV1_BITCENSUS=1` +
1215/// `examples/syntax_census.rs`, both streams read by OUR decoder), off vs on:
1216///
1217/// | | skip-only | + residual |
1218/// |---|---|---|
1219/// | 64x64 share, all frames | 36.4% | 38.3% |
1220/// | 64x64 share, leaf frames | 53.3% | 56.0% |
1221/// | skip area, all frames | 80.4% | 78.8% |
1222/// | skip area, leaf frames | 90.2% | 88.5% |
1223/// | stream bytes | 34,366 | 34,295 |
1224/// | encoder wall | 13.4s | 9.6s |
1225///
1226/// `base_luma_64` enters the leaf frames' top tables at 5.7%, i.e. the
1227/// TX_64X64 coefficients are really being coded. The root wins MORE often
1228/// with a residual to offer (rav1e speed 6's own 64x64 share on this clip is
1229/// 45.2%), which is also why the arm is 28% FASTER despite costing three more
1230/// transforms per superblock: a root that wins is four quadrant searches that
1231/// never run.
1232fn b64_residual() -> bool {
1233 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1234 crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0")
1235 });
1236 ENV.unwrap_or(true) && b64_root()
1237}
1238
1239/// How many 64x64 roots came out cheaper with a residual than skipped, since
1240/// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate
1241/// rather than assuming one (class `gate-blind-to-feature`).
1242static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1243
1244/// The non-skip 64x64-root count since the last call, and zero it.
1245pub fn take_b64_residual_hits() -> usize {
1246 B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1247}
1248
1249/// Whether the 64x64 root also prices COMPOUND candidates (lane-b64b): the
1250/// `LAST` + extra-reference pairs the 32x32 level already offers, at the
1251/// three modes a root can form without a second 64x64 motion search --
1252/// `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` (whose NEW half
1253/// is the vector `search_skip_64`'s own single-reference search already
1254/// found). `NEAREST_NEWMV`/`NEW_NEWMV` need the SECOND reference's own
1255/// `NEWMV` vector, which only a second search per superblock produces -- the
1256/// wall this root exists to save -- so they are not offered here.
1257///
1258/// Off by `EC_AV1_B64COMP=0`, so both arms measure on one build.
1259fn b64_compound() -> bool {
1260 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1261 crate::envflags::var("EC_AV1_B64COMP").ok().map(|v| v != "0")
1262 });
1263 ENV.unwrap_or(true) && b64_root()
1264}
1265
1266/// How many 64x64 roots took a COMPOUND candidate since the last
1267/// [`take_b64_compound_hits`] (class `gate-blind-to-feature`).
1268static B64_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1269
1270/// The compound 64x64-root count since the last call, and zero it.
1271pub fn take_b64_compound_hits() -> usize {
1272 B64_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1273}
1274
1275/// Whether a 64x64 root that codes a residual may SPLIT its luma transform
1276/// (lane-b64b): four TX_32X32 units instead of the one TX_64X64, decided by
1277/// [`commit_inter_luma`] like every other inter block's var-tx, and coded by
1278/// the writer's `Whole64` arm as `txfm_split = 1`. It exists because
1279/// TX_64X64 zeroes everything outside its 32x32 corner, so a root whose
1280/// residual has detail in the other three quadrants cannot code it at all.
1281///
1282/// Off by `EC_AV1_B64VARTX=0`.
1283fn b64_var_tx() -> bool {
1284 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1285 crate::envflags::var("EC_AV1_B64VARTX").ok().map(|v| v != "0")
1286 });
1287 ENV.unwrap_or(true) && b64_root()
1288}
1289
1290/// How many 64x64 roots split their luma transform since the last
1291/// [`take_b64_var_tx_hits`].
1292static B64_VAR_TX_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1293
1294/// The split-luma 64x64-root count since the last call, and zero it.
1295pub fn take_b64_var_tx_hits() -> usize {
1296 B64_VAR_TX_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1297}
1298
1299/// Whether a superblock the true frame edge CUTS THROUGH may be left whole
1300/// (lane-b64b). AV1 asks only that the block's own half is inside
1301/// (`has_cols`/`has_rows`, spec `decode_partition`), and the writer already
1302/// codes that case; what was missing was a trial whose SSE is scored over the
1303/// INSIDE part alone ([`Plane::block_sse`], which clips since lane-sse)
1304/// instead of over the padding the encoder
1305/// invented past the edge. Both gate films are superblock-aligned, so this
1306/// only reaches the user's own arbitrary export sizes.
1307///
1308/// Off by `EC_AV1_B64EDGE=0`.
1309fn b64_edge() -> bool {
1310 edge_root_enabled() && b64_root()
1311}
1312
1313/// What `EC_AV1_B64EDGE` names on its own, without the inter root's own
1314/// preset switch -- the key frame's root ([`I64_ROOT`]) reads the same flag
1315/// but is gated by [`i64_root`].
1316fn edge_root_enabled() -> bool {
1317 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1318 crate::envflags::var("EC_AV1_B64EDGE").ok().map(|v| v != "0")
1319 });
1320 ENV.unwrap_or(true)
1321}
1322
1323/// How many 64x64 roots the frame edge cut through since the last
1324/// [`take_b64_edge_hits`] (class `gate-blind-to-feature`: both gate films are
1325/// superblock-aligned, so nothing but a synthetic size fires this).
1326static B64_EDGE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1327
1328/// The edge 64x64-root count since the last call, and zero it.
1329pub fn take_b64_edge_hits() -> usize {
1330 B64_EDGE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1331}
1332
1333/// Whether the encoder searches loop restoration at all (spec 7.17): one
1334/// Wiener filter per 64x64 luma restoration unit, picked from
1335/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
1336/// test build, like [`lambda_scale`].
1337pub(crate) const RESTORATION: bool = true;
1338
1339/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
1340fn restoration_enabled() -> bool {
1341 match std::env::var("EC_AV1_LR").ok() {
1342 Some(v) if cfg!(test) => v != "0",
1343 _ => crate::speed::at(&crate::speed::RESTORATION),
1344 }
1345}
1346
1347/// libaom's `partition_search_breakout` shape: how many non-zero luma
1348/// coefficients per 256 luma samples a block may code and still be judged
1349/// well enough predicted that the split below it is not worth trying. `0`
1350/// disables the breakout (only the existing all-skip prune applies), which
1351/// is the default until the sweep below justifies otherwise.
1352///
1353/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
1354/// is where this lane's wall would have gone: 1 cuts the three clips'
1355/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
1356/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
1357/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
1358/// encoder's inter quality lives, so `0` ships and the knob stays for a
1359/// future explicit speed preset.
1360pub(crate) const SPLIT_BREAKOUT_COEFFS: usize = 0;
1361
1362/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
1363/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
1364/// out under `threshold * lambda` is not offered the split at all, and a
1365/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
1366/// always, as before this lever.
1367///
1368/// The census is what points here: the split trial runs on nearly every
1369/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
1370/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
1371/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
1372/// points, so the gate has to read the block's own RD cost, not its levels.
1373///
1374/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
1375/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
1376/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
1377/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
1378/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
1379/// the largest threshold whose BD stays inside the +0.3 keep rule on every
1380/// clip.
1381/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on (base
1382/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3): 0.0625 is +16.9/-0.4, +47.0/+19.1,
1383/// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is
1384/// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off
1385/// the screen wall). Neither clears the keep rule; 0.125 stays.
1386pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125;
1387
1388/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
1389fn split_rd_threshold() -> f64 {
1390 static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| {
1391 crate::envflags::var("EC_AV1_SPLIT_RD").ok().and_then(|v| v.parse().ok())
1392 });
1393 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD))
1394}
1395
1396/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
1397/// [`split_rd_threshold`] withholds the split trial.
1398fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
1399 split_rd_breakout_at(split_rd_threshold(), cost, side, lambda)
1400}
1401
1402/// [`split_rd_breakout`] at an explicit threshold -- what the 64x64 root's own
1403/// early-out reads.
1404fn split_rd_breakout_at(t: f64, cost: f64, side: usize, lambda: f64) -> bool {
1405 t > 0.0 && cost < t * lambda * (side * side) as f64
1406}
1407
1408/// The threshold the 64x64 root's early-out uses: [`split_rd_threshold`]
1409/// CLAMPED at the shipped [`SPLIT_RD_THRESHOLD`] (lane-tx64).
1410///
1411/// The 32x32 level is allowed to loosen its breakout with the speed preset
1412/// (`crate::speed::SPLIT_RD` steps to 0.5 at preset 6), but lane-b64 measured
1413/// what that does one size up: at 0.5 a whole superblock is taken at 64x64
1414/// without its four quadrants ever being searched, and film B goes
1415/// +91.5/+53.4 -> +114.6/+71.5. A 64x64 block is four times the area, so the
1416/// same per-pixel threshold withholds four times as much search -- the
1417/// preset's step is priced for the 32 level and does not carry up here.
1418fn b64_breakout_threshold() -> f64 {
1419 split_rd_threshold().min(SPLIT_RD_THRESHOLD)
1420}
1421
1422/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
1423/// build.
1424fn split_breakout_coeffs() -> usize {
1425 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
1426 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
1427 _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT),
1428 }
1429}
1430
1431/// How often each partition decision was taken since the last
1432/// [`take_partition_hits`], so a gate can report how often a new partition
1433/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
1434/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
1435/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
1436static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
1437 std::sync::atomic::AtomicUsize::new(0),
1438 std::sync::atomic::AtomicUsize::new(0),
1439 std::sync::atomic::AtomicUsize::new(0),
1440 std::sync::atomic::AtomicUsize::new(0),
1441];
1442
1443/// Records one such decision.
1444fn partition_hit(which: usize) {
1445 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1446}
1447
1448/// Takes (and clears) the counts.
1449#[cfg(test)]
1450pub(crate) fn take_partition_hits() -> [usize; 4] {
1451 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1452}
1453
1454/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
1455/// rate-distortion trials the block search actually runs, by kind, and where
1456/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
1457/// default, and a measurement build rather than a speed one -- the census
1458/// runs the SAD pre-pass the unpruned search otherwise skips.
1459pub fn census_on() -> bool {
1460 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1461 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
1462}
1463
1464/// What each [`CENSUS`] counter counts.
1465pub const CENSUS_KINDS: [&str; 11] = [
1466 "intra blocks searched (key frame + inter leaves)",
1467 "intra luma mode trials",
1468 "chroma searches",
1469 "chroma mode trials (each = 2 plane trials)",
1470 "tx-depth trials (transform units, depth >= 1)",
1471 "inter 32x32 blocks searched",
1472 "inter block intra-mode trials",
1473 "inter mv candidates (each = 3 mc trials)",
1474 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
1475 " of those, intra won",
1476 " of those, the NEARESTMV trial coded no residual",
1477];
1478
1479/// The census counters themselves, indexed by [`CENSUS_KINDS`].
1480static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
1481 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
1482
1483/// Where the RD winner sat in the SAD ranking, for the luma intra search and
1484/// the chroma mode search -- what says whether a top-N prune would have kept
1485/// the block the search actually chose.
1486static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
1487 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
1488static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
1489 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1490
1491fn census_add(kind: usize, n: usize) {
1492 if census_on() {
1493 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
1494 }
1495}
1496
1497/// Reads (and clears) the census, so a driver can attribute it to its own encode.
1498pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
1499 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
1500 (
1501 std::array::from_fn(|i| take(&CENSUS[i])),
1502 std::array::from_fn(|i| take(&LUMA_RANK[i])),
1503 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
1504 )
1505}
1506
1507/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
1508/// first -- the census's one shared rule, so the luma and chroma histograms
1509/// mean the same thing.
1510fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
1511 scored
1512 .iter()
1513 .filter(|&&(score, mode)| {
1514 mode != winner
1515 && score
1516 < scored
1517 .iter()
1518 .find(|&&(_, m)| m == winner)
1519 .map_or(f64::INFINITY, |&(s, _)| s)
1520 })
1521 .count()
1522}
1523
1524/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
1525/// four cost less. Set from the measurement in the lane report.
1526const SPLIT_BLOCKS: bool = true;
1527
1528/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
1529/// by calling [`encode_key_frame_inner`] both ways.
1530pub(crate) fn split_blocks() -> bool {
1531 SPLIT_BLOCKS
1532}
1533
1534/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
1535/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
1536/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
1537/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
1538/// stream's decode output actually carries 10-bit precision instead of
1539/// silently losing its low 2 bits). The encoder only ever produces values in
1540/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
1541/// decision); `Plane::source` narrows right back to `u8` at its two
1542/// construction sites, a lossless round trip for that range.
1543#[derive(Clone, Debug, PartialEq, Eq)]
1544pub struct Picture {
1545 /// The picture's width in luma samples.
1546 pub width: usize,
1547 /// Its height in luma samples.
1548 pub height: usize,
1549 /// The luma plane, `width * height` samples in raster order.
1550 pub y: Vec<u16>,
1551 /// The U plane, at half the width and half the height.
1552 pub u: Vec<u16>,
1553 /// The V plane, the same shape as U.
1554 pub v: Vec<u16>,
1555}
1556
1557impl Picture {
1558 /// A mid-grey picture of the given size.
1559 #[must_use]
1560 pub fn grey(width: usize, height: usize) -> Self {
1561 Self {
1562 width,
1563 height,
1564 y: vec![128; width * height],
1565 u: vec![128; width * height / 4],
1566 v: vec![128; width * height / 4],
1567 }
1568 }
1569
1570 pub(crate) fn check(&self) -> Result<()> {
1571 if self.width == 0
1572 || !self.width.is_multiple_of(BLOCK)
1573 || !self.height.is_multiple_of(BLOCK)
1574 || !self.height.is_multiple_of(BLOCK)
1575 {
1576 return Err(Error::unsupported(
1577 "AV1 encode",
1578 "the picture must be a whole number of 32x32 blocks in each direction",
1579 ));
1580 }
1581 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1582 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1583 return Err(Error::unsupported(
1584 "AV1 encode",
1585 "each plane must carry one sample per position at 4:2:0",
1586 ));
1587 }
1588 Ok(())
1589 }
1590
1591 /// What the public entry points require of the picture they are handed,
1592 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
1593 /// needs a whole chroma sample per two luma ones) and one sample per
1594 /// position on each plane.
1595 pub(crate) fn check_even(&self) -> Result<()> {
1596 if self.width == 0
1597 || self.height == 0
1598 || !self.width.is_multiple_of(2)
1599 || !self.height.is_multiple_of(2)
1600 {
1601 return Err(Error::unsupported(
1602 "AV1 encode",
1603 "the picture's width and height must each be even and nonzero",
1604 ));
1605 }
1606 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1607 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1608 return Err(Error::unsupported(
1609 "AV1 encode",
1610 "each plane must carry one sample per position at 4:2:0",
1611 ));
1612 }
1613 Ok(())
1614 }
1615
1616 /// This picture, padded by edge replication to the next whole number of
1617 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
1618 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
1619 /// sequence (what the inter tile writer's partition needs on top of
1620 /// that). Identity (a plain clone, not a copy through the replication
1621 /// loop) when the picture is already that size — the multiple-of-32 (or
1622 /// -64) fast path is unchanged.
1623 pub(crate) fn padded_to(&self, align: usize) -> Picture {
1624 let padded_width = self.width.next_multiple_of(align);
1625 let padded_height = self.height.next_multiple_of(align);
1626 if padded_width == self.width && padded_height == self.height {
1627 return self.clone();
1628 }
1629 Picture {
1630 width: padded_width,
1631 height: padded_height,
1632 y: pad_plane(
1633 &self.y,
1634 self.width,
1635 self.height,
1636 padded_width,
1637 padded_height,
1638 ),
1639 u: pad_plane(
1640 &self.u,
1641 self.width / 2,
1642 self.height / 2,
1643 padded_width / 2,
1644 padded_height / 2,
1645 ),
1646 v: pad_plane(
1647 &self.v,
1648 self.width / 2,
1649 self.height / 2,
1650 padded_width / 2,
1651 padded_height / 2,
1652 ),
1653 }
1654 }
1655}
1656
1657/// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8`
1658/// (8-bit only, unchanged this round -- widening the encoder is out of this
1659/// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that
1660/// lets it keep calling [`crate::intra::predict`] now that shape is `u16`
1661/// in and out. A block-sized round-trip through `u16` is exact for 8-bit
1662/// content (every value fits both ways), so this changes no encoder output.
1663#[allow(clippy::too_many_arguments)]
1664fn intra_predict_u8(
1665 mode: u8,
1666 angle_delta: i32,
1667 above: Option<&[u8]>,
1668 left: Option<&[u8]>,
1669 corner: Option<u8>,
1670 bw: usize,
1671 bh: usize,
1672 enable_edge_filter: bool,
1673 smooth_neighbor: bool,
1674 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
1675) {
1676 // Three heap allocations per call became three stack buffers: this runs
1677 // once per mode per trial, and an edge is at most `bw + bh` samples while
1678 // a block is at most `SUPERBLOCK * SUPERBLOCK` (lane-i64: the key frame's
1679 // 64x64 intra root predicts through here too, and reads up to `2 * bw`
1680 // samples above).
1681 let mut above_buf = [0u16; 2 * SUPERBLOCK];
1682 let mut left_buf = [0u16; 2 * SUPERBLOCK];
1683 // lane-av1speed2: a `BLOCK * BLOCK` scratch is 2 KB zeroed on every mode
1684 // trial of every block, and a 4x4 block writes 32 bytes of it. The
1685 // predictor fills every sample it is handed, so the zeros are dead
1686 // either way -- size the scratch to the block instead of to the largest
1687 // block there is.
1688
1689 let widen = |src: &[u8], buf: &mut [u16; 2 * SUPERBLOCK]| {
1690 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1691 *d = u16::from(v);
1692 }
1693 };
1694 if let Some(s) = above {
1695 widen(s, &mut above_buf);
1696 }
1697 if let Some(s) = left {
1698 widen(s, &mut left_buf);
1699 }
1700 let above16 = above.map(|s| &above_buf[..s.len()]);
1701 let left16 = left.map(|s| &left_buf[..s.len()]);
1702 let mut run = |dst16: &mut [u16]| {
1703 crate::intra::predict(
1704 mode,
1705 angle_delta,
1706 above16,
1707 left16,
1708 corner.map(u16::from),
1709 bw,
1710 bh,
1711 enable_edge_filter,
1712 smooth_neighbor,
1713 dst16, fctx,
1714 );
1715 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
1716 *d = s as u8;
1717 }
1718 };
1719 let n = bw * bh;
1720 if n <= 64 {
1721 run(&mut [0u16; 64][..n]);
1722 } else if n <= 256 {
1723 run(&mut [0u16; 256][..n]);
1724 } else if n <= BLOCK * BLOCK {
1725 run(&mut [0u16; BLOCK * BLOCK][..n]);
1726 } else {
1727 run(&mut [0u16; SUPERBLOCK * SUPERBLOCK][..n]);
1728 }
1729}
1730
1731/// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same
1732/// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one
1733/// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode.
1734fn filter_intra_predict_u8(
1735 mode: usize,
1736 above: Option<&[u8]>,
1737 left: Option<&[u8]>,
1738 corner: Option<u8>,
1739 side: usize,
1740 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
1741) {
1742 let mut above_buf = [0u16; 2 * BLOCK];
1743 let mut left_buf = [0u16; 2 * BLOCK];
1744 let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
1745 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1746 *d = u16::from(v);
1747 }
1748 };
1749 if let Some(a) = above {
1750 widen(a, &mut above_buf);
1751 }
1752 if let Some(l) = left {
1753 widen(l, &mut left_buf);
1754 }
1755 let mut dst16 = [0u16; BLOCK * BLOCK];
1756 let n = side * side;
1757 crate::intra::predict_filter_intra(
1758 mode,
1759 above.map(|a| &above_buf[..a.len()]),
1760 left.map(|l| &left_buf[..l.len()]),
1761 corner.map(u16::from),
1762 side,
1763 side,
1764 &mut dst16[..n], fctx,
1765 );
1766 for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) {
1767 *d = v as u8;
1768 }
1769}
1770
1771/// Pads one plane to `(padded_width, padded_height)` by repeating its last
1772/// row and column, so the block coder always sees a whole number of blocks.
1773/// [`crop_plane`] undoes this on the way back out.
1774fn pad_plane<T: Copy + Default>(
1775 source: &[T],
1776 width: usize,
1777 height: usize,
1778 padded_width: usize,
1779 padded_height: usize,
1780) -> Vec<T> {
1781 let mut out = vec![T::default(); padded_width * padded_height];
1782 for row in 0..padded_height {
1783 let src = source[row.min(height - 1) * width..][..width].as_ref();
1784 let dst = &mut out[row * padded_width..][..padded_width];
1785 dst[..width].copy_from_slice(src);
1786 dst[width..].fill(src[width - 1]);
1787 }
1788 out
1789}
1790
1791/// The top-left `width` x `height` region of a plane that is `padded_width`
1792/// wide, which is the render-size crop [`Picture::padded`]'s replication
1793/// exists to let a decoder undo.
1794fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
1795 let mut out = Vec::with_capacity(width * height);
1796 for row in 0..height {
1797 out.extend_from_slice(&source[row * padded_width..][..width]);
1798 }
1799 out
1800}
1801
1802/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
1803/// region a decoder produces, which is the public contract for what a caller
1804/// sees back — the padded planes the encoder coded against never leave this
1805/// module. Identity when the reconstruction is already that size.
1806pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
1807 let reconstruction = &encoded.reconstruction;
1808 let cropped = if reconstruction.width == width && reconstruction.height == height {
1809 reconstruction.clone()
1810 } else {
1811 Picture {
1812 width,
1813 height,
1814 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
1815 u: crop_plane(
1816 &reconstruction.u,
1817 reconstruction.width / 2,
1818 width / 2,
1819 height / 2,
1820 ),
1821 v: crop_plane(
1822 &reconstruction.v,
1823 reconstruction.width / 2,
1824 width / 2,
1825 height / 2,
1826 ),
1827 }
1828 };
1829 Encoded {
1830 stream: encoded.stream.clone(),
1831 modes: encoded.modes.clone(),
1832 inter_block_share: encoded.inter_block_share,
1833 reconstruction: cropped,
1834 tile: encoded.tile.clone(),
1835 mi_cols: encoded.mi_cols,
1836 mi_rows: encoded.mi_rows,
1837 base_q_idx: encoded.base_q_idx,
1838 tx_select: encoded.tx_select,
1839 switchable_motion_mode: encoded.switchable_motion_mode,
1840 screen: encoded.screen,
1841 reduced_tx_set: encoded.reduced_tx_set,
1842 start_cdfs: encoded.start_cdfs.clone(),
1843 next_cdfs: encoded.next_cdfs.clone(),
1844 loop_filter: encoded.loop_filter,
1845 loop_restoration: encoded.loop_restoration,
1846 allow_intrabc: encoded.allow_intrabc,
1847 delta: encoded.delta.clone(),
1848 cdef: encoded.cdef,
1849 }
1850}
1851
1852/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
1853/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
1854#[derive(Clone)]
1855pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
1856
1857impl std::fmt::Debug for CdfSnapshot {
1858 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1859 f.write_str("CdfSnapshot")
1860 }
1861}
1862
1863/// What one call to [`encode_key_frame`] produced.
1864#[derive(Clone, Debug)]
1865pub struct Encoded {
1866 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
1867 /// OBU carrying one tile.
1868 pub stream: Vec<u8>,
1869 /// What a decoder will produce from `stream` — the encoder's own
1870 /// reconstruction, which its prediction was built on.
1871 pub reconstruction: Picture,
1872 /// The luma intra mode each block was coded under, in the order the blocks
1873 /// are coded — raster order among the quadrants of each superblock, and
1874 /// among the four 16x16 blocks of a quadrant that was split.
1875 pub modes: Vec<u8>,
1876 /// The fraction of this frame's 32x32 blocks that were coded inter (any
1877 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
1878 /// for a key frame, which has no such choice — so a caller can tell a
1879 /// frame with no motion worth coding from one that never got the chance.
1880 pub inter_block_share: f64,
1881 /// The tile payload alone, undecorated by any OBU framing, and the frame
1882 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
1883 /// `crate::decode`'s tests are the only reader; a real decoder gets these
1884 /// off the wire by parsing `stream`'s OBUs instead.
1885 pub(crate) tile: Vec<u8>,
1886 pub(crate) mi_cols: u32,
1887 pub(crate) mi_rows: u32,
1888 pub(crate) base_q_idx: u8,
1889 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
1890 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
1891 /// and reading it off `stream`'s header is what `decode_stream` does. A
1892 /// test that decodes `tile` directly must pass this one along, or it reads
1893 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
1894 /// block.
1895 pub(crate) tx_select: bool,
1896 /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the
1897 /// bit that makes every eligible single-reference inter block carry a
1898 /// `motion_mode` symbol. Same contract as `tx_select` above: a test
1899 /// decoding `tile` directly must pass it along or it desyncs at the
1900 /// first eligible block.
1901 pub(crate) switchable_motion_mode: bool,
1902 /// The CDF state this frame's tile writer started from -- the defaults
1903 /// for a key frame and for the first inter frame, and the previous
1904 /// frame's stored tables after that. A test that decodes `tile` directly
1905 /// must feed the decoder this, exactly as `decode_stream` feeds it what
1906 /// the frame's `primary_ref_frame` slot holds (same class as
1907 /// `tx_select`: a header bit a raw tile decode cannot guess).
1908 pub(crate) start_cdfs: CdfSnapshot,
1909 /// What this frame stores into the slots it refreshes (spec 7.20,
1910 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
1911 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
1912 /// started from when it is on.
1913 pub(crate) next_cdfs: CdfSnapshot,
1914 /// This frame header's chosen deblocking parameters
1915 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
1916 /// picture the decoder produces UNDER them, so a test that decodes
1917 /// `tile` directly must pass these along, exactly as it must `tx_select`
1918 /// (class: test asserts against a stale header).
1919 pub(crate) loop_filter: LoopFilterParams,
1920 /// This frame header's chosen CDEF parameters, threaded for the same
1921 /// reason as `loop_filter`.
1922 pub(crate) cdef: CdefParams,
1923 /// This frame header's `allow_screen_content_tools`
1924 /// ([`screen_content`]) -- every intra block of the tile carries the two
1925 /// palette-mode symbols under it, so a raw tile decode that guessed
1926 /// `false` would desync at the first block (same class as `tx_select`).
1927 pub(crate) screen: bool,
1928 /// This frame header's own `reduced_tx_set` (spec 5.9.2) -- the bit that
1929 /// picks the inter `tx_type` alphabets AND, on an inter block, the
1930 /// allowance the chroma transform's inherited type reduces against
1931 /// ([`crate::decode::reduce_inherited_chroma_tx_type`]). A raw tile
1932 /// decode that guesses `true` here mis-derives every inherited chroma
1933 /// type on a `reduced_tx_set = 0` frame (lane-intertx; same class as
1934 /// `tx_select`/`screen` above).
1935 pub(crate) reduced_tx_set: bool,
1936 /// This frame header's chosen loop restoration parameters, threaded for
1937 /// the same reason as `loop_filter` -- and doubly so: the per-unit
1938 /// filters themselves are coded in `tile`, so a decode of it under a
1939 /// stale `RESTORE_NONE` header desyncs at the first superblock.
1940 pub(crate) loop_restoration: LoopRestorationParams,
1941 /// This frame header's `allow_intrabc` -- every intra block of the tile
1942 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
1943 /// guessed `false` would desync at the first block (same class as
1944 /// `screen`/`tx_select`).
1945 pub(crate) allow_intrabc: bool,
1946 /// This frame header's `delta_q_params`/`delta_lf_params` (spec
1947 /// 5.9.17/5.9.18) -- with `delta_q_present` every superblock's first
1948 /// coded block carries a `delta_qindex` symbol group, so a raw tile
1949 /// decode that guessed the defaults desyncs at the first superblock
1950 /// (same class as `screen`/`tx_select`).
1951 pub(crate) delta: ec_av1_syntax::DeltaParams,
1952}
1953
1954thread_local! {
1955 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
1956 /// for on the last key frame encoded on this thread -- read by the gates,
1957 /// which print it beside the block counts (class `gate-blind-to-feature`).
1958 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
1959}
1960
1961/// [`IBC_SHARE`] for the last key frame encoded on this thread.
1962#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1963pub(crate) fn intrabc_source_share() -> f64 {
1964 IBC_SHARE.with(std::cell::Cell::get)
1965}
1966
1967thread_local! {
1968 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
1969 /// header offers the per-frame `allow_screen_content_tools` bit at all.
1970 /// Armed once by the key frame ([`encode_key_frame_inner`], from
1971 /// [`screen_content`]) and read by every header builder after it, so that
1972 /// the inter frames of a screen sequence lay their headers out the same
1973 /// way the sequence header the key frame wrote says they do -- a per-call
1974 /// parameter would have to thread through `inter_frame_headers`' four
1975 /// public entry points and every hand-built-stream test that calls them.
1976 /// A sequence with no screen content leaves this false and writes exactly
1977 /// the bits it wrote before this lane.
1978 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1979}
1980
1981thread_local! {
1982 /// Overrides [`screen_content`] for the calling thread, which is what the
1983 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
1984 /// codes every block losslessly, so both arms of a mode ablation reach
1985 /// infinite PSNR and the ablation measures nothing at all (the
1986 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
1987 /// variable cannot do this -- the tests run in one process, in parallel.
1988 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1989}
1990
1991thread_local! {
1992 /// What the last [`encode_sequence_with_ctx`] call on this thread coded
1993 /// under, AFTER the content gate: the pyramid, or `None` for a stream
1994 /// that stayed flat. Read by the BD gates, which print the requested and
1995 /// the effective pyramid side by side -- a screen clip requests one and
1996 /// codes flat, and that difference is the gate (class
1997 /// `gate-blind-to-feature`).
1998 static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> =
1999 const { std::cell::Cell::new(None) };
2000}
2001
2002/// The pyramid the last sequence coded on this thread was EFFECTIVELY under.
2003#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2004pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> {
2005 LAST_SEQ_PYRAMID.with(std::cell::Cell::get)
2006}
2007
2008#[cfg(test)]
2009pub(crate) fn force_screen(value: Option<bool>) {
2010 SCREEN_FORCE.with(|c| c.set(value));
2011}
2012
2013// lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE
2014// ablation can measure the mode search alone. Setting it also clears the
2015// sequence header's own `enable_filter_intra` bit, so the stream the arm
2016// writes is exactly the one this encoder wrote before the lane.
2017#[cfg(test)]
2018thread_local! {
2019 static FILTER_INTRA_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
2020}
2021
2022#[cfg(test)]
2023pub(crate) fn force_filter_intra(value: Option<bool>) {
2024 FILTER_INTRA_FORCE.with(|c| c.set(value));
2025}
2026
2027pub(crate) fn arm_seq_screen(on: bool) {
2028 SEQ_SCREEN.with(|c| c.set(on));
2029}
2030
2031fn seq_screen() -> bool {
2032 SEQ_SCREEN.with(std::cell::Cell::get)
2033}
2034
2035/// How many distinct colours a 16x16 luma block may hold and still count as
2036/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
2037/// `av1_set_screen_content_options` bound is 4, which separates nothing on
2038/// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against
2039/// the variance floor below on the five gate clips at BOTH the native crop
2040/// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of
2041/// the frame is the widest-margin split of those ten rows -- every
2042/// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5
2043/// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6%
2044/// native and 17.9% scaled.
2045fn screen_colors() -> usize {
2046 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2047 *N.get_or_init(|| {
2048 std::env::var("EC_AV1_SCREEN_COLORS")
2049 .ok()
2050 .and_then(|v| v.parse().ok())
2051 .unwrap_or(16)
2052 })
2053}
2054
2055/// The reciprocal of the frame area those blocks must cover, in tenths --
2056/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth;
2057/// 8 (an eighth) is the midpoint of the two populations
2058/// `probe_screen_detect` measures at the colour bound and variance floor
2059/// around it. `EC_AV1_SCREEN_PCT`.
2060fn screen_pct() -> usize {
2061 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2062 *N.get_or_init(|| {
2063 std::env::var("EC_AV1_SCREEN_PCT")
2064 .ok()
2065 .and_then(|v| v.parse().ok())
2066 .unwrap_or(10)
2067 })
2068}
2069
2070/// The per-pixel variance a few-colour block must clear before it counts as
2071/// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its
2072/// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it
2073/// a smooth dark film frame is all few-colour blocks and reads as a desktop
2074/// capture -- which is exactly what this detector did until 2026-09-07, when
2075/// it called BOTH real films screen content on 48/48 frames, priced every
2076/// coefficient against the default CDFs and ran the palette search over
2077/// film. `probe_screen_detect`: at 16 colours the floor takes both films
2078/// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to
2079/// 23.6%.
2080fn screen_var() -> u64 {
2081 static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
2082 *N.get_or_init(|| {
2083 std::env::var("EC_AV1_SCREEN_VAR")
2084 .ok()
2085 .and_then(|v| v.parse().ok())
2086 .unwrap_or(16)
2087 })
2088}
2089
2090/// How many frames [`screen_content`] said yes/no to, so a gate can print
2091/// whether the detector fired at all (class `gate-blind-to-feature`).
2092pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
2093 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
2094
2095/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
2096/// the distinct colours of every 16x16 block and turn the screen-content
2097/// tools on when the blocks holding between 2 and [`screen_colors`] of them
2098/// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the
2099/// frame. `width` is the plane's
2100/// stride, `true_*` the frame's real (decodable) extent.
2101fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
2102 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
2103 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2104 return forced;
2105 }
2106 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
2107 let on = v != "0";
2108 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2109 return on;
2110 }
2111 let (blk, limit, floor) = (16usize, screen_colors(), screen_var());
2112 let mut counted = 0usize;
2113 for by in (0..true_height).step_by(blk) {
2114 for bx in (0..true_width).step_by(blk) {
2115 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
2116 let mut seen = [false; 256];
2117 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
2118 for row in 0..h {
2119 for col in 0..w {
2120 let v = y[(by + row) * width + bx + col];
2121 sum += u64::from(v);
2122 sq += u64::from(v) * u64::from(v);
2123 if !seen[usize::from(v)] {
2124 seen[usize::from(v)] = true;
2125 colors += 1;
2126 }
2127 }
2128 }
2129 // Per-pixel variance over the block's real (edge-clipped) extent.
2130 let n = (h * w) as u64;
2131 let var = (sq - sum * sum / n) / n;
2132 if colors > 1 && colors <= limit && var > floor {
2133 counted += 1;
2134 }
2135 }
2136 }
2137 let on = counted * blk * blk * screen_pct() > true_width * true_height;
2138 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2139 on
2140}
2141
2142/// Whether this SOURCE picture reads as screen content, for a caller that has
2143/// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`]
2144/// gates its coding pyramid on this (a desktop capture keeps the flat
2145/// one-in-one-out structure the BD gate measured it on, camera material takes
2146/// the mini-GOP). The key frame runs the same detector again when it builds
2147/// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to
2148/// count, so this probe undoes its own tick and leaves the gate prints
2149/// reading one detection per coded frame.
2150pub(crate) fn picture_is_screen(picture: &Picture) -> bool {
2151 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
2152 let on = screen_content(&y, picture.width, picture.width, picture.height);
2153 SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2154 on
2155}
2156
2157/// The sequence and frame headers a picture of this size is coded under: one
2158/// tile, one transform size per block, no in-loop filter parameters yet
2159/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
2160/// CDEF strengths in once the tile is coded), no CDF adaptation
2161/// and no tool the tile writer does not code.
2162///
2163/// # Errors
2164/// Returns an error when the picture is larger than the 16-bit frame size the
2165/// sequence header carries.
2166pub fn key_frame_headers(
2167 width: usize,
2168 height: usize,
2169 base_q_idx: u8,
2170) -> Result<(SequenceHeader, FrameHeader)> {
2171 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
2172}
2173
2174/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
2175/// studio (limited) range: what this crate's sequence header carried before
2176/// [`crate::encoder`]'s facade could configure it, and what
2177/// [`key_frame_headers`] still asks for.
2178fn unspecified_color_config() -> ColorConfig {
2179 ColorConfig {
2180 bit_depth: 8,
2181 mono_chrome: false,
2182 num_planes: 3,
2183 color_primaries: 2,
2184 transfer_characteristics: 2,
2185 matrix_coefficients: 2,
2186 color_range: false,
2187 subsampling_x: 1,
2188 subsampling_y: 1,
2189 chroma_sample_position: ChromaSamplePosition::Unknown,
2190 separate_uv_delta_q: false,
2191 }
2192}
2193
2194/// [`key_frame_headers`] with the sequence header's colour config named
2195/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
2196/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
2197/// which is all a player picks a colour transform from and which
2198/// [`crate::encoder::Colour`] is the facade's own name for.
2199///
2200/// # Errors
2201/// The same as [`key_frame_headers`].
2202pub(crate) fn key_frame_headers_colour(
2203 width: usize,
2204 height: usize,
2205 base_q_idx: u8,
2206 color_config: ColorConfig,
2207) -> Result<(SequenceHeader, FrameHeader)> {
2208 let bits = |n: usize| -> Result<u32> {
2209 let n = u32::try_from(n).map_err(|_| too_large())?;
2210 if n == 0 || n > 1 << 16 {
2211 return Err(too_large());
2212 }
2213 Ok((32 - (n - 1).leading_zeros()).max(1))
2214 };
2215 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
2216 let (w, h) = (width as u32, height as u32);
2217 let seq = SequenceHeader {
2218 seq_profile: 0,
2219 operating_points: vec![OperatingPoint {
2220 seq_level_idx: 8,
2221 ..OperatingPoint::default()
2222 }],
2223 frame_width_bits,
2224 frame_height_bits,
2225 max_frame_width: w,
2226 max_frame_height: h,
2227 use_128x128_superblock: sb128_on(),
2228 // lane-fintra: the encoder's intra search offers the five recursive
2229 // filter-intra modes on eligible blocks, so the sequence bit is set
2230 // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both
2231 // off and restores the streams this encoder wrote before the lane).
2232 enable_filter_intra: filter_intra_on(),
2233 enable_intra_edge_filter: false,
2234 enable_order_hint: true,
2235 order_hint_bits: 7,
2236 enable_superres: false,
2237 // spec 5.9.19: with the sequence bit set every frame header carries
2238 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
2239 // pair for the whole frame, chosen by `crate::filter_search` -- so no
2240 // `cdef_idx` literal is coded in the tile and a frame that wants no
2241 // CDEF simply carries zero strengths.
2242 enable_cdef: true,
2243 enable_restoration: true,
2244 // SELECT (2) when this sequence's key frame detected screen content
2245 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
2246 // is then coded in every frame header, and only the frames that want
2247 // the palette syntax set it. 0 -- the forced-off form, no bit at all
2248 // -- otherwise, which is what every non-screen stream this encoder
2249 // writes still carries.
2250 seq_force_screen_content_tools: if seq_screen() {
2251 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
2252 } else {
2253 0
2254 },
2255 seq_force_integer_mv: 0,
2256 color_config,
2257 still_picture: false,
2258 reduced_still_picture_header: false,
2259 timing_info: None,
2260 decoder_model_info: None,
2261 initial_display_delay_present_flag: false,
2262 operating_point: 0,
2263 operating_point_idc: 0,
2264 frame_id_numbers_present_flag: false,
2265 delta_frame_id_length: 0,
2266 additional_frame_id_length: 0,
2267 enable_interintra_compound: false,
2268 enable_masked_compound: false,
2269 // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
2270 // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
2271 // header is byte-identical to the streams before this lane.
2272 enable_warped_motion: warp_on(),
2273 enable_dual_filter: false,
2274 enable_jnt_comp: false,
2275 enable_ref_frame_mvs: false,
2276 film_grain_params_present: false,
2277 };
2278 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
2279 // own (true, unpadded) width and height, not from any block-grid
2280 // alignment — a decoder derives these straight from `frame_width`/
2281 // `frame_height` below, so this must match it exactly.
2282 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
2283 let header = FrameHeader {
2284 frame_type: FrameType::Key,
2285 frame_is_intra: true,
2286 show_frame: true,
2287 error_resilient_mode: true,
2288 // The tile writer keeps the same CDF state the decoder does and
2289 // updates it in the same order, so the frame lets the decoder adapt.
2290 disable_cdf_update: false,
2291 // Nothing reads the state this frame leaves behind: a key frame always
2292 // starts from the defaults, and this encoder emits one frame.
2293 disable_frame_end_update_cdf: true,
2294 force_integer_mv: true,
2295 refresh_frame_flags: 0xFF,
2296 primary_ref_frame: PRIMARY_REF_NONE,
2297 frame_width: w,
2298 frame_height: h,
2299 upscaled_width: w,
2300 render_width: w,
2301 render_height: h,
2302 mi_cols,
2303 mi_rows,
2304 tile_info: TileInfo {
2305 uniform_spacing: true,
2306 cols: 1,
2307 rows: 1,
2308 mi_col_starts: vec![0, mi_cols],
2309 mi_row_starts: vec![0, mi_rows],
2310 tile_size_bytes: 1,
2311 ..TileInfo::default()
2312 },
2313 quantization: QuantizationParams {
2314 base_q_idx,
2315 ..QuantizationParams::default()
2316 },
2317 tx_mode: TxMode::Largest,
2318 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
2319 // intra transform below 32x32, not only 16x16 -- the set this crate
2320 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
2321 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
2322 // so a decoder honouring the header picks the same CDF the writer
2323 // used only if this is set here too, not only on the inter variant
2324 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
2325 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
2326 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
2327 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
2328 // the arithmetic coder's `rng` register from the very first 8x8-leaf
2329 // luma transform onward with no symbol value ever differing.
2330 reduced_tx_set: true,
2331 ..FrameHeader::default()
2332 };
2333 Ok((seq, header))
2334}
2335
2336/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
2337/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
2338/// 1 still holds the key frame however long the GOP runs.
2339pub const GOLDEN_SLOT: u8 = 1;
2340
2341/// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every inter
2342/// frame this encoder writes carries. `EC_AV1_INTERP=smooth|sharp` codes the
2343/// EIGHTTAP_SMOOTH / EIGHTTAP_SHARP kernel instead of the default REGULAR --
2344/// one filter for the whole frame, which is what libaom does on this content
2345/// too (`lanes/obmc3.report.md` read `switchable_interp 0/0` out of its own
2346/// stream, so a per-BLOCK filter search has no bits to win). The kernel
2347/// reaches the search, the trials and the recon through
2348/// `FrameCtx::interp_filter`, so the stream a decoder reads and the
2349/// prediction the search priced are the same one.
2350/// A PROCESS-GLOBAL [`frame_interp_filter`] override that wins over the
2351/// environment (`u8::MAX` = unset), the shape [`set_inter_tx_search`] has:
2352/// the witness that has to see a non-REGULAR kernel coded and decoded turns
2353/// it on through this while holding [`crate::speed::knob_write`].
2354static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 =
2355 std::sync::atomic::AtomicU8::new(u8::MAX);
2356
2357/// Sets [`INTERP_OVERRIDE`]; `None` clears it.
2358#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
2359pub(crate) fn set_frame_interp(filter: Option<ec_av1_syntax::InterpolationFilter>) {
2360 INTERP_OVERRIDE.store(
2361 filter.map_or(u8::MAX, |f| f as u8),
2362 std::sync::atomic::Ordering::Relaxed,
2363 );
2364}
2365
2366fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter {
2367 use ec_av1_syntax::InterpolationFilter as F;
2368 match INTERP_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
2369 0 => return F::Eighttap,
2370 1 => return F::EighttapSmooth,
2371 2 => return F::EighttapSharp,
2372 _ => {}
2373 }
2374 static ENV: std::sync::LazyLock<Option<F>> = std::sync::LazyLock::new(|| {
2375 crate::envflags::var("EC_AV1_INTERP").ok().map(|v| match v.as_str() {
2376 "smooth" => F::EighttapSmooth,
2377 "sharp" => F::EighttapSharp,
2378 _ => F::Eighttap,
2379 })
2380 });
2381 ENV.unwrap_or(F::Eighttap)
2382}
2383
2384/// The frame header for a shown inter frame that predicts from the single
2385/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
2386/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
2387/// reused verbatim: an inter frame never changes the sequence.
2388///
2389/// # Errors
2390/// Returns an error under the same conditions as [`key_frame_headers`].
2391pub fn inter_frame_headers(
2392 width: usize,
2393 height: usize,
2394 base_q_idx: u8,
2395 order_hint: u32,
2396 last_slot: u8,
2397) -> Result<(SequenceHeader, FrameHeader)> {
2398 inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
2399}
2400
2401/// [`inter_frame_headers`] with the three slots named apart: the one read as
2402/// `LAST_FRAME`, the one this frame refreshes, and the one read as
2403/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
2404/// so that the frame two back is still intact in the slot this one is about
2405/// to overwrite -- read before write, spec 7.20's decode order.
2406///
2407/// # Errors
2408/// As [`inter_frame_headers`].
2409pub fn inter_frame_headers_slots(
2410 width: usize,
2411 height: usize,
2412 base_q_idx: u8,
2413 order_hint: u32,
2414 last_slot: u8,
2415 self_slot: u8,
2416 altref_slot: u8,
2417) -> Result<(SequenceHeader, FrameHeader)> {
2418 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
2419 let header = FrameHeader {
2420 frame_type: FrameType::Inter,
2421 frame_is_intra: false,
2422 show_frame: true,
2423 error_resilient_mode: false,
2424 disable_cdf_update: false,
2425 // The tile writer hands its end-of-tile tables to the next frame
2426 // (`encode_sequence_with_ctx`), so the frame stores them the way the
2427 // decoder will load them (spec 7.20).
2428 disable_frame_end_update_cdf: false,
2429 force_integer_mv: false,
2430 order_hint,
2431 primary_ref_frame: 0,
2432 refresh_frame_flags: 1 << self_slot,
2433 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
2434 // names the slot this frame both predicts from and refreshes;
2435 // GOLDEN names slot 1, which the key frame wrote when it refreshed
2436 // all eight and which no inter frame ever overwrites, so it holds
2437 // the key frame's own picture for the whole GOP.
2438 ref_frame_idx: {
2439 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
2440 idx[3] = GOLDEN_SLOT;
2441 idx[6] = altref_slot;
2442 idx
2443 },
2444 // lane-hpmv: libaom's own rule (`av1_pick_and_set_high_precision_mv`:
2445 // `use_hp = qindex < HIGH_PRECISION_MV_QTHRESH`), with this crate's
2446 // threshold in [`HP_MV_QTHRESH`]. `force_integer_mv` is false in
2447 // every frame this constructor builds, so no further guard is needed.
2448 allow_high_precision_mv: high_precision_mv_at(base_q_idx),
2449 // A FIXED frame-level filter, so no block codes an `interp_filter`
2450 // symbol. lane-obmc3 instrumented whether that costs anything: a
2451 // libaom `cpu-used 6` crf 41 stream of the long-GOP film B window
2452 // (45941 B, the same point `lanes/libcen.report.md` matched) read
2453 // back through `EC_AV1_BITCENSUS=1 syntax_census` codes
2454 // `switchable_interp 0/0` in EVERY frame -- libaom picks a fixed
2455 // frame filter here too, so there are ZERO per-block filter bits at
2456 // stake on this content and the per-block switchable search was not
2457 // built (the charter's premise that libaom codes switchable interp
2458 // per block on film B is refuted by its own stream).
2459 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
2460 // lane-av1obmc: with this bit set every single-reference inter block
2461 // libaom's `motion_mode_allowed` accepts carries a `motion_mode`
2462 // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion`
2463 // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied
2464 // to the OBMC knob rather than always on: with every block choosing
2465 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
2466 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
2467 // and stays byte-identical to the streams before this lane.
2468 // lane-av1obmc2: the warp knob joins that disjunction, and turns on
2469 // `allow_warped_motion` besides -- which is what makes an eligible
2470 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
2471 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
2472 is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC")
2473 || warp_on(),
2474 allow_warped_motion: warp_on(),
2475 use_ref_frame_mvs: false,
2476 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
2477 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
2478 // set this crate carries a table for at 16x16 (see
2479 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
2480 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
2481 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
2482 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
2483 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
2484 // path) -- with this flag set, `get_tx_set`'s intra branch returns
2485 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
2486 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
2487 reduced_tx_set: true,
2488 ..key
2489 };
2490 Ok((seq, header))
2491}
2492
2493fn too_large() -> Error {
2494 Error::unsupported(
2495 "AV1 encode",
2496 "the picture is larger than a frame size can carry",
2497 )
2498}
2499
2500/// One plane of the picture being coded, and the reconstruction being built
2501/// beside it.
2502/// What one committed 4x4 cell left behind for the coefficient contexts of
2503/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
2504/// is the same state decode.rs records.
2505#[derive(Clone, Copy, Default, PartialEq, Eq)]
2506struct CoefCtx {
2507 /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
2508 level: u8,
2509 /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
2510 /// the DC itself was zero (tile.rs `dc_vote`).
2511 dc: i8,
2512}
2513
2514/// One plane's coefficient contexts, committed in CODING ORDER: the search
2515/// prices partition TREES, so the neighbour state a candidate reads has to be
2516/// whatever the blocks coded before it left -- the parent's committed
2517/// neighbours for a tree's first child, the just-committed sibling for the
2518/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
2519/// writer's two running bands is what makes that fall out: a trial commits
2520/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
2521/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
2522/// to its left is exactly what the tile writer's `Neighbours` bands will hold
2523/// when it gets there.
2524///
2525/// Before this map the pricer took both contexts as zero, which is exact for
2526/// a luma transform covering its whole block and the largest remaining row of
2527/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
2528#[derive(Default)]
2529struct CoefCtxMap {
2530 cells: Vec<CoefCtx>,
2531 stride: usize,
2532 /// Whether the transforms being priced right now are SMALLER than the
2533 /// block they sit in -- a `TxMode::Select` depth split
2534 /// ([`Plane::code_tx_depth`]) or an inter var-tx split
2535 /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
2536 /// trial cannot tell, and it is what decides whether luma reads context 0
2537 /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
2538 tu_split: bool,
2539}
2540
2541/// Whether [`Plane::block_sse`] scores a block the true frame edge cuts
2542/// through over its INSIDE part alone. On; `EC_AV1_EDGESSE=0` restores the
2543/// padding-inclusive score the search used before lane-sse, which is how the
2544/// before/after arms of the straddling gate rows are read off ONE binary.
2545fn edge_sse() -> bool {
2546 static ENV: std::sync::LazyLock<Option<bool>> =
2547 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGESSE").ok().map(|v| v != "0"));
2548 ENV.unwrap_or(true)
2549}
2550
2551/// Whether [`Plane::block_sse`] counts the blocks the true frame edge cuts
2552/// through and the share of their raw squared error that sat in the padding
2553/// (`EC_AV1_EDGE_CENSUS=1`). Off by default: only edge blocks would pay for
2554/// it, but the numbers are an instrument, not a decision (class
2555/// `gate-blind-to-feature` -- both gate films are superblock-aligned, so
2556/// without this census no gate row can say the clip fires at all).
2557fn edge_census() -> bool {
2558 static ENV: std::sync::LazyLock<bool> =
2559 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1"));
2560 *ENV
2561}
2562
2563/// Per block side (indexed by `side.trailing_zeros()`, so 2 is 4x4 and 7 is
2564/// 128x128): how many scores clipped, the inside squared error they kept and
2565/// the padding squared error they dropped.
2566static EDGE_SCORES: [[std::sync::atomic::AtomicU64; 3]; 8] =
2567 [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 8];
2568
2569/// One clipped score, for [`take_edge_census`].
2570fn record_edge_score(side: usize, inside: u64, padding: u64) {
2571 let row = &EDGE_SCORES[(side.trailing_zeros() as usize).min(7)];
2572 row[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2573 row[1].fetch_add(inside, std::sync::atomic::Ordering::Relaxed);
2574 row[2].fetch_add(padding, std::sync::atomic::Ordering::Relaxed);
2575}
2576
2577/// The straddling-block census since the last call, and zero it: one
2578/// `(side, scores, inside_sse, padding_sse)` row per block size that fired.
2579#[must_use]
2580pub fn take_edge_census() -> Vec<(usize, u64, u64, u64)> {
2581 EDGE_SCORES
2582 .iter()
2583 .enumerate()
2584 .filter_map(|(log2, row)| {
2585 let n = row[0].swap(0, std::sync::atomic::Ordering::Relaxed);
2586 let inside = row[1].swap(0, std::sync::atomic::Ordering::Relaxed);
2587 let padding = row[2].swap(0, std::sync::atomic::Ordering::Relaxed);
2588 (n != 0).then_some((1usize << log2, n, inside, padding))
2589 })
2590 .collect()
2591}
2592
2593struct Plane<'a> {
2594 source: &'a [u8],
2595 reconstruction: Vec<u8>,
2596 width: usize,
2597 height: usize,
2598 /// The frame's true, decodable extent in this plane's own units --
2599 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
2600 /// not `width`/`height` above, which is the padded coding-surface size.
2601 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
2602 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
2603 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
2604 /// this bound, even though the padded reconstruction buffer holds real
2605 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
2606 /// those instead of stopping here is what desyncs prediction at the true
2607 /// edge.
2608 true_width: usize,
2609 true_height: usize,
2610 /// This plane's own tile's pixel bounds, in this plane's units -- the
2611 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
2612 /// prediction never reaches across a tile edge even though the
2613 /// neighbouring tile's real samples sit right there in the shared
2614 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
2615 /// leaves every edge exactly as it was before tiles existed.
2616 tile_x0: usize,
2617 tile_y0: usize,
2618 tile_x1: usize,
2619 tile_y1: usize,
2620 /// [`CoefCtxMap`]: what the blocks already committed left for the
2621 /// coefficient contexts of the ones still being priced. Sized on the
2622 /// first commit, so a plane literal does not have to know its own extent
2623 /// twice.
2624 ctx: CoefCtxMap,
2625}
2626
2627impl Plane<'_> {
2628 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
2629 /// called at every superblock of the frame-raster search with the rect
2630 /// of the tile that superblock belongs to.
2631 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
2632 self.tile_x0 = x0;
2633 self.tile_y0 = y0;
2634 self.tile_x1 = x1.min(self.width);
2635 self.tile_y1 = y1.min(self.height);
2636 }
2637 /// The reconstructed samples a block at `(x, y)` predicts from: the row
2638 /// above it, the column to its left and the sample between them, each
2639 /// missing where the block sits against an edge of the frame.
2640 ///
2641 /// `reach` says whether the samples above the block's right and below its
2642 /// left are decoded, which is what a directional mode reads into; where
2643 /// they are not, or where the frame ends first, the edge is shorter and
2644 /// the predictor repeats its last sample, exactly as the decoder's clamp
2645 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
2646 /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and
2647 /// a free per mode per block, on the search's hottest path -- while an
2648 /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same
2649 /// samples, on the caller's stack.
2650 fn edges_into<'a>(
2651 &self,
2652 x: usize,
2653 y: usize,
2654 side: usize,
2655 reach: Reach,
2656 above_buf: &'a mut [u8; 2 * SUPERBLOCK],
2657 left_buf: &'a mut [u8; 2 * SUPERBLOCK],
2658 ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) {
2659 // Even a block's *own* edge is clamped to the true frame bound, not
2660 // just a `reach` extension: libaom's `av1_predict_intra_block`
2661 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
2662 // this block's own right/bottom to the frame edge -- from
2663 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
2664 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
2665 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
2666 // samples the row/column above/left holds before the decoder starts
2667 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
2668 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
2669 // extent straddles that edge legally (`has_half`) -- the transform
2670 // still covers the whole block, but prediction does not get to read
2671 // real reconstructed pixels past the true edge for its own row/column,
2672 // only for the padded tail it invents.
2673 let own_across = x + side.min(self.true_width.saturating_sub(x));
2674 let across = if reach.above_right {
2675 own_across + side.min(self.true_width.saturating_sub(own_across))
2676 } else {
2677 own_across
2678 }
2679 .min(self.width);
2680 let own_down = y + side.min(self.true_height.saturating_sub(y));
2681 let down = if reach.below_left {
2682 own_down + side.min(self.true_height.saturating_sub(own_down))
2683 } else {
2684 own_down
2685 }
2686 .min(self.height);
2687 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
2688 // whose own origin already sits past the true edge -- only reachable
2689 // through a partition trial priced for comparison on a split this
2690 // frame's straddling quadrant will go on to refuse (see
2691 // `a_picture_off_the_block_grid_is_refused`), never through a block
2692 // this encoder actually commits. Such a block has no true-edge
2693 // samples above or left of it at all, same as `y == 0`/`x == 0`.
2694 let across = across.min(self.tile_x1);
2695 let down = down.min(self.tile_y1);
2696 let above_n = (y > self.tile_y0 && across > x).then(|| across - x);
2697 if let Some(n) = above_n {
2698 above_buf[..n]
2699 .copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
2700 }
2701 let left_n = (x > self.tile_x0 && down > y).then(|| down - y);
2702 if let Some(n) = left_n {
2703 for (d, row) in left_buf[..n].iter_mut().zip(y..down) {
2704 *d = self.reconstruction[row * self.width + x - 1];
2705 }
2706 }
2707 let corner = (x > self.tile_x0 && y > self.tile_y0)
2708 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
2709 (
2710 above_n.map(|n| &above_buf[..n]),
2711 left_n.map(|n| &left_buf[..n]),
2712 corner,
2713 )
2714 }
2715
2716 /// Codes one block under one mode without committing it: hands back the
2717 /// levels, the block the decoder would reconstruct, the squared error
2718 /// against the source and an estimate of what the levels cost in bits.
2719 fn trial(&self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
2720 self.trial_typed(at, mode, angle_delta, base_q_idx, deadzone, TxType::DctDct, fctx)
2721 }
2722
2723 /// [`Self::trial`] under a named transform type -- what an intra chroma
2724 /// block gets, since chroma codes no `tx_type` symbol and the decoder
2725 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
2726 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
2727 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
2728 #[allow(clippy::too_many_arguments)]
2729 /// Sum of absolute differences between the source block at `(x, y)` and a
2730 /// `side x side` prediction, as the whole number it is.
2731 ///
2732 /// Bit-identical to the `f64` accumulation it replaces: every partial sum
2733 /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
2734 /// exactly, so no add here rounds and the order of the adds cannot change
2735 /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
2736 /// integer division per sample -- is what lets the row walk vectorize.
2737 fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
2738 let mut sad = 0u32;
2739 for row in 0..side {
2740 let source = &self.source[(y + row) * self.width + x..][..side];
2741 for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
2742 sad += u32::from(s.abs_diff(p));
2743 }
2744 }
2745 f64::from(sad)
2746 }
2747
2748 /// Squared error between the source block at `(x, y)` and a reconstruction
2749 /// of it, over the part of the block that is INSIDE the true frame.
2750 /// Exact for the same reason [`Self::block_sad`] is: the largest total is
2751 /// `255^2 * 64 * 64`, under 2^28.
2752 ///
2753 /// A block the frame edge cuts through is still coded whole -- the
2754 /// decoder reconstructs its outside samples too and the display crop
2755 /// throws them away -- so scoring the padding would rank a mode, a
2756 /// transform or a partition tree by how well it codes samples the source
2757 /// does not have (libaom clips the same way: `av1_dist_block` measures
2758 /// over `max_blocks_wide`/`max_blocks_high`). The padding is replicated
2759 /// edge pixels, so predicting it is nearly free, but coding coefficients
2760 /// for it spends real bits. Both gate films are superblock-aligned; this
2761 /// only reaches arbitrary export sizes (lane-sse, generalising
2762 /// lane-b64b's 64-root-only rescore of the 64 root).
2763 fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
2764 let inside_rows = side.min(self.true_height.saturating_sub(y));
2765 let inside_cols = side.min(self.true_width.saturating_sub(x));
2766 let straddles = inside_rows < side || inside_cols < side;
2767 // The knob is read only for a block the edge cuts, so the interior
2768 // path -- the hot one -- carries no extra load at all.
2769 let (rows, cols) = match straddles && !edge_sse() {
2770 true => (side, side),
2771 false => (inside_rows, inside_cols),
2772 };
2773 let mut sse = 0u64;
2774 for row in 0..rows {
2775 let source = &self.source[(y + row) * self.width + x..][..cols];
2776 for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..cols]) {
2777 let d = u32::from(s.abs_diff(r));
2778 sse += u64::from(d * d);
2779 }
2780 }
2781 if straddles && edge_census() {
2782 let (mut inside, mut whole) = (0u64, 0u64);
2783 for row in 0..side {
2784 let source = &self.source[(y + row) * self.width + x..][..side];
2785 for (col, (&s, &r)) in
2786 source.iter().zip(&reconstruction[row * side..][..side]).enumerate()
2787 {
2788 let d = u64::from(u32::from(s.abs_diff(r)).pow(2));
2789 whole += d;
2790 if row < inside_rows && col < inside_cols {
2791 inside += d;
2792 }
2793 }
2794 }
2795 record_edge_score(side, inside, whole - inside);
2796 }
2797 sse as f64
2798 }
2799
2800 fn trial_typed(
2801 &self,
2802 at: At,
2803 mode: u8,
2804 // This block's `angle_delta_y`/`angle_delta_uv` (spec
2805 // `read_intra_angle_info`, -3..=3), zero for every non-directional
2806 // mode -- the predictor's own `angle_delta` argument.
2807 angle_delta: i32,
2808 base_q_idx: u8,
2809 deadzone: f64,
2810 tx_type: TxType,
2811 fctx: &crate::decode::FrameCtx,
2812 ) -> Trial {
2813 let At {
2814 x, y, side, reach, ..
2815 } = at;
2816 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2817 let (above, left, corner) =
2818 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2819 // Per-candidate scratch on the search's hottest path, so both buffers
2820 // live on the stack -- `side` is at most `BLOCK` -- rather than
2821 // costing a malloc/free pair per trial (`mc_trial` already does this).
2822 let mut prediction = [0u8; BLOCK * BLOCK];
2823 let prediction = &mut prediction[..side * side];
2824 intra_predict_u8(
2825 mode,
2826 angle_delta,
2827 above,
2828 left,
2829 corner,
2830 side,
2831 side,
2832 false,
2833 false,
2834 prediction, fctx,
2835 );
2836
2837 let mut residual = [0i32; BLOCK * BLOCK];
2838 let residual = &mut residual[..side * side];
2839 for row in 0..side {
2840 for col in 0..side {
2841 residual[row * side + col] =
2842 i32::from(self.source[(y + row) * self.width + x + col])
2843 - i32::from(prediction[row * side + col]);
2844 }
2845 }
2846 #[cfg(test)]
2847 let t = stage_start();
2848 // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the
2849 // reconstruction below and the price further down are both of the
2850 // grid this trial would really code.
2851 let (levels, rdoq_bits) = if rdoq_on() {
2852 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
2853 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2854 );
2855 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2856 let bits = crate::tile::rdoq(
2857 &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(),
2858 tx_type,
2859 );
2860 (levels, Some(bits))
2861 } else {
2862 (
2863 forward_and_quantize_typed(
2864 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2865 ),
2866 None,
2867 )
2868 };
2869 // lane-av1speed2: 60% of the transform units of an inter stream carry
2870 // no coefficient at all, and the square entry point re-inflates that
2871 // case into `side * side` zeros (one allocate-and-memset per trial)
2872 // only for the sum below to add them to the prediction. The `_wh`
2873 // entry hands back the empty all-zero marker instead, and a zero
2874 // residual reconstructs to the prediction itself -- `clamp(p + 0)` is
2875 // `p` for a `u8`, so the bytes are the same.
2876 let coded = dequant_and_inverse_typed_wh(
2877 &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type, None,
2878 );
2879 #[cfg(test)]
2880 stage_since(2, t);
2881
2882 let reconstruction: Vec<u8> = if coded.is_empty() {
2883 prediction.to_vec()
2884 } else {
2885 prediction
2886 .iter()
2887 .zip(&coded)
2888 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
2889 .collect()
2890 };
2891 let sse = self.block_sse(x, y, side, &reconstruction);
2892 // What the levels cost is priced through the same CDFs the tile writer
2893 // will code them with, so the search ranks modes -- and the partition
2894 // trial ranks trees -- by the bits they actually spend.
2895 #[cfg(test)]
2896 let t = stage_start();
2897 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
2898 // What the search used before it could price a block exactly: a
2899 // level costs its magnitude's width plus a sign and a run. Kept
2900 // reachable from the sweep so the two rate terms can be compared
2901 // on one build.
2902 levels
2903 .iter()
2904 .filter(|&&level| level != 0)
2905 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
2906 .sum()
2907 } else if let Some(bits) = rdoq_bits {
2908 // Already priced, against the grid the pass settled on.
2909 bits
2910 } else {
2911 {
2912 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2913 crate::tile::coeff_bits_typed(
2914 &levels,
2915 at.set,
2916 crate::decode::q_ctx_of(base_q_idx),
2917 skip_ctx,
2918 sign_ctx,
2919 tx_type,
2920 )
2921 }
2922 };
2923 #[cfg(test)]
2924 stage_since(3, t);
2925 Trial {
2926 levels,
2927 reconstruction,
2928 sse,
2929 bits,
2930 }
2931 }
2932
2933 /// [`Self::trial`] with the prediction already built, so that an inter
2934 /// block's motion-compensated prediction can go through the same
2935 /// residual/quantize/reconstruct path an intra block's does. `skip`
2936 /// takes the prediction as the reconstruction outright, coding no
2937 /// residual at all — what a `NEARESTMV` block that names no coefficients
2938 /// codes.
2939 #[allow(clippy::too_many_arguments)]
2940 fn code_from_prediction(
2941 &self,
2942 x: usize,
2943 y: usize,
2944 side: usize,
2945 prediction: &[u8],
2946 skip: bool,
2947 base_q_idx: u8,
2948 deadzone: f64,
2949 set: TxbSet,
2950 ) -> Trial {
2951 self.code_from_prediction_typed(
2952 x, y, side, prediction, skip, base_q_idx, deadzone, set, TxType::DctDct,
2953 )
2954 }
2955
2956 /// [`Self::code_from_prediction`] coding the residual with a NAMED
2957 /// transform type (lane-txset2): the inter luma sets carry a two-type
2958 /// alphabet (`TX_SET_INTER_3`, `IDTX`/`DCT_DCT`) the writer already codes
2959 /// a symbol for, and [`commit_inter_luma`] prices both through this.
2960 #[allow(clippy::too_many_arguments)]
2961 fn code_from_prediction_typed(
2962 &self,
2963 x: usize,
2964 y: usize,
2965 side: usize,
2966 prediction: &[u8],
2967 skip: bool,
2968 base_q_idx: u8,
2969 deadzone: f64,
2970 set: TxbSet,
2971 tx_type: TxType,
2972 ) -> Trial {
2973 if skip {
2974 let sse = self.block_sse(x, y, side, prediction);
2975 return Trial {
2976 levels: vec![0i32; side * side],
2977 reconstruction: prediction.to_vec(),
2978 sse,
2979 bits: 0.0,
2980 };
2981 }
2982 // A 64x64 root's residual is four times the scratch every other
2983 // block coder here sizes for [`BLOCK`]; only that one case pays for
2984 // a heap buffer, so the 4x4..32x32 path keeps its stack array.
2985 let mut small = [0i32; BLOCK * BLOCK];
2986 let mut big = if side > BLOCK {
2987 vec![0i32; side * side]
2988 } else {
2989 Vec::new()
2990 };
2991 let residual: &mut [i32] = if side > BLOCK {
2992 &mut big
2993 } else {
2994 &mut small[..side * side]
2995 };
2996 for row in 0..side {
2997 for col in 0..side {
2998 residual[row * side + col] =
2999 i32::from(self.source[(y + row) * self.width + x + col])
3000 - i32::from(prediction[row * side + col]);
3001 }
3002 }
3003 #[cfg(test)]
3004 let t = stage_start();
3005 // lane-rdoq, as in [`Self::trial_typed`].
3006 let (levels, rdoq_bits) = if rdoq_on() {
3007 let (mut levels, scaled) =
3008 forward_and_quantize_typed_scaled(
3009 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
3010 );
3011 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3012 let bits = crate::tile::rdoq(
3013 &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(),
3014 tx_type,
3015 );
3016 (levels, Some(bits))
3017 } else {
3018 (
3019 forward_and_quantize_typed(
3020 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
3021 ),
3022 None,
3023 )
3024 };
3025 // The same all-zero shortcut [`Self::trial_typed`] takes.
3026 let coded = dequant_and_inverse_typed_wh(
3027 &levels,
3028 side,
3029 side,
3030 8,
3031 i32::from(base_q_idx),
3032 0,
3033 0,
3034 tx_type,
3035 None,
3036 );
3037 #[cfg(test)]
3038 stage_since(2, t);
3039 let reconstruction: Vec<u8> = if coded.is_empty() {
3040 prediction.to_vec()
3041 } else {
3042 prediction
3043 .iter()
3044 .zip(&coded)
3045 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
3046 .collect()
3047 };
3048 let sse = self.block_sse(x, y, side, &reconstruction);
3049 // A 64-point transform codes only its top-left 32x32 corner (spec
3050 // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the
3051 // key frame writer takes a 32x32 level grid for one). The inverse
3052 // above reads the whole 64x64 array, but the price below and the
3053 // levels the writer takes are that corner.
3054 let levels = if side > BLOCK {
3055 coded_corner(&levels, side, BLOCK)
3056 } else {
3057 levels
3058 };
3059 #[cfg(test)]
3060 let t = stage_start();
3061 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
3062 levels
3063 .iter()
3064 .filter(|&&level| level != 0)
3065 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
3066 .sum()
3067 } else if let Some(bits) = rdoq_bits {
3068 bits
3069 } else {
3070 {
3071 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3072 crate::tile::coeff_bits_typed(
3073 &levels,
3074 set,
3075 crate::decode::q_ctx_of(base_q_idx),
3076 skip_ctx,
3077 sign_ctx,
3078 tx_type,
3079 )
3080 }
3081 };
3082 #[cfg(test)]
3083 stage_since(3, t);
3084 Trial {
3085 levels,
3086 reconstruction,
3087 sse,
3088 bits,
3089 }
3090 }
3091
3092 /// Codes this block's luma at transform depth `depth`: the
3093 /// `(side >> depth)^2` transform units in raster order, each predicted
3094 /// from the reconstruction the units before it left behind -- exactly
3095 /// what the decoder's multi-transform-unit branch does (decode.rs
3096 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
3097 /// reconstructed on its own. Commits the result and hands back the
3098 /// block-coordinate levels, the block's squared error and what its
3099 /// coefficients cost.
3100 #[allow(clippy::too_many_arguments)]
3101 fn code_tx_depth(
3102 &mut self,
3103 at: At,
3104 mode: u8,
3105 angle_delta: i32,
3106 depth: usize,
3107 // This block's `filter_intra_mode` when it is coded with one, in
3108 // which case every transform unit predicts recursively off the
3109 // reconstruction the units before it left -- what the decoder does
3110 // per unit (decode.rs `decode_block`, `push_intra_rect`'s
3111 // `filter_intra`), not once over the whole block.
3112 filter_intra: Option<u8>,
3113 search: &Search, fctx: &crate::decode::FrameCtx,
3114 ) -> (Vec<i32>, f64, f64, Vec<TxType>) {
3115 let At { x, y, side, reach, .. } = at;
3116 let tx = side >> depth;
3117 let n = 1usize << depth;
3118 let set = luma_set_for(
3119 match tx {
3120 32 => TxbSet::Luma32,
3121 16 => TxbSet::Luma16,
3122 8 => TxbSet::Luma8,
3123 _ => TxbSet::Luma4,
3124 },
3125 search.screen,
3126 );
3127 let mut levels = vec![0i32; side * side];
3128 census_add(4, n * n);
3129 // A unit smaller than its block reads the neighbour magnitude table
3130 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
3131 self.ctx.tu_split = n > 1;
3132 let (mut sse, mut bits) = (0.0, 0.0);
3133 // One entry per unit at its own `tu_row * n + tu_col`, which is how
3134 // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the
3135 // frame edge cuts away is never coded there, so a compacted list
3136 // would slide every later unit's type onto the wrong transform.
3137 let mut tx_types = vec![TxType::DctDct; n * n];
3138 for tu_row in 0..n {
3139 for tu_col in 0..n {
3140 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
3141 let tu = At {
3142 x: x + col_off,
3143 y: y + row_off,
3144 side: tx,
3145 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
3146 set,
3147 };
3148 let trial = match filter_intra {
3149 Some(fi) => {
3150 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3151 let (above, left, corner) =
3152 self.edges_into(tu.x, tu.y, tx, tu.reach, &mut above_buf, &mut left_buf);
3153 let mut prediction = vec![0u8; tx * tx];
3154 filter_intra_predict_u8(
3155 usize::from(fi),
3156 above,
3157 left,
3158 corner,
3159 tx,
3160 &mut prediction,
3161 fctx,
3162 );
3163 self.code_from_prediction(
3164 tu.x,
3165 tu.y,
3166 tx,
3167 &prediction,
3168 false,
3169 search.base_q_idx,
3170 search.deadzone,
3171 set,
3172 )
3173 }
3174 None => {
3175 // lane-txset: the unit picks its own transform type
3176 // out of the set the writer can name it in, priced
3177 // through the same RDOQ'd trial path (its `bits`
3178 // already carry the `tx_type` symbol itself).
3179 let mut best: Option<(f64, TxType, Trial)> = None;
3180 for &tx_type in tx_type_candidates(set, search.screen) {
3181 let candidate = self.trial_typed(
3182 tu, mode, angle_delta, search.base_q_idx, search.deadzone,
3183 tx_type, fctx,
3184 );
3185 // lane-txi: a non-`DCT_DCT` type is charged its
3186 // bits at `EC_AV1_TXRD_LAMBDA` times the mode
3187 // search's weight (default 1 = unchanged). The
3188 // film rows buy 0.04 dB for 1.2% more bytes at
3189 // weight 1 on every frame and every PLANE, key
3190 // frame included -- a rate term this decision
3191 // under-charges (class
3192 // `rd-rate-term-calibration`), not the
3193 // propagation loss the leaves would have shown.
3194 let cost = candidate.sse
3195 + search.lambda * candidate.bits
3196 + non_dct_surcharge(search.lambda, tx_type, candidate.bits);
3197 if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {
3198 best = Some((cost, tx_type, candidate));
3199 }
3200 }
3201 let (_, tx_type, trial) =
3202 best.expect("the candidate list is never empty");
3203 tx_types[tu_row * n + tu_col] = tx_type;
3204 TX_TYPE_HITS[tx_type as usize]
3205 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3206 trial
3207 }
3208 };
3209 sse += trial.sse;
3210 bits += trial.bits;
3211 self.commit(tu.x, tu.y, tx, &trial);
3212 for row in 0..tx {
3213 levels[(row_off + row) * side + col_off..][..tx]
3214 .copy_from_slice(&trial.levels[row * tx..][..tx]);
3215 }
3216 }
3217 }
3218 self.ctx.tu_split = false;
3219 (levels, sse, bits, tx_types)
3220 }
3221
3222 /// Writes a trial's reconstruction back into the plane, and the
3223 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
3224 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
3225 for row in 0..side {
3226 self.reconstruction[(y + row) * self.width + x..][..side]
3227 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
3228 }
3229 self.commit_ctx(x, y, side, &trial.levels);
3230 }
3231
3232 /// Publishes one committed transform's own context over every 4x4 cell it
3233 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
3234 /// which is what the writer will read when it reaches the next block.
3235 fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
3236 if self.ctx.cells.is_empty() {
3237 self.ctx.stride = self.width.div_ceil(4);
3238 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
3239 }
3240 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
3241 let state = CoefCtx {
3242 level: cul,
3243 dc: match levels[0].signum() {
3244 0 => 0,
3245 -1 => -1,
3246 _ => 1,
3247 },
3248 };
3249 let n = (side / 4).max(1);
3250 // Only up to the frame's TRUE extent: the writer's own
3251 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
3252 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
3253 // and leaves the cells past it uncoded even mid-block, so a
3254 // straddling block publishes context for its inside part only.
3255 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
3256 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
3257 for row in 0..rows {
3258 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3259 let end = (start + cols).min(self.ctx.cells.len());
3260 if start < end {
3261 self.ctx.cells[start..end].fill(state);
3262 }
3263 }
3264 }
3265
3266 /// A block committed without any residual at all ([`ibc_commit`]): the
3267 /// cells it covers coded nothing, and leaving an earlier trial's state
3268 /// there would price its neighbours off a block that was never coded.
3269 fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
3270 self.commit_ctx(x, y, side, &[0i32]);
3271 }
3272
3273 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
3274 /// plane reads, off what the blocks before it in coding order committed
3275 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
3276 /// the above/left neighbours coded anything (tile.rs
3277 /// `write_block_planes`), luma reads context 0 when its transform covers
3278 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
3279 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
3280 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
3281 /// the same neighbours (tile.rs `dc_sign_ctx`).
3282 ///
3283 /// A neighbour outside this plane's own TILE does not exist, exactly as
3284 /// the writer's per-tile `Neighbours` bands start blank.
3285 ///
3286 /// CLOSED (lane-av1straddle): the decisions this price changes used to
3287 /// make `decode_stream_round_trips_an_odd_size_gop` and
3288 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
3289 /// fail at 216x96. Never this map: the writer coded the phantom
3290 /// transform units of a right-edge-straddling 32x32 (tile.rs
3291 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
3292 /// like decode.rs and libaom), which libdav1d and libaom both refused
3293 /// outright while a decision change was what first walked into it.
3294 fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
3295 if self.ctx.cells.is_empty() {
3296 return (0, 0);
3297 }
3298 let n = (side / 4).max(1);
3299 let (cx, cy) = (x / 4, y / 4);
3300 let (mut top, mut left) = (0u8, 0u8);
3301 let mut vote = 0i32;
3302 if y > self.tile_y0 && cy > 0 {
3303 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
3304 top |= cell.level;
3305 vote += i32::from(cell.dc);
3306 }
3307 }
3308 if x > self.tile_x0 && cx > 0 {
3309 for row in 0..n {
3310 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
3311 left |= cell.level;
3312 vote += i32::from(cell.dc);
3313 }
3314 }
3315 let skip_ctx = if set.is_chroma() {
3316 usize::from(top != 0) + usize::from(left != 0)
3317 } else if self.ctx.tu_split {
3318 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
3319 } else {
3320 0
3321 };
3322 let sign_ctx = match vote.signum() {
3323 0 => 0,
3324 -1 => 1,
3325 _ => 2,
3326 };
3327 (skip_ctx, sign_ctx)
3328 }
3329
3330 /// The source samples of one square, contiguous — what a motion search
3331 /// compares its candidates' predictions against ([`motion::search`]'s
3332 /// `source`), since [`Self::source`] itself is the whole plane, strided
3333 /// by [`Self::width`].
3334 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
3335 rows_of(self.source, self.width, x, y, side)
3336 }
3337
3338 /// lane-b128hv: [`Self::source_block`] over a rectangle, for the 128
3339 /// root's own HORZ/VERT motion search.
3340 fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> {
3341 let mut out = vec![0u8; w * h];
3342 for row in 0..h {
3343 out[row * w..][..w]
3344 .copy_from_slice(&self.source[(y + row) * self.width + x..][..w]);
3345 }
3346 out
3347 }
3348
3349 /// The reconstructed samples of one square, so that a partition trial can
3350 /// be undone.
3351 /// The reconstructed samples of one square AND the coefficient contexts
3352 /// its cells hold, so that a partition trial can be undone whole: a
3353 /// losing trial that left its own nz/DC state behind would price the
3354 /// blocks after it off a block the tile writer never codes.
3355 fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
3356 (
3357 rows_of(&self.reconstruction, self.width, x, y, side),
3358 self.ctx_rows(x, y, side),
3359 )
3360 }
3361
3362 fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
3363 if self.ctx.cells.is_empty() {
3364 return Vec::new();
3365 }
3366 let n = (side / 4).max(1);
3367 (0..n)
3368 .flat_map(|row| {
3369 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3370 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
3371 })
3372 .collect()
3373 }
3374
3375 /// Puts a snapshot back.
3376 fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
3377 for row in 0..side {
3378 self.reconstruction[(y + row) * self.width + x..][..side]
3379 .copy_from_slice(&saved.0[row * side..][..side]);
3380 }
3381 if saved.1.is_empty() {
3382 return;
3383 }
3384 let n = (side / 4).max(1);
3385 for row in 0..n {
3386 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3387 let end = (start + n).min(self.ctx.cells.len());
3388 if start < end {
3389 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
3390 }
3391 }
3392 }
3393
3394 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
3395 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
3396 /// prescreen by the identical rule rather than a second one that could
3397 /// drift from it.
3398 fn intra_scores(
3399 &self,
3400 at: At,
3401 modes: &[u8],
3402 mode_bits: &[f64; 13],
3403 lambda: f64, fctx: &crate::decode::FrameCtx,
3404 ) -> Vec<(f64, u8)> {
3405 let At {
3406 x, y, side, reach, ..
3407 } = at;
3408 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3409 let (above, left, corner) =
3410 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3411 modes
3412 .iter()
3413 .map(|&mode| {
3414 let mut prediction = vec![0u8; side * side];
3415 intra_predict_u8(
3416 mode,
3417 0,
3418 above,
3419 left,
3420 corner,
3421 side,
3422 side,
3423 false,
3424 false,
3425 &mut prediction, fctx,
3426 );
3427 let sad = self.block_sad(x, y, side, &prediction);
3428 (sad + lambda * mode_bits[usize::from(mode)], mode)
3429 })
3430 .collect()
3431 }
3432
3433 /// Codes one block under every mode the search offers (or, when
3434 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
3435 /// pre-pass plus DC) and commits the one whose squared error and
3436 /// estimated rate come out cheapest.
3437 ///
3438 /// The prediction is built once per mode regardless -- the full RD trial
3439 /// needs it too -- so ranking modes by SAD on that same prediction before
3440 /// running the expensive part (forward transform, quantize, reconstruct,
3441 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
3442 /// only to sum.
3443 fn search_block(
3444 &mut self,
3445 at: At,
3446 search: &Search,
3447 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
3448 ) -> (Vec<Coeff>, u8, i32, f64, TxType) {
3449 let At {
3450 x, y, side, reach, ..
3451 } = at;
3452 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3453 let (above, left, corner) =
3454 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3455 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
3456 // the census reports it), so summing it under the default unpruned
3457 // search is `side * side` absolute differences per mode spent on a
3458 // number no one reads.
3459 let want_sad = search.top_k.is_some() || census_on();
3460 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
3461 .modes
3462 .iter()
3463 .map(|&mode| {
3464 let mut prediction = vec![0u8; side * side];
3465 intra_predict_u8(
3466 mode,
3467 0,
3468 above,
3469 left,
3470 corner,
3471 side,
3472 side,
3473 false,
3474 false,
3475 &mut prediction, fctx,
3476 );
3477 let sad = if want_sad {
3478 self.block_sad(x, y, side, &prediction)
3479 } else {
3480 0.0
3481 };
3482 (
3483 sad + search.lambda * mode_bits[usize::from(mode)],
3484 mode,
3485 prediction,
3486 )
3487 })
3488 .collect();
3489 if let Some(k) = search.top_k {
3490 if k < scored.len() {
3491 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
3492 let dc_entry = dc_pos.map(|i| scored.remove(i));
3493 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
3494 scored.truncate(if dc_entry.is_some() {
3495 k.saturating_sub(1)
3496 } else {
3497 k
3498 });
3499 if let Some(dc_entry) = dc_entry {
3500 scored.push(dc_entry);
3501 }
3502 }
3503 }
3504 let ranking: Vec<(f64, u8)> = if census_on() {
3505 scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
3506 } else {
3507 Vec::new()
3508 };
3509 census_add(0, 1);
3510 census_add(1, scored.len());
3511 let mut best: Option<(f64, u8, Trial)> = None;
3512 for (_, mode, prediction) in scored {
3513 let trial = self.code_from_prediction(
3514 x,
3515 y,
3516 side,
3517 &prediction,
3518 false,
3519 search.base_q_idx,
3520 search.deadzone,
3521 at.set,
3522 );
3523 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
3524 if best
3525 .as_ref()
3526 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
3527 {
3528 best = Some((cost, mode, trial));
3529 }
3530 }
3531 let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
3532 // `angle_delta_y` (spec `read_intra_angle_info`): the eight
3533 // directional modes each carry a -3..=3 delta, three degrees a step,
3534 // which the writer has always coded as ZERO because nothing searched
3535 // it. Refined on the winning mode only -- libaom's own ordering, and
3536 // six extra trials on the directional blocks instead of on every
3537 // block times every mode. The edges are the ones the base angle
3538 // already read (`enable_intra_edge_filter` is off in this encoder's
3539 // sequence header, so no delta changes which samples exist), and the
3540 // predictor is the decoder's, `angle_delta` argument and all.
3541 let mut angle_delta = 0i32;
3542 // Not on a screen frame: measured on the 5-row native gate, the
3543 // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
3544 // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
3545 // synthetic edges land on the base angles, so every delta there buys
3546 // a symbol and no prediction. Same `search.screen` gate palette and
3547 // intrabc already stand behind.
3548 if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
3549 let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
3550 let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
3551 let mut prediction = vec![0u8; side * side];
3552 for delta in [-3i32, -2, -1, 1, 2, 3] {
3553 intra_predict_u8(
3554 mode,
3555 delta,
3556 above,
3557 left,
3558 corner,
3559 side,
3560 side,
3561 false,
3562 false,
3563 &mut prediction, fctx,
3564 );
3565 let candidate = self.code_from_prediction(
3566 x,
3567 y,
3568 side,
3569 &prediction,
3570 false,
3571 search.base_q_idx,
3572 search.deadzone,
3573 at.set,
3574 );
3575 let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
3576 - zero_bits;
3577 let cost_d = candidate.sse
3578 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
3579 if cost_d < cost {
3580 cost = cost_d;
3581 angle_delta = delta;
3582 trial = candidate;
3583 }
3584 }
3585 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
3586 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3587 }
3588 // lane-txset: the block's own transform type, searched on the mode
3589 // and angle the trials above settled -- the same ordering the angle
3590 // refinement uses, and the same RD terms.
3591 let mut tx_type = TxType::DctDct;
3592 for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) {
3593 let candidate = self.trial_typed(
3594 at, mode, angle_delta, search.base_q_idx, search.deadzone, candidate_type, fctx,
3595 );
3596 let cost_t =
3597 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
3598 // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is
3599 // `DCT_DCT` and pays none of it, so the returned `cost` stays the
3600 // block's true one for the caller's own decision.
3601 if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost {
3602 cost = cost_t;
3603 tx_type = candidate_type;
3604 trial = candidate;
3605 }
3606 }
3607 TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3608 if census_on() {
3609 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
3610 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3611 }
3612 self.commit(x, y, side, &trial);
3613 // A 64-point transform codes only its top-left 32x32 corner, which is
3614 // the grid `code_from_prediction` hands back (lane-i64).
3615 (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost, tx_type)
3616 }
3617}
3618
3619/// Where one block sits in its plane, and how far past its own edges its
3620/// prediction may read.
3621#[derive(Clone, Copy)]
3622struct At {
3623 x: usize,
3624 y: usize,
3625 side: usize,
3626 reach: Reach,
3627 /// Which of the tile writer's coefficient tables this block's levels are
3628 /// coded with, and so which the search prices them through.
3629 set: TxbSet,
3630}
3631
3632/// Which of the samples past a block's own edges the decoder has decoded by
3633/// the time it predicts the block, and so which a directional mode may read.
3634///
3635/// The decoder derives these from its `BlockDecoded` flags, which are cleared
3636/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
3637/// that map, this reads the answer the same way libaom and rav1e do: for a
3638/// block whose transform covers it whole, whether the samples above its right
3639/// (or below its left) are decoded depends only on where the block sits inside
3640/// its 64x64 superblock, which is a pinned table per block size.
3641#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3642pub(crate) struct Reach {
3643 pub(crate) above_right: bool,
3644 pub(crate) below_left: bool,
3645}
3646
3647/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
3648/// libaom): for a block that is neither in the superblock's top row nor its
3649/// rightmost column, whether the block above and to its right is coded before
3650/// it. Indexed by the block's position in the superblock, in blocks of its own
3651/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
3652/// 128, not this crate's 64 superblock -- bit by bit from the low end.
3653const HAS_TOP_RIGHT: [&[u8]; 4] = [
3654 &[255, 85, 119, 85, 127, 85, 119, 85],
3655 &[95, 87],
3656 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
3657 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
3658 &[
3659 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
3660 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
3661 ],
3662
3663 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
3664 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
3665 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
3666 // with side 4 outside a TX4 split; without their own row they clamped
3667 // into the 8x8 table and read above-right samples the decoder has not
3668 // written yet (all-zero pixels in the bottom-right triangle of a
3669 // directional 4x4 leaf).
3670 &[
3671 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
3672 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
3673 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
3674 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
3675 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
3676 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
3677 119, 119, 119, 119, 85, 85, 85, 85,
3678 ],
3679];
3680
3681/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
3682/// left.
3683const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
3684 &[84, 16, 84, 0, 84, 16, 84, 0],
3685 &[4, 4],
3686 // has_bl_8x8 (libaom av1/common/reconintra.c)
3687 &[
3688 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
3689 84, 85, 16, 17, 84, 85, 0, 0,
3690 ],
3691
3692 // has_bl_4x4 (same source, same order).
3693 &[
3694 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
3695 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84,
3696 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
3697 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 1, 0, 84, 85,
3698 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
3699 85, 85, 0, 0, 0, 0,
3700 ],
3701];
3702
3703/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
3704/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
3705/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
3706/// rather than in raster order, so the bottom-left square's top-right
3707/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
3708/// libaom switches tables on the partition type (`get_has_tr_table`); the
3709/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
3710/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
3711/// lane-part32 r5 caught reading undecoded samples.
3712const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
3713 // has_tr_vert_16x16
3714 &[255, 0, 119, 0, 127, 0, 119, 0],
3715 // has_tr_vert_32x32
3716 &[15, 7],
3717 // has_tr_vert_8x8
3718 &[
3719 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
3720 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
3721 ],
3722];
3723
3724/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
3725const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
3726 // has_bl_vert_16x16
3727 &[254, 16, 254, 0, 254, 16, 254, 0],
3728 // has_bl_vert_32x32
3729 &[14, 14],
3730 // has_bl_vert_8x8
3731 &[
3732 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
3733 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
3734 ],
3735];
3736
3737thread_local! {
3738 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
3739 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
3740 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
3741 /// threading one bool through this crate's already twenty-argument
3742 /// `decode_block` would touch every call site instead of the two arms
3743 /// that need it.
3744 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3745}
3746
3747/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
3748pub(crate) struct VertAbGuard(bool);
3749
3750impl Drop for VertAbGuard {
3751 fn drop(&mut self) {
3752 VERT_AB_PARTITION.with(|c| c.set(self.0));
3753 }
3754}
3755
3756/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
3757/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
3758/// so no byte is retyped). Each is indexed by
3759/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
3760/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
3761/// superblock grid; on this crate's 64-pixel superblock the highest index a
3762/// shape can reach stays inside its own table, so no wrap is involved.
3763///
3764/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
3765/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
3766/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
3767/// 10 of the 21 reachable superblock positions for above-right and 7 for
3768/// below-left.
3769/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3770const HAS_TR_4X8: [u8; 64] = [255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119];
3771/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3772const HAS_BL_4X8: [u8; 64] = [16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0];
3773/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3774const HAS_TR_8X4: [u8; 64] = [255, 255, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 255, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0];
3775/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3776const HAS_BL_8X4: [u8; 64] = [254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0];
3777/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3778const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119];
3779/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3780const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
3781/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3782const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
3783/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3784const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0];
3785/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3786const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
3787/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3788const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
3789/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3790const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
3791/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3792const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
3793/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3794const HAS_TR_32X64: [u8; 1] = [127];
3795/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3796const HAS_BL_32X64: [u8; 1] = [0];
3797/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3798const HAS_TR_64X32: [u8; 1] = [19];
3799/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3800const HAS_BL_64X32: [u8; 1] = [34];
3801/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3802const HAS_TR_4X16: [u8; 32] = [255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255, 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127];
3803/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3804const HAS_BL_4X16: [u8; 32] = [0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0];
3805/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3806const HAS_TR_16X4: [u8; 32] = [255, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, 127, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0];
3807/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3808const HAS_BL_16X4: [u8; 32] = [254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0];
3809/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3810const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
3811/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3812const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
3813/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3814const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
3815/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3816const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
3817/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3818const HAS_TR_16X64: [u8; 2] = [255, 127];
3819/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3820const HAS_BL_16X64: [u8; 2] = [0, 0];
3821/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3822const HAS_TR_64X16: [u8; 2] = [3, 1];
3823/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3824const HAS_BL_64X16: [u8; 2] = [42, 42];
3825
3826/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
3827fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
3828 match (bw, bh) {
3829 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
3830 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
3831 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
3832 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
3833 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
3834 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
3835 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
3836 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
3837 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
3838 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
3839 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
3840 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
3841 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
3842 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
3843 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
3844 }
3845}
3846
3847impl Reach {
3848 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
3849 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
3850 /// own answer is `block` -- a different rule from the standalone-block
3851 /// tables, because a unit's neighbours are mostly its own block's
3852 /// already-reconstructed units:
3853 /// * top-right: available while the unit to the right is still inside
3854 /// the block (`col_off + tx < bw`); otherwise only the block's top row
3855 /// of units reaches past it, through the block-level answer
3856 /// (libaom's `row_off > 0` branch returns exactly
3857 /// `col_off + txw < plane_bw`).
3858 /// * bottom-left: a unit outside the block's left column has none
3859 /// (libaom returns 0 for `col_off > 0`); inside the block
3860 /// (`row_off + tx < bh`) they are the left unit's, already
3861 /// reconstructed; the bottom row falls back to the block-level answer.
3862 pub(crate) fn of_tu(
3863 bw: usize,
3864 bh: usize,
3865 col_off: usize,
3866 row_off: usize,
3867 // The unit's own width and height in pixels; equal for a square
3868 // transform, different for the rect unit a 1:4 strip's first split
3869 // produces (lane-rectsplitx r1).
3870 tx_w: usize,
3871 tx_h: usize,
3872 block: Self,
3873 ) -> Self {
3874 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
3875 // order, so both libaom predicates special-case it (lane-sb128c r10);
3876 // without this the last unit column of every chunk of a 128x64 block
3877 // predicts from a chunk libaom has not decoded yet.
3878 let wide = bw > 64;
3879 Self {
3880 above_right: if row_off > 0 {
3881 // `has_top_right`'s `row_off > 0` branch: the offset is taken
3882 // modulo the 64-wide chunk, except for the one unit whose
3883 // top-right corner is the centre of a 128x128 block.
3884 if wide {
3885 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
3886 } else {
3887 col_off + tx_w < bw
3888 }
3889 } else if col_off + tx_w < bw {
3890 true
3891 } else {
3892 block.above_right
3893 },
3894 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
3895 // `has_bottom_left`: at the left edge of a right-hand chunk
3896 // the bottom-left pixels are in the already-coded left chunk,
3897 // provided they stay inside it.
3898 (row_off % 64) + tx_h < bh.min(64)
3899 } else if col_off > 0 {
3900 false
3901 } else if row_off + tx_h < bh {
3902 true
3903 } else {
3904 block.below_left
3905 },
3906 }
3907 }
3908
3909 /// What a block of `side` samples at `(x, y)` may read past its own edges,
3910 /// in a frame of `width` by `height`.
3911 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
3912 Self {
3913 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
3914 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
3915 }
3916 }
3917
3918 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
3919 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
3920 /// block's own width for the row stride and by its own height for the
3921 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
3922 /// unlike the square [`Self::of`] which uses one `side` for everything.
3923 pub(crate) fn of_rect(
3924 bw: usize,
3925 bh: usize,
3926 x: usize,
3927 y: usize,
3928 width: usize,
3929 height: usize, fctx: &crate::decode::FrameCtx,
3930 ) -> Self {
3931 Self {
3932 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
3933 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
3934 }
3935 }
3936
3937 /// [`Self::of`] for one transform unit of a square block whose transform
3938 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
3939 /// non-zero `row_off`/`col_off`): interior units answer from the block's
3940 /// own geometry, and only a unit on the block's top row (resp. left
3941 /// column) reaches the table -- which is the BLOCK's table read at the
3942 /// BLOCK's position, never a table row for the transform's size. Letting
3943 /// the unit stand in for a block of its own size agrees with libaom for
3944 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
3945 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
3946 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
3947 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
3948 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
3949 /// the transform covering the whole block, luma): everything before the
3950 /// table lookup is that function's own early-exit ladder.
3951 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3952 let sb_mi: usize = reach_sb_px(fctx) / 4;
3953 let (mi_row, mi_col) = (y / 4, x / 4);
3954 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3955 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3956 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3957 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3958 // Top row of the superblock: the top-right pixels are in the (already
3959 // decoded) superblock above.
3960 if blk_row == 0 {
3961 return true;
3962 }
3963 // Rightmost column: they fall in the superblock to the right.
3964 if ((blk_col + 1) << bw_log2) >= sb_mi {
3965 return false;
3966 }
3967 let table = rect_reach_tables(bw, bh).0;
3968 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
3969 }
3970
3971 /// libaom `has_top_right`'s own index arithmetic:
3972 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
3973 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
3974 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
3975 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
3976 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
3977 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
3978 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
3979 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
3980 (blk_row << (5 - bw_log2)) + blk_col
3981 }
3982
3983 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
3984 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3985 let sb_mi: usize = reach_sb_px(fctx) / 4;
3986 let (mi_row, mi_col) = (y / 4, x / 4);
3987 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3988 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3989 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3990 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3991 // Leftmost column of the superblock: the bottom-left pixels are in
3992 // the left superblock iff they stay inside its height.
3993 if blk_col == 0 {
3994 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
3995 }
3996 // Bottom row (and not the leftmost column): they fall in the
3997 // superblock below, which is not decoded yet.
3998 if ((blk_row + 1) << bh_log2) >= sb_mi {
3999 return false;
4000 }
4001 let table = rect_reach_tables(bw, bh).1;
4002 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
4003 }
4004
4005 /// Marks every [`Reach::of`] made until the returned guard drops as being
4006 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
4007 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
4008 /// unaffected: libaom's own comment says vertical rectangles keep their
4009 /// non-vert table, which is what [`Reach::of_rect`] already reads.
4010 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
4011 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
4012 /// can count the sub-block work that partition creates (lane-ab16).
4013 pub(crate) fn in_vert_ab() -> bool {
4014 VERT_AB_PARTITION.with(std::cell::Cell::get)
4015 }
4016
4017 pub(crate) fn vert_ab_partition() -> VertAbGuard {
4018 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
4019 }
4020
4021 /// Neither, which is all a mode that reads no further than its own edges
4022 /// needs.
4023 pub(crate) fn none() -> Self {
4024 Self {
4025 above_right: false,
4026 below_left: false,
4027 }
4028 }
4029
4030 /// `has_top_right` for a block whose transform covers it whole: the top
4031 /// row of a superblock reads into the superblock above, which is decoded;
4032 /// the rightmost column would read into the superblock to the right, which
4033 /// is not; and everything between is the table's to answer.
4034 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4035 let (row, col, per_side) = Self::position(side, x, y, fctx);
4036 if row == 0 {
4037 return true;
4038 }
4039 if col + 1 == per_side {
4040 return false;
4041 }
4042 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4043 // (the clamp corner-cut that used to live here is gone); sides
4044 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4045 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4046 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4047 // -- a reach over-estimate (extra above-right reference pixels),
4048 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4049 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4050 // NB: named `table_row`, not `row` -- `row` above is the block's
4051 // position inside the superblock and is what the bit index below
4052 // steps by (a merge that shadowed it desynced every block size).
4053 let table_row = Self::table(side);
4054 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() {
4055 HAS_TOP_RIGHT_VERT[table_row]
4056 } else {
4057 HAS_TOP_RIGHT[table_row]
4058 };
4059 Self::bit(
4060 table,
4061 (row * Self::table_stride(side) + col) % (table.len() * 8),
4062 )
4063 }
4064
4065 /// `has_bottom_left` for such a block: the leftmost column of a superblock
4066 /// reads into the superblock to its left, which is decoded only as far
4067 /// down as its own bottom; the bottom row would read into the superblock
4068 /// below, which is not decoded at all; and the table answers the rest.
4069 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4070 let (row, col, per_side) = Self::position(side, x, y, fctx);
4071 if col == 0 {
4072 return row * side + side < reach_sb_px(fctx);
4073 }
4074 if row + 1 == per_side {
4075 return false;
4076 }
4077 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4078 // (the clamp corner-cut that used to live here is gone); sides
4079 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4080 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4081 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4082 // -- a reach over-estimate (extra above-right reference pixels),
4083 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4084 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4085 // NB: named `table_row`, not `row` -- `row` above is the block's
4086 // position inside the superblock and is what the bit index below
4087 // steps by (a merge that shadowed it desynced every block size).
4088 let table_row = Self::table(side);
4089 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() {
4090 HAS_BOTTOM_LEFT_VERT[table_row]
4091 } else {
4092 HAS_BOTTOM_LEFT[table_row]
4093 };
4094 Self::bit(
4095 table,
4096 (row * Self::table_stride(side) + col) % (table.len() * 8),
4097 )
4098 }
4099
4100 /// Where a block sits inside its superblock, in blocks of its own size,
4101 /// and how many of them a superblock is across.
4102 fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
4103 let sb = reach_sb_px(fctx);
4104 ((y % sb) / side, (x % sb) / side, sb / side)
4105 }
4106
4107 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
4108 /// these tables to its compile-time maximum superblock (128, spec
4109 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
4110 /// size an encode actually uses, so a block's row in the bit index steps
4111 /// by 128 / `side` even though this crate only ever codes a 64
4112 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
4113 /// here instead indexes the wrong bit for every block size but the one
4114 /// where 64 and 128 give the same stride.
4115 fn table_stride(side: usize) -> usize {
4116 128 / side
4117 }
4118
4119 /// Which of the three block sizes the encoder codes a table row is for.
4120 fn table(side: usize) -> usize {
4121 if side == BLOCK {
4122 1
4123 } else if side == 8 {
4124 2
4125 } else if side == 4 {
4126 3
4127 } else {
4128 0
4129 }
4130 }
4131
4132 /// One bit of a table, counting from the low end of its first byte.
4133 fn bit(table: &[u8], index: usize) -> bool {
4134 (table[index / 8] >> (index % 8)) & 1 != 0
4135 }
4136}
4137
4138/// What one symbol costs against a CDF, in bits.
4139/// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the
4140/// search, the frame header's `allow_warped_motion` and the sequence's
4141/// `enable_warped_motion`, all three together. ON by default since
4142/// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at
4143/// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
4144/// bits -- back off for an A/B on one build.
4145pub(crate) fn warp_on() -> bool {
4146 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4147 crate::envflags::var("EC_AV1_WARP").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
4148 });
4149 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
4150}
4151
4152/// The smallest LEAF an OBMC candidate is offered for, so the census can
4153/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
4154/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
4155/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
4156///
4157/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
4158/// (12 frames, four quantizers, the standing keep table):
4159///
4160/// | min side | film 1080p | film 2160p | screen |
4161/// |---|---|---|---|
4162/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
4163/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
4164/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
4165/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
4166///
4167/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
4168/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
4169/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
4170/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
4171/// that wins the local RD on five blocks in six and loses ladder bytes is
4172/// the `local-RD-on-references` class again, not a missing footprint.
4173///
4174/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
4175/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
4176/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
4177/// loss on the 1080p film became a 0.3-point win and the other two rows went
4178/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
4179/// of the "local win, ladder loss" it was charged with was the rate weight.
4180/// It still does not meet the keep rule (two down, one flat, both columns).
4181/// The tool stays OFF by default; the upgrade path is the price, not the size
4182/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
4183/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
4184/// 1080p film up, i.e. the same disagreement between the two gates).
4185///
4186/// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept
4187/// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1,
4188/// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads
4189/// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p
4190/// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference
4191/// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at
4192/// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and
4193/// the margin's gain are the same bytes. It stays OFF.
4194///
4195/// RE-MEASURED on lane-obmc3 (2026-09-08) on the REAL film rows -- every
4196/// judgement above was taken when the gate's "film" rows were the `testsrc2`
4197/// COLOUR BARS fixtures (class `gate film rows are colour bars`), so this is
4198/// the first OBMC measurement on film. BD vs libaom / vs rav1e, 12 pictures,
4199/// the standing native keep table (`bd_rate_screen_native`):
4200///
4201/// | arm | film A | film B | screen | OBMC fire A/B |
4202/// |---|---|---|---|---|
4203/// | off (control) | +21.7 / -4.4 | +26.9 / -0.6 | +20.1 / -30.4 | 0% / 0% |
4204/// | min side 8 | +21.7 / -4.3 | +27.2 / -0.3 | +20.0 / -30.4 | 15.5% / 9.7% |
4205/// | min side 16 | +21.5 / -4.5 | +27.6 / +0.1 | +20.1 / -30.4 | 10.0% / 6.9% |
4206///
4207/// and on the LONG-GOP gate (`bd_rate_film_long_gop`, 48 pictures, film B
4208/// only), where the anchors' non-skip area is the known gap:
4209///
4210/// | arm | film B long GOP | wall ours |
4211/// |---|---|---|
4212/// | off (control) | +89.8 / +9.1 | 477.5s |
4213/// | min side 8 | +89.6 / +9.0 | 514.1s |
4214///
4215/// The two gates disagree in SIGN on film B -- 0.3/0.3 worse over 12
4216/// pictures, 0.2/0.1 better over 48 -- and film A moves 0.2/0.1 the good way
4217/// only at min side 16, which is exactly where film B loses 0.7 on both
4218/// columns. Nothing here meets the keep rule (both films down on both
4219/// columns, or one down >=0.5 with the other flat), and the long-GOP gain
4220/// costs +7.7% wall. OBMC stays OFF at every preset.
4221fn obmc_min_side() -> usize {
4222 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
4223 *N.get_or_init(|| {
4224 std::env::var("EC_AV1_OBMC_MIN")
4225 .ok()
4226 .and_then(|v| v.parse().ok())
4227 .unwrap_or(8)
4228 })
4229}
4230
4231/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
4232/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
4233/// same frame-CDF price the coefficients of a non-screen frame are estimated
4234/// with, not the static default table.
4235/// The same price for whichever alphabet the writer will really use for this
4236/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
4237/// (`allow_warped_motion` and at least one warp sample), otherwise the
4238/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
4239/// search pay it, so the alphabet cancels out of a comparison and only its
4240/// per-value spread decides.
4241fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
4242 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
4243 return 0.0;
4244 };
4245 match warp_alphabet {
4246 true => crate::tile::motion_mode_symbol_bits(row, motion),
4247 false => crate::tile::obmc_symbol_bits(row, motion == 1),
4248 }
4249}
4250
4251/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
4252/// candidate, the header's `allow_warped_motion` and the sequence's
4253/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
4254/// native keep table, against the same build with the knob off:
4255///
4256/// | clip | warp on | off |
4257/// |---|---|---|
4258/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
4259/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
4260/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
4261///
4262/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
4263/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
4264/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
4265/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
4266/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
4267/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
4268/// this is a measured loss, not an inert knob. Same shape as the OBMC
4269/// candidate above it (`obmc_min_side`): a local RD win that does not convert
4270/// into ladder bytes.
4271///
4272/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
4273/// because a tool whose gain is local and whose cost is the rate it adds is
4274/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
4275///
4276/// | clip | warp on | off (both at lambda 0.05) |
4277/// |---|---|---|
4278/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
4279/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
4280/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
4281///
4282/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
4283/// column inside 0.1 everywhere -- which reads as a keep rather than the
4284/// 0.7/0.9 loss it was.
4285///
4286/// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table
4287/// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5,
4288/// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and
4289/// ran the conformance shape the lambda lane deferred: every warp stream
4290/// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1`
4291/// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside
4292/// a 16-tile frame, sample walk and all), and tile bytes still do not depend
4293/// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks
4294/// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it,
4295/// `allow_warped_motion` and `enable_warped_motion` back off together.
4296///
4297/// The WARPED_CAUSAL prediction of one square single-reference block: the
4298/// decoder's own warp-sample walk (`decode::find_samples` +
4299/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
4300/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
4301/// grid -- never a second implementation of any of the three. `None` when the
4302/// block would code no motion_mode symbol at all, when it has no warp sample
4303/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
4304/// or when the projection is not filter-representable (the decoder would then
4305/// predict translationally, so the mode is pure cost).
4306#[allow(clippy::too_many_arguments)]
4307fn warp_prediction(
4308 grid: &MiGrid,
4309 (mi_row, mi_col): (usize, usize),
4310 (mi_rows, mi_cols): (usize, usize),
4311 (x, y): (usize, usize),
4312 side: usize,
4313 mv: (i32, i32),
4314 ref_frame: i8,
4315 ref_planes: [(&[u16], usize, usize, usize); 3],
4316 fctx: &crate::decode::FrameCtx,
4317) -> Option<[Vec<u8>; 3]> {
4318 let n4 = side / 4;
4319 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
4320 return None;
4321 }
4322 let mut samples = crate::decode::find_samples(
4323 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
4324 );
4325 if samples.is_empty() {
4326 return None;
4327 }
4328 if samples.len() > 1 {
4329 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
4330 }
4331 let params = crate::warp::find_projection(
4332 &samples,
4333 side as i32,
4334 side as i32,
4335 mv.1,
4336 mv.0,
4337 mi_row as i32,
4338 mi_col as i32,
4339 )?;
4340 let mut pred = [
4341 vec![0u16; side * side],
4342 vec![0u16; side * side / 4],
4343 vec![0u16; side * side / 4],
4344 ];
4345 // The translational prediction first, exactly as the decoder builds it,
4346 // then the affine one over the planes whose OWN block is at least 8x8
4347 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
4348 // 4x4 chroma stays translational).
4349 for (i, r) in ref_planes.into_iter().enumerate() {
4350 let luma_plane = i == 0;
4351 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
4352 let s = if luma_plane { side } else { side / 2 };
4353 mc::predict(
4354 r.0,
4355 r.1,
4356 r.2,
4357 r.3,
4358 mv_to_q4(px, mv.1, luma_plane),
4359 mv_to_q4(py, mv.0, luma_plane),
4360 s,
4361 s,
4362 &mut pred[i],
4363 fctx,
4364 );
4365 if crate::decode::warp_plane_allowed(s, s) {
4366 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
4367 crate::warp::warp_affine(
4368 &params,
4369 r.0,
4370 r.2 as i32,
4371 r.3 as i32,
4372 r.1 as i32,
4373 &mut pred[i],
4374 px as i32,
4375 py as i32,
4376 cside,
4377 cside,
4378 cside,
4379 sub,
4380 sub,
4381 fctx,
4382 );
4383 }
4384 }
4385 let [py_buf, pu_buf, pv_buf] = pred;
4386 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
4387 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
4388}
4389
4390/// What tile.rs' `write_compound_ref_frames` pays for the pair
4391/// `(ref0, ref1)`, symbol for symbol, each at the context its own
4392/// `single_ref_p*_ctx`/`uni_comp_ref_p1_ctx`/`comp_reference_type_ctx`
4393/// derives from the block's above/left neighbours -- plus the `comp_mode`
4394/// symbol itself at `reference_mode_ctx`.
4395///
4396/// Before lane-ctx this was four constants at CDF row 0 that assumed the pair
4397/// was LAST+GOLDEN or LAST+ALTREF: `comp_bwdref[0][0] = 1` prices a BWDREF or
4398/// ALTREF2 partner as ALTREF and drops its `p6` symbol entirely, and the
4399/// `uni_comp_ref` leaves price a LAST+LAST2 pair as LAST+GOLDEN.
4400pub(crate) fn compound_ref_bits(
4401 (ref0, ref1): (i8, i8),
4402 stack: &crate::mvstack::MvStack,
4403) -> f64 {
4404 use crate::mvstack::{
4405 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4406 comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx,
4407 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
4408 uni_comp_ref_p1_ctx,
4409 };
4410 let (a, a1) = stack.above_refs;
4411 let (l, l1) = stack.left_refs;
4412 let unidir = is_uni_comp_ref(ref0, ref1);
4413 let comp_mode = symbol_bits(
4414 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4415 1,
4416 );
4417 let ref_type = symbol_bits(
4418 &cdf::COMP_REF_TYPE[comp_reference_type_ctx(stack.above_nbr, stack.left_nbr)],
4419 usize::from(!unidir),
4420 );
4421 if unidir {
4422 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
4423 let p0 = symbol_bits(
4424 &cdf::UNI_COMP_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4425 usize::from(both_backward),
4426 );
4427 if both_backward {
4428 return comp_mode + ref_type + p0;
4429 }
4430 let past_last2 = ref1 != LAST2_FRAME;
4431 let p1 = symbol_bits(
4432 &cdf::UNI_COMP_REF[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
4433 usize::from(past_last2),
4434 );
4435 let p2 = if past_last2 {
4436 symbol_bits(
4437 &cdf::UNI_COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4438 usize::from(ref1 == GOLDEN_FRAME),
4439 )
4440 } else {
4441 0.0
4442 };
4443 return comp_mode + ref_type + p0 + p1 + p2;
4444 }
4445 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
4446 let fwd = symbol_bits(
4447 &cdf::COMP_REF[single_ref_p3_ctx(a, a1, l, l1)][0],
4448 usize::from(far),
4449 ) + if far {
4450 symbol_bits(
4451 &cdf::COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4452 usize::from(ref0 == GOLDEN_FRAME),
4453 )
4454 } else {
4455 symbol_bits(
4456 &cdf::COMP_REF[single_ref_p4_ctx(a, a1, l, l1)][1],
4457 usize::from(ref0 == LAST2_FRAME),
4458 )
4459 };
4460 let is_altref = ref1 == ALTREF_FRAME;
4461 let bwd = symbol_bits(
4462 &cdf::COMP_BWDREF[single_ref_p2_ctx(a, a1, l, l1)][0],
4463 usize::from(is_altref),
4464 ) + if is_altref {
4465 0.0
4466 } else {
4467 symbol_bits(
4468 &cdf::COMP_BWDREF[single_ref_p6_ctx(a, a1, l, l1)][1],
4469 usize::from(ref1 == ALTREF2_FRAME),
4470 )
4471 };
4472 comp_mode + ref_type + fwd + bwd
4473}
4474
4475/// What the `skip` symbol costs at the context tile.rs really codes it with
4476/// (`above_skip[mi_c] + left_skip[mi_r]`, the two cells the MV stack now
4477/// carries) instead of row 0 -- the pricer's skip-versus-residual margin is
4478/// exactly the difference between this symbol's two values, so the row it is
4479/// read from moves that decision (class pricer-context-zero, lane-ctx).
4480pub(crate) fn skip_bits_at(stack: &crate::mvstack::MvStack, skip: bool) -> f64 {
4481 let ctx = usize::from(stack.above_skip) + usize::from(stack.left_skip);
4482 symbol_bits(&cdf::SKIP[ctx], usize::from(skip))
4483}
4484
4485/// What the `is_inter` symbol costs at tile.rs' own `intra_inter_ctx` -- the
4486/// neighbours' intra/inter state, with an out-of-tile side contributing
4487/// nothing, off the same two cells (lane-ctx).
4488pub(crate) fn intra_inter_bits_at(stack: &crate::mvstack::MvStack, inter: bool) -> f64 {
4489 let ctx = crate::tile::intra_inter_ctx(
4490 stack.above_nbr.is_some(),
4491 stack.left_nbr.is_some(),
4492 stack.above_nbr.is_some_and(|n| n.is_inter),
4493 stack.left_nbr.is_some_and(|n| n.is_inter),
4494 );
4495 symbol_bits(&cdf::INTRA_INTER[ctx], usize::from(inter))
4496}
4497
4498/// The `comp_mode = 0` symbol tile.rs' `write_comp_mode` codes ahead of a
4499/// SINGLE-reference block's reference syntax, at `reference_mode_ctx`'s own
4500/// context -- zero on a frame that carries no `reference_select` bit, where
4501/// the writer codes no symbol at all.
4502fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 {
4503 if !reference_select() {
4504 return 0.0;
4505 }
4506 symbol_bits(
4507 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4508 0,
4509 )
4510}
4511
4512/// What tile.rs' `write_single_ref` pays for `ref_frame`, symbol for symbol,
4513/// each at the context that symbol's own `single_ref_p*_ctx` derives from the
4514/// block's above/left neighbours -- plus the `comp_mode = 0` symbol
4515/// `write_comp_mode` codes ahead of it on a `reference_select` frame.
4516/// LAST is p1=0,p3=0,p4=0,
4517/// LAST2 p1=0,p3=0,p4=1, LAST3 p1=0,p3=1,p5=0, GOLDEN p1=0,p3=1,p5=1,
4518/// BWDREF p1=1,p2=0,p6=0, ALTREF2 p1=1,p2=0,p6=1 and ALTREF p1=1,p2=1.
4519/// Before lane-pricer every BACKWARD reference was priced as LAST -- three
4520/// symbols off the wrong CDFs -- which is what made the search believe an
4521/// ALTREF block cost the same syntax as a LAST one. The `comp_mode` term is
4522/// lane-ctx2's: a compound candidate paid `comp_mode = 1` while a single one
4523/// paid nothing at all, so compound was overcharged by the whole symbol.
4524pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 {
4525 use crate::mvstack::{
4526 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4527 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
4528 single_ref_p5_ctx, single_ref_p6_ctx,
4529 };
4530 let (a, a1) = stack.above_refs;
4531 let (l, l1) = stack.left_refs;
4532 let comp_mode = comp_mode_single_bits(stack);
4533 let backward = ref_frame >= BWDREF_FRAME;
4534 let p1 = symbol_bits(
4535 &cdf::SINGLE_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4536 usize::from(backward),
4537 );
4538 if backward {
4539 let is_altref = ref_frame == ALTREF_FRAME;
4540 let p2 = symbol_bits(
4541 &cdf::SINGLE_REF[single_ref_p2_ctx(a, a1, l, l1)][1],
4542 usize::from(is_altref),
4543 );
4544 return comp_mode
4545 + p1
4546 + p2
4547 + if is_altref {
4548 0.0
4549 } else {
4550 symbol_bits(
4551 &cdf::SINGLE_REF[single_ref_p6_ctx(a, a1, l, l1)][5],
4552 usize::from(ref_frame == ALTREF2_FRAME),
4553 )
4554 };
4555 }
4556 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
4557 comp_mode + p1 + symbol_bits(
4558 &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2],
4559 usize::from(far),
4560 ) + if far {
4561 symbol_bits(
4562 &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4],
4563 usize::from(ref_frame == GOLDEN_FRAME),
4564 )
4565 } else {
4566 symbol_bits(
4567 &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3],
4568 usize::from(ref_frame == LAST2_FRAME),
4569 )
4570 }
4571}
4572
4573pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
4574 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
4575 let width = cdf[symbol] - low;
4576 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
4577 // 32769 prices a symbol can carry; the `log2` behind each is computed
4578 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
4579 // profile -- this function is called for every symbol of every candidate
4580 // the RD search prices). Each entry is exactly the expression this used
4581 // to evaluate, so every price is bit-identical.
4582 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
4583 PRICES.get_or_init(|| {
4584 (0..=32768u32)
4585 .map(|w| -(f64::from(w) / 32768.0).log2())
4586 .collect()
4587 })[usize::from(width)]
4588}
4589
4590/// What the tile writer spends to say a block is coded in each of the thirteen
4591/// modes, given the modes of the blocks above it and to its left: the luma mode
4592/// symbol against the CDF those two neighbours pick, the angle delta a
4593/// directional mode carries, and the chroma mode symbol, whose CDF the luma
4594/// mode itself indexes.
4595///
4596/// Without this the search is blind to what a mode costs to name, which is not
4597/// a rounding error: a directional mode on a picture that does not run that way
4598/// is a rate loss the squared error never sees.
4599/// Codes one square of the picture as a single block: searches the luma mode,
4600/// codes both chroma planes DC, and hands back the block and what it cost --
4601/// squared error plus lambda times the bits its symbols spend.
4602/// How many halvings of a `side`-square block's transform the `tx_depth`
4603/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
4604/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
4605fn max_tx_depth(side: usize) -> usize {
4606 match side {
4607 8 => 1,
4608 16 | 32 => 2,
4609 _ => 0,
4610 }
4611}
4612
4613/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
4614/// Priced at context row 0 -- the writer picks the real row from its
4615/// neighbours' transform sizes, which the search has no view of; the term is
4616/// the same for every depth of one block either way, so it only shifts the
4617/// depth-0-versus-split margin, never the ordering between two splits.
4618fn tx_depth_bits(side: usize, depth: usize) -> f64 {
4619 match side {
4620 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
4621 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
4622 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
4623 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
4624 }
4625}
4626
4627/// lane-split: a multiplier on the RATE term of the transform-SPLIT trial
4628/// only -- the intra `tx_depth` depth>0 candidates in [`code_square`] and the
4629/// inter var-tx depth-1 trial in [`commit_inter_luma`]. `1.0` is the control
4630/// (the mode search's own weight); below 1 the split trial is charged less
4631/// for its bits and fires more often.
4632///
4633/// The knob the class `rd-rate-term-calibration` asks for: lane-txd made the
4634/// `tx_depth` SYMBOL price correct and every film row got worse, because the
4635/// correct row is a one-sided push away from splitting (depth 0 up to 1.5
4636/// bits cheaper at ctx 2, which is 66% of an inter frame's intra blocks) --
4637/// so what is mis-calibrated is the weight the split's rate is judged under,
4638/// not the price. `EC_AV1_SPLIT_LAMBDA`.
4639pub(crate) fn split_lambda_mult() -> f64 {
4640 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4641 crate::envflags::var("EC_AV1_SPLIT_LAMBDA")
4642 .ok()
4643 .and_then(|v| v.parse().ok())
4644 .unwrap_or(SPLIT_LAMBDA)
4645 });
4646 *M
4647}
4648
4649/// The shipped value of [`split_lambda_mult`]. See lanes/split.report.md for
4650/// the sweep that chose it.
4651const SPLIT_LAMBDA: f64 = 1.0;
4652
4653/// lane-split census (`EC_AV1_SPLIT_CENSUS=1`): the split decision itself,
4654/// bucketed by site (0 = intra `tx_depth`, 1 = inter var-tx), frame type
4655/// (0 = key, 1 = inter) and block side (8/16/32/64). Ten counters per bucket:
4656/// trials offered, trials the split won, then the (rate, distortion) of the
4657/// split and flat arms summed apart for the split-won and flat-won trials --
4658/// rate scaled by 64 into an integer counter, as [`TXRD_STATS`] is.
4659static SPLIT_CENSUS: [std::sync::atomic::AtomicU64; 160] =
4660 [const { std::sync::atomic::AtomicU64::new(0) }; 160];
4661
4662/// Whether [`SPLIT_CENSUS`] is armed, read once.
4663pub(crate) fn split_census_on() -> bool {
4664 static ON: std::sync::LazyLock<bool> =
4665 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_SPLIT_CENSUS"));
4666 *ON
4667}
4668
4669/// Where one (site, frame type, block side) bucket starts in [`SPLIT_CENSUS`].
4670/// Sides below 8 and above 64 fold into the end rows, which no caller offers.
4671fn split_census_base(site: usize, key: bool, side: usize) -> usize {
4672 let side_idx = (side.trailing_zeros() as usize).saturating_sub(3).min(3);
4673 ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10
4674}
4675
4676/// Records one split trial into [`SPLIT_CENSUS`]. `split` and `flat` are each
4677/// `(rate in bits, distortion as squared error)`.
4678fn split_census(
4679 site: usize,
4680 key: bool,
4681 side: usize,
4682 split_won: bool,
4683 split: (f64, f64),
4684 flat: (f64, f64),
4685) {
4686 use std::sync::atomic::Ordering::Relaxed;
4687 let base = split_census_base(site, key, side);
4688 let add = |i: usize, v: u64| {
4689 SPLIT_CENSUS[base + i].fetch_add(v, Relaxed);
4690 };
4691 add(0, 1);
4692 let off = if split_won {
4693 add(1, 1);
4694 2
4695 } else {
4696 6
4697 };
4698 let (win, lose) = if split_won { (split, flat) } else { (flat, split) };
4699 add(off, (win.0 * 64.0).max(0.0) as u64);
4700 add(off + 1, win.1.max(0.0) as u64);
4701 add(off + 2, (lose.0 * 64.0).max(0.0) as u64);
4702 add(off + 3, lose.1.max(0.0) as u64);
4703}
4704
4705/// Prints [`SPLIT_CENSUS`] to stderr when `EC_AV1_SPLIT_CENSUS=1`. Called at
4706/// the end of every `Av1Encoder::encode_frames` call and NOT reset, so the
4707/// last table a run prints is the whole encode's total (there is no flush
4708/// hook the encoder API guarantees to reach).
4709pub(crate) fn dump_split_census() {
4710 use std::sync::atomic::Ordering::Relaxed;
4711 eprintln!(
4712 "SPLITCENSUS site frame side offered split share% \
4713 win_rate win_dist lose_rate lose_dist"
4714 );
4715 for site in 0..2 {
4716 for key in [true, false] {
4717 for side_idx in 0..4 {
4718 let base = split_census_base(site, key, 8 << side_idx);
4719 let v: [u64; 10] = std::array::from_fn(|i| SPLIT_CENSUS[base + i].load(Relaxed));
4720 if v[0] == 0 {
4721 continue;
4722 }
4723 let (n, s) = (v[0] as f64, v[1] as f64);
4724 // Winner terms live at 2,3 (split won) and 6,7 (flat won),
4725 // loser terms at 4,5 and 8,9 -- so each mean is one sum over
4726 // all `n` trials, not a mean of two means.
4727 eprintln!(
4728 "SPLITCENSUS {} {} {:>3} {:>7} {:>7} {:>5.1} \
4729 {:>9.2} {:>9.0} {:>9.2} {:>9.0}",
4730 if site == 0 { "intra" } else { "inter" },
4731 if key { "key " } else { "inter" },
4732 8 << side_idx,
4733 v[0],
4734 v[1],
4735 100.0 * s / n,
4736 (v[2] + v[6]) as f64 / n / 64.0,
4737 (v[3] + v[7]) as f64 / n,
4738 (v[4] + v[8]) as f64 / n / 64.0,
4739 (v[5] + v[9]) as f64 / n,
4740 );
4741 }
4742 }
4743 }
4744}
4745
4746/// lane-newmv: a multiplier on the mv RATE term of the BLOCK-level inter
4747/// decision only -- the `NEWMV` candidate's own mv residual + DRL bits, not
4748/// its mode/reference syntax and not the search's own cost function
4749/// ([`crate::motion`]'s `EC_AV1_MV_SEARCH_LAMBDA` is that one). `1.0` is the
4750/// control; below 1 a coded vector is charged less and `NEWMV` wins more
4751/// blocks. `EC_AV1_MV_LAMBDA`, class `rd-rate-term-calibration`.
4752pub(crate) fn mv_lambda_mult() -> f64 {
4753 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4754 crate::envflags::var("EC_AV1_MV_LAMBDA")
4755 .ok()
4756 .and_then(|v| v.parse().ok())
4757 .unwrap_or(MV_LAMBDA)
4758 });
4759 *M
4760}
4761
4762/// The shipped value of [`mv_lambda_mult`]. See lanes/newmv.report.md.
4763const MV_LAMBDA: f64 = 1.0;
4764
4765/// What a `NEWMV` candidate is charged ON TOP of its own priced mv syntax
4766/// bits, `(EC_AV1_MV_LAMBDA - 1) * mv_bits` (added to the candidate's bits,
4767/// which the RD cost multiplies by lambda). Zero at the default weight.
4768fn mv_rate_surcharge(mv_bits: f64) -> f64 {
4769 (mv_lambda_mult() - 1.0) * mv_bits
4770}
4771
4772/// lane-newmv census (`EC_AV1_NEWMV_CENSUS=1`): the block-level `NEWMV`
4773/// decision, bucketed by block side (8/16/32/64). Eight counters per bucket:
4774/// 0 blocks that ran a `LAST` motion search, 1 of those whose vector the
4775/// writer could name (offered to RD), 2 blocks `NEWMV` won, 3 the summed RD
4776/// cost it won by, 4 the summed cost it lost by, 5 the summed
4777/// `|mv - nearest_mv|` (1/8-pel units, both axes), 6 blocks whose searched
4778/// vector IS the stack's `NEARESTMV`, 7 the summed mv syntax bits (x64, as
4779/// [`SPLIT_CENSUS`]'s rate terms are). Four globals follow at 32: extra-
4780/// reference searches offered/skipped by [`EXTRA_NEW_SKIP_MARGIN`], leaf
4781/// second-reference searches offered/skipped by [`LEAF_SECOND_NEW_MARGIN`].
4782static NEWMV_CENSUS: [std::sync::atomic::AtomicU64; 36] =
4783 [const { std::sync::atomic::AtomicU64::new(0) }; 36];
4784
4785/// Whether [`NEWMV_CENSUS`] is armed, read once.
4786pub(crate) fn newmv_census_on() -> bool {
4787 static ON: std::sync::LazyLock<bool> =
4788 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_NEWMV_CENSUS"));
4789 *ON
4790}
4791
4792/// Bumps one of [`NEWMV_CENSUS`]'s four global counters (32..36).
4793fn newmv_census_global(i: usize) {
4794 if newmv_census_on() {
4795 NEWMV_CENSUS[32 + i].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4796 }
4797}
4798
4799/// Records one block's `NEWMV` decision into [`NEWMV_CENSUS`]. `other_cost`
4800/// is the best cost the block had WITHOUT the `NEWMV` candidate (its
4801/// `NEAREST`/`NEAR`/`GLOBAL`/intra winner), `new_cost` the `NEWMV`
4802/// candidate's own; both `f64::INFINITY` is a block that offered neither.
4803fn newmv_census_block(
4804 side: usize,
4805 offered: bool,
4806 new_cost: f64,
4807 other_cost: f64,
4808 mv: (i32, i32),
4809 nearest: (i32, i32),
4810 mv_bits: f64,
4811) {
4812 if !newmv_census_on() {
4813 return;
4814 }
4815 use std::sync::atomic::Ordering::Relaxed;
4816 let base = (side.trailing_zeros() as usize).saturating_sub(3).min(3) * 8;
4817 let add = |i: usize, v: u64| {
4818 NEWMV_CENSUS[base + i].fetch_add(v, Relaxed);
4819 };
4820 add(0, 1);
4821 if !offered {
4822 return;
4823 }
4824 add(1, 1);
4825 if new_cost < other_cost {
4826 add(2, 1);
4827 add(3, (other_cost - new_cost).max(0.0) as u64);
4828 } else {
4829 add(4, (new_cost - other_cost).max(0.0) as u64);
4830 }
4831 add(5, ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64);
4832 if mv == nearest {
4833 add(6, 1);
4834 }
4835 add(7, (mv_bits * 64.0).max(0.0) as u64);
4836}
4837
4838/// Prints [`NEWMV_CENSUS`] to stderr when `EC_AV1_NEWMV_CENSUS=1`, on the
4839/// same guard [`dump_split_census`] rides (cumulative, so the last table a
4840/// run prints is the whole encode's).
4841pub(crate) fn dump_newmv_census() {
4842 use std::sync::atomic::Ordering::Relaxed;
4843 eprintln!(
4844 "NEWMVCENSUS side searched offered won won% win_margin lose_margin \
4845 mv_dist_q3 mv==nearest% mv_bits"
4846 );
4847 for side_idx in 0..4 {
4848 let base = side_idx * 8;
4849 let v: [u64; 8] = std::array::from_fn(|i| NEWMV_CENSUS[base + i].load(Relaxed));
4850 if v[0] == 0 {
4851 continue;
4852 }
4853 let off = v[1].max(1) as f64;
4854 eprintln!(
4855 "NEWMVCENSUS {:>3} {:>8} {:>8} {:>7} {:>5.1} {:>10.0} {:>11.0} {:>10.2} {:>12.1} {:>7.2}",
4856 8 << side_idx,
4857 v[0],
4858 v[1],
4859 v[2],
4860 100.0 * v[2] as f64 / off,
4861 v[3] as f64 / v[2].max(1) as f64,
4862 v[4] as f64 / (v[1] - v[2]).max(1) as f64,
4863 v[5] as f64 / off,
4864 100.0 * v[6] as f64 / off,
4865 v[7] as f64 / off / 64.0,
4866 );
4867 }
4868 // lane-hpmv: how many mv components this encode coded an eighth-pel bit
4869 // for, and how many of those named a vector no non-hp frame can code.
4870 let (hp_all, hp_eighth) = crate::tile::hp_symbols();
4871 eprintln!(
4872 "NEWMVCENSUS hp symbols {hp_all}, of them eighth-pel {hp_eighth} ({:.1}%)",
4873 100.0 * hp_eighth as f64 / hp_all.max(1) as f64,
4874 );
4875 let g: [u64; 4] = std::array::from_fn(|i| NEWMV_CENSUS[32 + i].load(Relaxed));
4876 eprintln!(
4877 "NEWMVCENSUS pre-RD margin skips: extra-reference {}/{} ({:.1}%), \
4878 leaf second reference {}/{} ({:.1}%)",
4879 g[1],
4880 g[0],
4881 100.0 * g[1] as f64 / g[0].max(1) as f64,
4882 g[3],
4883 g[2],
4884 100.0 * g[3] as f64 / g[2].max(1) as f64,
4885 );
4886 let [calls, evals, _subpel, rounds, near_pred, unmoved, widest, widest_moves] =
4887 crate::motion::take_census();
4888 let per = |n: u64| n as f64 / calls.max(1) as f64;
4889 eprintln!(
4890 "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \
4891 winner within +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%, \
4892 moved at the WIDEST step {:.1}% of calls ({:.2} such moves/call)",
4893 per(evals),
4894 per(rounds),
4895 100.0 * near_pred as f64 / calls.max(1) as f64,
4896 100.0 * unmoved as f64 / calls.max(1) as f64,
4897 100.0 * widest as f64 / calls.max(1) as f64,
4898 per(widest_moves),
4899 );
4900}
4901
4902/// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
4903/// the intra witness's fire count stays its own.
4904pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
4905 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
4906
4907/// lane-txrd: a multiplier on the rate term of the TRANSFORM-TYPE decision
4908/// only (`EC_AV1_TXRD_LAMBDA`, default 1.0 = the mode search's own weight).
4909/// `0` compares types on reconstruction error alone, which is what separates
4910/// a rate-term calibration (class `rd-rate-term-calibration`) from a
4911/// distortion the trial mis-measures.
4912pub(crate) fn tx_type_lambda_mult() -> f64 {
4913 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4914 crate::envflags::var("EC_AV1_TXRD_LAMBDA")
4915 .ok()
4916 .and_then(|v| v.parse().ok())
4917 .unwrap_or(1.0)
4918 });
4919 *M
4920}
4921
4922/// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own
4923/// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the
4924/// default weight of 1 and for `DCT_DCT` itself. The instrument the film
4925/// question needs: at weight 1 the five-type intra search spends 1.2% more
4926/// bytes for 0.04 dB on both film rows, so what it under-charges is the rate
4927/// of the type it picks.
4928pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 {
4929 if tx_type == TxType::DctDct {
4930 0.0
4931 } else {
4932 lambda * (tx_type_lambda_mult() - 1.0) * bits
4933 }
4934}
4935
4936/// lane-txrd instrument: over the FLAT inter luma decision, the summed
4937/// reconstruction error and priced bits of the type the search chose against
4938/// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an
4939/// integer counter. `EC_AV1_TXRD_CENSUS`.
4940pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [
4941 std::sync::atomic::AtomicU64::new(0),
4942 std::sync::atomic::AtomicU64::new(0),
4943 std::sync::atomic::AtomicU64::new(0),
4944 std::sync::atomic::AtomicU64::new(0),
4945 std::sync::atomic::AtomicU64::new(0),
4946 std::sync::atomic::AtomicU64::new(0),
4947 std::sync::atomic::AtomicU64::new(0),
4948];
4949
4950/// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib
4951/// build would warn `dead_code` (class from lane-txset2's `coeff_bits`).
4952#[cfg(test)]
4953pub(crate) fn take_txrd_stats() -> [u64; 7] {
4954 std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
4955}
4956
4957/// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
4958#[cfg(test)]
4959pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
4960 std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
4961}
4962
4963/// How many luma transform units resolved to each [`TxType`], indexed by the
4964/// enum's own discriminant (lane-txset): the fire count a witness asserts on,
4965/// and the instrument that says which types the search actually reaches.
4966pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
4967 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
4968
4969/// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the
4970/// counts to its own encode.
4971#[cfg(test)]
4972pub(crate) fn take_tx_type_hits() -> [usize; 16] {
4973 std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
4974}
4975
4976/// How many blocks resolved to each `tx_depth`, the fire count that says
4977/// whether the depth search below reaches its candidates at all.
4978static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
4979 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
4980
4981/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
4982/// to its own encode.
4983#[cfg(test)]
4984pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
4985 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
4986}
4987
4988/// How many inter blocks resolved to each var-tx depth (0 = one transform
4989/// over the whole block, 1 = its four halves), the fire count a gate prints
4990/// to see the split search reach its candidates at all. Indexed
4991/// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census
4992/// says which of the four block classes the split reaches -- the 32x32 root
4993/// and the compound blocks are this lane's two new ones.
4994static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
4995 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
4996
4997/// Whether a 32x32 inter winner searches its own var-tx depth (the four
4998/// 16x16 units against the flat transform) instead of coding depth 0 blind.
4999/// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off.
5000///
5001/// Rejected three times on the bars rows of the native gate (flat to +0.3).
5002/// lane-av1resweep re-judged it on the two REAL film crops at
5003/// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file
5004/// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`):
5005///
5006/// | clip | shipped | tx32 depth | + [`compound_var_tx`] |
5007/// |---|---|---|---|
5008/// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 |
5009/// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 |
5010/// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 |
5011/// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 |
5012/// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 |
5013///
5014/// The bars rows are ~90% zero-intra-cost cells, so the split never had
5015/// residual to reach there -- the tool was being judged on content that
5016/// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
5017fn tx32_depth_search() -> bool {
5018 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5019 crate::envflags::var("EC_AV1_TX32_DEPTH").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
5020 });
5021 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
5022}
5023
5024/// Whether a COMPOUND inter winner is offered the var-tx split at all: its
5025/// trial units have to be predicted from BOTH references
5026/// ([`mc_trial_compound`]) or the split would re-predict them by single-
5027/// reference translation, which is not what the decoder reconstructs.
5028/// ON by default (the table on [`tx32_depth_search`]: on real film it is
5029/// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the
5030/// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
5031/// `EC_AV1_COMP_VARTX`.
5032fn compound_var_tx() -> bool {
5033 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5034 crate::envflags::var("EC_AV1_COMP_VARTX").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
5035 });
5036 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
5037}
5038
5039/// How many 32x32-and-below inter blocks each reference frame won, indexed by
5040/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
5041/// fire count a gate prints to see an extra reference reach a block at all
5042/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
5043/// chosen is a pyramid that costs bytes and buys nothing).
5044static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
5045 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
5046
5047/// Reads [`REF_FRAME_HITS`] and zeroes it.
5048#[cfg(test)]
5049pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
5050 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
5051}
5052
5053/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
5054#[cfg(test)]
5055pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] {
5056 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
5057}
5058
5059/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
5060/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
5061/// is one flag, depth 1 is a split root plus one unsplit flag per child
5062/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
5063/// or a 4x4 sub-size).
5064fn txfm_split_bits(side: usize, depth: usize) -> f64 {
5065 let max_tx = side.min(64);
5066 let ctx = |tx: usize| {
5067 crate::decode::txfm_partition_ctx_rect(
5068 crate::decode::TXFM_CTX_INIT,
5069 crate::decode::TXFM_CTX_INIT,
5070 side,
5071 tx,
5072 tx,
5073 )
5074 };
5075 if depth == 0 {
5076 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
5077 }
5078 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
5079 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
5080}
5081
5082/// spec 5.11.40 / libaom `av1_get_tx_type`: an INTER block's chroma transform
5083/// type is never coded -- the decoder takes the LUMA type of the block's
5084/// chroma-reference position and reduces it to the set the chroma size allows
5085/// ([`crate::decode::reduce_inherited_chroma_tx_type`]). This encoder
5086/// quantised chroma under a `DCT_DCT` basis whatever luma chose, so every
5087/// non-`DCT_DCT` luma winner had its chroma levels inverse-transformed on a
5088/// basis they were never produced for: on the bars gate row the luma of the
5089/// unconditional tx-type arm came out BETTER on every frame (53.66 -> 53.70
5090/// dB) while V lost seven decibels (52.52 -> 45.53) -- the whole 20-point BD
5091/// collapse two lanes attributed to the type PRICE (class
5092/// `parsed then discarded` / `override slot on one arm`: a decoder-derived
5093/// field the encoder never mirrored).
5094///
5095/// Re-codes the two chroma planes of a committed inter block at the type the
5096/// decoder will use, `None` when the inherited type reduces to `DCT_DCT` and
5097/// the trials the caller already holds are right.
5098#[allow(clippy::too_many_arguments)]
5099fn recode_inter_chroma(
5100 chroma: &[Plane; 2],
5101 (x, y): (usize, usize),
5102 side: usize,
5103 mv: (i32, i32),
5104 refs: [(&[u16], usize, usize, usize); 2],
5105 second: Option<((i32, i32), [(&[u16], usize, usize, usize); 2])>,
5106 search: &Search,
5107 set: TxbSet,
5108 luma_tx_type: TxType,
5109 fctx: &crate::decode::FrameCtx,
5110) -> Option<[Trial; 2]> {
5111 let c = side / 2;
5112 let tx = crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx);
5113 if tx == TxType::DctDct {
5114 return None;
5115 }
5116 Some([0usize, 1].map(|p| match second {
5117 Some((mv1, r1)) => mc_trial_compound_typed(
5118 &chroma[p], x / 2, y / 2, c, (mv, mv1), false, refs[p], r1[p], search.base_q_idx,
5119 search.deadzone, set, tx, fctx,
5120 ),
5121 None => mc_trial_typed(
5122 &chroma[p], x / 2, y / 2, c, mv, false, refs[p].0, refs[p].1, refs[p].2, refs[p].3,
5123 false, search.base_q_idx, search.deadzone, set, tx, fctx,
5124 ),
5125 }))
5126}
5127
5128/// The inter block's own var-tx decision, once its motion vector is settled:
5129/// its residual as ONE transform over the whole block, or as the four
5130/// transforms of half the side the tree's first halving names. The prediction
5131/// is the same motion compensation either way, so the split trial
5132/// re-transforms the identical residual in four pieces -- it wins where four
5133/// small transforms carry a locally varying residual cheaper than one big
5134/// one. Commits the winner into `luma` and hands back its block-coordinate
5135/// levels, the depth the writer codes and the cost the winner adds to (or
5136/// takes off) the caller's already-computed flat cost.
5137///
5138/// Only for a block wholly inside the frame: past the true edge the reader's
5139/// var-tx recursion skips the units that fall outside
5140/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
5141/// leave the residual units this writes unpaired.
5142#[allow(clippy::too_many_arguments)]
5143fn commit_inter_luma(
5144 luma: &mut Plane,
5145 (x, y): (usize, usize),
5146 side: usize,
5147 mv: (i32, i32),
5148 reference: (&[u16], usize, usize, usize),
5149 search: &Search,
5150 flat: &Trial,
5151 skip: bool,
5152 // A COMPOUND winner's second half: the vector and reference planes the
5153 // trial units are blended from ([`mc_trial_compound`], the decoder's own
5154 // `comp_group_idx == 0` average). `None` is the single-reference block.
5155 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
5156 fctx: &crate::decode::FrameCtx,
5157) -> (Vec<i32>, u8, f64, Vec<TxType>) {
5158 // lane-txset2 step 1: the whole-block (depth 0) residual picks its own
5159 // type out of the two-type inter set the writer already codes a symbol
5160 // for, priced the same way the intra search is (sse + lambda * bits, the
5161 // bits carrying the `tx_type` symbol itself through RDOQ). A skipped
5162 // block codes no residual and the 64-point transform names no type.
5163 let mut flat_typed: Option<Trial> = None;
5164 let mut flat_type = TxType::DctDct;
5165 if !skip {
5166 // lane-intertx: on a `reduced_tx_set = 0` frame the search names the
5167 // Set1 alphabet the writer codes into ([`luma_set_for`], the shape
5168 // the intra search already takes), which is what makes the wider
5169 // seven-type candidate list below reachable -- and prices every
5170 // candidate, `IDTX` included, in the alphabet its symbol is really
5171 // coded into.
5172 if let Some(fset) =
5173 inter_luma_set(side).map(|set| luma_set_for(set, search.screen))
5174 {
5175 let lambda = search.lambda * tx_type_lambda_mult();
5176 let cost = |t: &Trial| t.sse + lambda * t.bits;
5177 for &tx_type in inter_tx_type_candidates(fset, search.screen) {
5178 if tx_type == TxType::DctDct {
5179 continue;
5180 }
5181 let candidate = match second {
5182 Some((mv1, ref1)) => mc_trial_compound_typed(
5183 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
5184 search.deadzone, fset, tx_type, fctx,
5185 ),
5186 None => mc_trial_typed(
5187 luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
5188 reference.3, false, search.base_q_idx, search.deadzone, fset, tx_type,
5189 fctx,
5190 ),
5191 };
5192 if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) {
5193 flat_type = tx_type;
5194 flat_typed = Some(candidate);
5195 }
5196 }
5197 }
5198 }
5199 // Counted at the return points, so the census names the types the block
5200 // really CODES -- a split unit's winner that the flat cost then beats was
5201 // never written (class `counter from refused stream`).
5202 let count = |types: &[TxType]| {
5203 for &t in types {
5204 INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5205 }
5206 };
5207 let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat);
5208 if crate::envflags::env_flag!("EC_AV1_TXRD_CENSUS") && !skip {
5209 use std::sync::atomic::Ordering::Relaxed;
5210 TXRD_STATS[0].fetch_add(1, Relaxed);
5211 TXRD_STATS[1].fetch_add(flat_ref.sse as u64, Relaxed);
5212 TXRD_STATS[2].fetch_add(flat.sse as u64, Relaxed);
5213 TXRD_STATS[3].fetch_add((flat_ref.bits * 64.0) as u64, Relaxed);
5214 TXRD_STATS[4].fetch_add((flat.bits * 64.0) as u64, Relaxed);
5215 // Is the `DCT_DCT` baseline the search compares against the trial
5216 // THIS function would build for the same block? A stale or
5217 // differently-predicted baseline is what would let a candidate win on
5218 // both terms at once (class `local-rd-on-references` vs a real
5219 // pricing defect); re-predicting it here is the only way to tell.
5220 if let Some(fset) = inter_luma_set(side) {
5221 let here = match second {
5222 Some((mv1, ref1)) => mc_trial_compound_typed(
5223 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
5224 search.deadzone, fset, TxType::DctDct, fctx,
5225 ),
5226 None => mc_trial_typed(
5227 luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
5228 reference.3, false, search.base_q_idx, search.deadzone, fset,
5229 TxType::DctDct, fctx,
5230 ),
5231 };
5232 TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed);
5233 TXRD_STATS[6].fetch_add((here.bits * 64.0) as u64, Relaxed);
5234 static DUMPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
5235 let n = TXRD_STATS[0].load(Relaxed);
5236 if here.sse * 2.0 < flat.sse && DUMPED.fetch_add(1, Relaxed) < 30 {
5237 eprintln!(
5238 "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \
5239 flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \
5240 sse={:.0} bits={:.1}",
5241 second.is_some(), flat.sse, flat.bits, here.sse, here.bits,
5242 flat_ref.sse, flat_ref.bits,
5243 );
5244 }
5245 }
5246 }
5247 // What the caller's already-counted `flat` cost has to be corrected by
5248 // when a non-`DCT_DCT` type won it, the same way the split delta below is.
5249 let flat_gain = (flat_ref.sse + search.lambda * flat_ref.bits)
5250 - (flat.sse + search.lambda * flat.bits);
5251 let eligible = tx_select()
5252 && tx_select_inter()
5253 && !skip
5254 && side >= 16
5255 && (second.is_none() || compound_var_tx())
5256 && (side != BLOCK || tx32_depth_search())
5257 && x + side <= luma.true_width
5258 && y + side <= luma.true_height;
5259 if !eligible {
5260 luma.commit(x, y, side, flat_ref);
5261 count(&[flat_type]);
5262 return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);
5263 }
5264 let tx = side / 2;
5265 let set = luma_set_for(
5266 if tx >= 32 {
5267 // lane-b64b: the 64x64 root's halved transform is TX_32X32.
5268 TxbSet::Luma32Inter
5269 } else if tx >= 16 {
5270 TxbSet::Luma16Inter
5271 } else {
5272 TxbSet::Luma8Inter
5273 },
5274 search.screen,
5275 );
5276 let mut levels = vec![0i32; side * side];
5277 let (mut sse, mut bits) = (0.0, 0.0);
5278 let mut units = Vec::with_capacity(4);
5279 // The split units are smaller than their block, so their `txb_skip`
5280 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
5281 // each unit's own commit publishes what the next one reads, coding order.
5282 luma.ctx.tu_split = true;
5283 // One type per unit in the writer's own raster order (tile.rs
5284 // `write_luma_tus`), all `DCT_DCT` when nothing else is offered.
5285 let mut split_types = vec![TxType::DctDct; 4];
5286 for tu_row in 0..2 {
5287 for tu_col in 0..2 {
5288 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
5289 let unit = |tx_type: TxType| match second {
5290 Some((mv1, ref1)) => mc_trial_compound_typed(
5291 luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1,
5292 search.base_q_idx, search.deadzone, set, tx_type, fctx,
5293 ),
5294 None => mc_trial_typed(
5295 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
5296 reference.3, false, search.base_q_idx, search.deadzone, set, tx_type, fctx,
5297 ),
5298 };
5299 let mut best: Option<(f64, TxType, Trial)> = None;
5300 for &tx_type in inter_tx_type_candidates(set, search.screen) {
5301 let candidate = unit(tx_type);
5302 let cost = candidate.sse + search.lambda * tx_type_lambda_mult() * candidate.bits;
5303 if best.as_ref().is_none_or(|(b, _, _)| cost < *b) {
5304 best = Some((cost, tx_type, candidate));
5305 }
5306 }
5307 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
5308 split_types[tu_row * 2 + tu_col] = tx_type;
5309 sse += trial.sse;
5310 bits += trial.bits;
5311 for row in 0..tx {
5312 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
5313 .copy_from_slice(&trial.levels[row * tx..][..tx]);
5314 }
5315 units.push((tu_x, tu_y, trial));
5316 }
5317 }
5318 luma.ctx.tu_split = false;
5319 let split_rate = bits + txfm_split_bits(side, 1);
5320 let flat_rate = flat_ref.bits + txfm_split_bits(side, 0);
5321 let split_cost = sse + search.lambda * split_lambda_mult() * split_rate;
5322 let flat_cost = flat_ref.sse + search.lambda * flat_rate;
5323 if split_census_on() {
5324 split_census(1, false, side, split_cost < flat_cost, (split_rate, sse), (flat_rate, flat_ref.sse));
5325 }
5326 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
5327 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
5328 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
5329 // in the leaf row (class `gate-blind-to-feature`).
5330 let counted = side <= BLOCK;
5331 if split_cost < flat_cost {
5332 for (tu_x, tu_y, trial) in &units {
5333 luma.commit(*tu_x, *tu_y, tx, trial);
5334 }
5335 if counted {
5336 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5337 }
5338 count(&split_types);
5339 return (levels, 1, flat_gain + split_cost - flat_cost, split_types);
5340 }
5341 if counted {
5342 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5343 }
5344 luma.commit(x, y, side, flat_ref);
5345 count(&[flat_type]);
5346 (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type])
5347}
5348
5349/// The largest distinct-colour count a block may hold and still be offered a
5350/// palette candidate at all: past it the k-means quantisation costs more
5351/// error than the map saves rate, and every trial is wasted wall.
5352///
5353/// Swept on the gate's own screen capture (lane-av1pal2, the
5354/// `unswept-decision-constants` class): 32 (the value this lane inherited)
5355/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
5356/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
5357/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
5358/// binds on nothing this content holds. 128 ships: best BD against both
5359/// references and no wall cost at all (6.1s, the same as at 32, because the
5360/// blocks it newly admits are ones the RD then keeps).
5361/// `EC_AV1_PAL_MAXCOLORS`.
5362fn palette_max_colors() -> usize {
5363 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5364 *N.get_or_init(|| {
5365 std::env::var("EC_AV1_PAL_MAXCOLORS")
5366 .ok()
5367 .and_then(|v| v.parse().ok())
5368 .unwrap_or(128)
5369 })
5370}
5371
5372/// The palettes worth trying for one block's luma, in the shape libaom's
5373/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
5374/// distinct colours takes them ALL (the prediction is then exact and the
5375/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
5376/// one-dimensional Lloyd iteration seeded evenly across its range -- both
5377/// offered, because which wins is an RD question the caller answers.
5378/// `block` is `side*side` source samples, row-major.
5379fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
5380 let mut histogram = [0u32; 256];
5381 for &v in block {
5382 histogram[usize::from(v)] += 1;
5383 }
5384 let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
5385 if present.len() < 2 {
5386 return Vec::new();
5387 }
5388 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
5389 let mut base = [0u16; 8];
5390 base[..colors.len()].copy_from_slice(colors);
5391 let map = block
5392 .iter()
5393 .map(|&v| {
5394 colors
5395 .iter()
5396 .enumerate()
5397 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
5398 .map(|(i, _)| i as u8)
5399 .expect("a palette holds at least two colours")
5400 })
5401 .collect();
5402 crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
5403 };
5404 if present.len() <= 8 {
5405 return vec![exact(&present)];
5406 }
5407 if present.len() > palette_max_colors() {
5408 return Vec::new();
5409 }
5410 let (lo, hi) = (
5411 i32::from(present[0]),
5412 i32::from(present[present.len() - 1]),
5413 );
5414 let mut out = Vec::with_capacity(2);
5415 for n in [8usize, 4] {
5416 // Even seeding across the block's own range, then four Lloyd passes
5417 // over the histogram (256 bins, not `side*side` pixels).
5418 let mut centres: Vec<f64> = (0..n)
5419 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
5420 .collect();
5421 for _ in 0..4 {
5422 let mut sums = vec![0f64; n];
5423 let mut counts = vec![0u32; n];
5424 for (v, &count) in histogram.iter().enumerate() {
5425 if count == 0 {
5426 continue;
5427 }
5428 let k = (0..n)
5429 .min_by(|&a, &b| {
5430 (centres[a] - v as f64)
5431 .abs()
5432 .total_cmp(&(centres[b] - v as f64).abs())
5433 })
5434 .expect("n >= 2");
5435 sums[k] += (v as u32 * count) as f64;
5436 counts[k] += count;
5437 }
5438 for k in 0..n {
5439 if counts[k] > 0 {
5440 centres[k] = sums[k] / f64::from(counts[k]);
5441 }
5442 }
5443 }
5444 let mut colors: Vec<u16> = centres
5445 .iter()
5446 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
5447 .collect();
5448 colors.sort_unstable();
5449 colors.dedup();
5450 if colors.len() >= 2 {
5451 out.push(exact(&colors));
5452 }
5453 }
5454 out
5455}
5456
5457#[allow(clippy::too_many_arguments)]
5458// ---------------------------------------------------------------------------
5459// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
5460// validity). A key frame that detected screen content and finds enough exact
5461// repeats in its own source sets `allow_intrabc`, which the spec forces every
5462// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
5463// its place when the copied blocks pay back the deblock/CDEF/LR the frame
5464// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
5465// ---------------------------------------------------------------------------
5466
5467/// Whether intra block copy is offered at all. **Off by default** --
5468/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
5469/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
5470/// but on the gate's real screen capture it MEASURED WORSE: setting
5471/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
5472/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
5473/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
5474/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
5475/// that detected no screen content.
5476fn intrabc_enabled() -> bool {
5477 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
5478 return forced;
5479 }
5480 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5481 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
5482}
5483
5484thread_local! {
5485 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
5486 /// probe runs both arms in one process, and the suite is one process, so
5487 /// an environment variable cannot separate them (same reason
5488 /// [`SCREEN_FORCE`] exists).
5489 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
5490}
5491
5492#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5493pub(crate) fn force_intrabc(value: Option<bool>) {
5494 INTRABC_FORCE.with(|c| c.set(value));
5495}
5496
5497/// How many of a screen frame's 16x16 blocks must have an exact repeat
5498/// somewhere else in the source before `allow_intrabc` is worth the in-loop
5499/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
5500/// constant class: `probe_intrabc_threshold` measures the arm at several
5501/// values.
5502fn intrabc_pct() -> usize {
5503 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5504 *N.get_or_init(|| {
5505 std::env::var("EC_AV1_INTRABC_PCT")
5506 .ok()
5507 .and_then(|v| v.parse().ok())
5508 .unwrap_or(10)
5509 })
5510}
5511
5512/// The pixel grid intrabc source positions are hashed on
5513/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
5514/// which keeps the block-hash table (and so the search) linear in the frame
5515/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
5516/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
5517/// bilinear interpolation decode.rs applies but this encoder does not.
5518fn intrabc_step() -> usize {
5519 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5520 *N.get_or_init(|| {
5521 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
5522 .ok()
5523 .and_then(|v| v.parse().ok())
5524 .unwrap_or(4);
5525 if n % 2 == 0 { n.max(2) } else { 4 }
5526 })
5527}
5528
5529/// The side of the luma square the block-hash table is keyed on.
5530const IBC_HASH: usize = 16;
5531
5532/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
5533/// the current one the source's bottom-right corner must already be. Under
5534/// 128 superblocks the same 256 pixels are two superblocks, which
5535/// [`Ibc::dv_valid`] derives from the size itself.
5536const INTRABC_DELAY_SB64: i32 = 4;
5537
5538/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
5539fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
5540 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
5541 for row in 0..IBC_HASH {
5542 let base = (y + row) * width + x;
5543 for &v in &plane[base..base + IBC_HASH] {
5544 h ^= u64::from(v);
5545 h = h.wrapping_mul(0x100_0000_01b3);
5546 }
5547 }
5548 h
5549}
5550
5551/// Every `intrabc_step()`-aligned position of `plane` inside
5552/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
5553fn ibc_index(
5554 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
5555 plane: &[u8],
5556 width: usize,
5557 (x0, y0): (usize, usize),
5558 (x1, y1): (usize, usize),
5559) {
5560 let step = intrabc_step();
5561 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
5562 return;
5563 }
5564 let mut y = y0.next_multiple_of(step);
5565 while y + IBC_HASH <= y1 {
5566 let mut x = x0.next_multiple_of(step);
5567 while x + IBC_HASH <= x1 {
5568 table
5569 .entry(ibc_hash(plane, width, x, y))
5570 .or_default()
5571 .push((x as u32, y as u32));
5572 x += step;
5573 }
5574 y += step;
5575 }
5576}
5577
5578/// Whether `screen`-detected source `y` repeats itself enough to be worth
5579/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
5580/// content appears at some other position, against [`intrabc_pct`]. Returns
5581/// the share as well, for the gate's own print.
5582fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
5583 if true_width < 4 * 64 || true_height < 2 * 64 {
5584 return (false, 0.0);
5585 }
5586 let mut table = std::collections::HashMap::new();
5587 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
5588 let (mut total, mut matched) = (0usize, 0usize);
5589 let mut by = 0;
5590 while by + IBC_HASH <= true_height {
5591 let mut bx = 0;
5592 while bx + IBC_HASH <= true_width {
5593 total += 1;
5594 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
5595 if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
5596 matched += 1;
5597 }
5598 }
5599 bx += IBC_HASH;
5600 }
5601 by += IBC_HASH;
5602 }
5603 let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
5604 (share * 100.0 >= intrabc_pct() as f64, share)
5605}
5606
5607/// One tile's intrabc search state: a block-hash table over the part of the
5608/// tile's own reconstruction that is already final (whole superblock rows --
5609/// the in-loop filters are off on this frame, so a coded superblock row never
5610/// changes again), plus the last DV chosen, which the RD price uses as its
5611/// predictor estimate.
5612struct Ibc {
5613 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
5614 /// source repeats exactly where a lossily coded reconstruction only
5615 /// nearly does, so an exact-match table over the reconstruction finds
5616 /// almost nothing. The candidate is then SCORED against the
5617 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
5618 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
5619 /// The tile's own luma rect, in samples.
5620 tile: (usize, usize, usize, usize),
5621 /// The DV the previous intrabc block of this tile took -- the *estimate*
5622 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
5623 /// against. The writer computes the true predictor off its own mi grid
5624 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
5625 /// a slightly mispriced candidate, never a wrong bitstream.
5626 last_dv: Option<(i32, i32)>,
5627 /// How many blocks took intrabc, and how many hash lookups found at least
5628 /// one valid candidate -- the gate's own fire counts.
5629 hits: usize,
5630 lookups: usize,
5631 found: usize,
5632}
5633
5634impl Ibc {
5635 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
5636 let mut table = std::collections::HashMap::new();
5637 ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
5638 Self {
5639 table,
5640 tile,
5641 last_dv: None,
5642 hits: 0,
5643 lookups: 0,
5644 found: 0,
5645 }
5646 }
5647
5648 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
5649 /// (1/8 pel), with this lane's own extra restriction on top: the source
5650 /// must lie entirely in a COMPLETED superblock row, which is exactly the
5651 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
5652 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
5653 /// wavefront's own diagonal) are legal and not searched; the upgrade path
5654 /// is to index the current row's finished superblocks too.
5655 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
5656 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
5657 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
5658 return false;
5659 }
5660 let (tx0, ty0, tx1, ty1) = (
5661 self.tile.0 as i32,
5662 self.tile.1 as i32,
5663 self.tile.2 as i32,
5664 self.tile.3 as i32,
5665 );
5666 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
5667 let (w, h) = (w as i32, h as i32);
5668 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
5669 return false;
5670 }
5671 // lane-b128m: libaom counts this wavefront in SUPERBLOCKS, and the
5672 // superblock is 128 wide under `EC_AV1_SB128` (`INTRABC_DELAY_SB =
5673 // INTRABC_DELAY_PIXELS >> sb_size_log2`, i.e. 2 there and 4 here).
5674 // Counting 64s under a 128 superblock let the search take a source
5675 // from a 64 row the 128 visit order had not reconstructed yet.
5676 let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 };
5677 let delay: i32 = if sb_log2 == 7 { INTRABC_DELAY_SB64 / 2 } else { INTRABC_DELAY_SB64 };
5678 let active_sb_row = (y as i32 - ty0) >> sb_log2;
5679 let active_sb_col = (x as i32 - tx0) >> sb_log2;
5680 let src_sb_row = (sy + h - 1 - ty0) >> sb_log2;
5681 let src_sb_col = (sx + w - 1 - tx0) >> sb_log2;
5682 // This lane's own restriction (see the doc comment).
5683 if src_sb_row >= active_sb_row {
5684 return false;
5685 }
5686 let total = ((tx1 - tx0 - 1) >> sb_log2) + 1;
5687 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay {
5688 return false;
5689 }
5690 // libaom's wavefront: only the top-left cone of the frame is legal.
5691 let wf = (1 + delay) * (active_sb_row - src_sb_row);
5692 src_sb_col < active_sb_col - delay + wf
5693 }
5694}
5695
5696/// How many block searches ran, how many found at least one VALID candidate,
5697/// and how many won on rate-distortion -- the hash hit rate a gate prints
5698/// (class `gate-blind-to-feature`: "the search ran" and "the search found
5699/// something" and "the block took it" are three different claims).
5700static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
5701 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
5702
5703impl Drop for Ibc {
5704 fn drop(&mut self) {
5705 for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
5706 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
5707 }
5708 }
5709}
5710
5711/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
5712/// its own encode.
5713#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5714pub(crate) fn take_intrabc_search() -> [usize; 3] {
5715 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5716}
5717
5718/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
5719/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
5720/// infers rather than codes.
5721fn dv_component_bits(diff: i32) -> f64 {
5722 let z = diff.unsigned_abs() as i32 - 1;
5723 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
5724 let class = mv_class_of(z);
5725 bits += symbol_bits(&cdf::MV_CLASS, class);
5726 let local = z - mv_class_base(class);
5727 if class == 0 {
5728 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
5729 } else {
5730 let d = local >> 3;
5731 for i in 0..class {
5732 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
5733 }
5734 }
5735 bits
5736}
5737
5738/// What one block vector costs against `pred`, plus the `skip` and
5739/// `use_intrabc` flags the block carries and the ordinary intra block does
5740/// not pay in this currency.
5741fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
5742 let diff = (dv.0 - pred.0, dv.1 - pred.1);
5743 let joint = match (diff.0 != 0, diff.1 != 0) {
5744 (false, false) => 0,
5745 (false, true) => 1,
5746 (true, false) => 2,
5747 (true, true) => 3,
5748 };
5749 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
5750 if diff.0 != 0 {
5751 bits += dv_component_bits(diff.0);
5752 }
5753 if diff.1 != 0 {
5754 bits += dv_component_bits(diff.1);
5755 }
5756 bits
5757}
5758
5759/// The squared error of copying the `side`-square block at `(sx, sy)` of each
5760/// plane's reconstruction onto the source block at `(x, y)`, luma and both
5761/// chroma planes together -- what an intrabc block's whole (residual-free)
5762/// distortion is.
5763fn ibc_sse(
5764 luma: &Plane,
5765 chroma: &[Plane; 2],
5766 (x, y): (usize, usize),
5767 (sx, sy): (usize, usize),
5768 side: usize,
5769) -> f64 {
5770 // Inside the true frame only, for the reason [`Plane::block_sse`] is
5771 // (lane-sse): an intrabc block at the edge would otherwise be ranked by
5772 // how well it copies the padding.
5773 let mut sse = 0.0f64;
5774 let clip = |whole: usize, inside: usize| match edge_sse() {
5775 true => whole.min(inside),
5776 false => whole,
5777 };
5778 let rows = clip(side, luma.true_height.saturating_sub(y));
5779 let cols = clip(side, luma.true_width.saturating_sub(x));
5780 for row in 0..rows {
5781 let src = &luma.source[(y + row) * luma.width + x..][..cols];
5782 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols];
5783 for (&s, &r) in src.iter().zip(rec) {
5784 let d = f64::from(i32::from(s) - i32::from(r));
5785 sse += d * d;
5786 }
5787 }
5788 let half = side / 2;
5789 for plane in chroma {
5790 let rows = clip(half, plane.true_height.saturating_sub(y / 2));
5791 let cols = clip(half, plane.true_width.saturating_sub(x / 2));
5792 for row in 0..rows {
5793 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols];
5794 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols];
5795 for (&s, &r) in src.iter().zip(rec) {
5796 let d = f64::from(i32::from(s) - i32::from(r));
5797 sse += d * d;
5798 }
5799 }
5800 }
5801 sse
5802}
5803
5804/// Copies the `side`-square block at `(sx, sy)` of each plane's
5805/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
5806/// since it carries no residual (`skip`). Full-pel in both planes by
5807/// construction ([`intrabc_step`] keeps every DV even), which is what makes
5808/// this a plain copy where decode.rs runs the bilinear kernel over the same
5809/// samples.
5810fn ibc_commit(
5811 luma: &mut Plane,
5812 chroma: &mut [Plane; 2],
5813 (x, y): (usize, usize),
5814 (sx, sy): (usize, usize),
5815 side: usize,
5816) {
5817 for row in 0..side {
5818 let from = (sy + row) * luma.width + sx;
5819 let to = (y + row) * luma.width + x;
5820 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
5821 luma.reconstruction[to..to + side].copy_from_slice(&copied);
5822 }
5823 let half = side / 2;
5824 for plane in chroma {
5825 for row in 0..half {
5826 let from = (sy / 2 + row) * plane.width + sx / 2;
5827 let to = (y / 2 + row) * plane.width + x / 2;
5828 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
5829 plane.reconstruction[to..to + half].copy_from_slice(&copied);
5830 }
5831 plane.commit_ctx_zero(x / 2, y / 2, half);
5832 }
5833 luma.commit_ctx_zero(x, y, side);
5834}
5835
5836/// Searches this block's own DV: every hash-table position whose 16x16 luma
5837/// square equals the block's source square, plus the previous block's DV as a
5838/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
5839/// the winning `(dv, cost)`, or `None` when nothing valid was found.
5840fn ibc_search(
5841 ibc: &mut Ibc,
5842 luma: &Plane,
5843 chroma: &[Plane; 2],
5844 (x, y): (usize, usize),
5845 side: usize,
5846 lambda: f64,
5847) -> Option<((i32, i32), f64, (usize, usize))> {
5848 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
5849 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
5850 let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
5851 let dv = (
5852 (sy as i32 - y as i32) * 8,
5853 (sx as i32 - x as i32) * 8,
5854 );
5855 if !ibc.dv_valid(x, y, side, side, dv) {
5856 return;
5857 }
5858 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
5859 if best.as_ref().is_none_or(|b| cost < b.1) {
5860 *best = Some((dv, cost, (sx, sy)));
5861 }
5862 };
5863 ibc.lookups += 1;
5864 let key = ibc_hash(luma.source, luma.width, x, y);
5865 // The table is filled in raster order, so the entries BEFORE this block's
5866 // own position are exactly the already-coded ones -- and the nearest of
5867 // them costs the fewest DV bits. Walking backwards from the block's own
5868 // slot is what makes the search look up-and-left; taking the newest
5869 // entries outright only ever finds candidates below and to the right,
5870 // every one of which `dv_valid` rejects.
5871 let hits: Vec<(u32, u32)> = ibc
5872 .table
5873 .get(&key)
5874 .map(|h| {
5875 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
5876 h[..end].iter().rev().take(32).copied().collect()
5877 })
5878 .unwrap_or_default();
5879 for (hx, hy) in hits {
5880 consider(&*ibc, hx as usize, hy as usize, &mut best);
5881 }
5882 if let Some(dv) = ibc.last_dv {
5883 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
5884 if sx >= 0 && sy >= 0 {
5885 consider(&*ibc, sx as usize, sy as usize, &mut best);
5886 }
5887 }
5888 if best.is_some() {
5889 ibc.found += 1;
5890 }
5891 best
5892}
5893
5894fn code_square(
5895 luma: &mut Plane,
5896 chroma: &mut [Plane; 2],
5897 (x, y): (usize, usize),
5898 side: usize,
5899 search: &Search,
5900 mode_bits: &[f64; 13],
5901 // The frame header's `tx_mode == TxMode::Select`: the block then searches
5902 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
5903 // transform over its whole side.
5904 tx_select: bool,
5905 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
5906 // header did not set `allow_intrabc`.
5907 ibc: Option<&mut Ibc>,
5908 // Whether this is a KEY frame's block, read only by the split census
5909 // ([`SPLIT_CENSUS`]): the two frame types split at very different rates,
5910 // which is this lane's whole finding.
5911 census_key: bool,
5912 fctx: &crate::decode::FrameCtx,
5913) -> (BlockCoeffs, f64) {
5914 let (luma_set, chroma_set) = if side == SUPERBLOCK {
5915 // A whole superblock coded as ONE intra block (lane-i64): one
5916 // TX_64X64 luma transform, whose coded quarter is the 32x32 corner
5917 // `code_from_prediction` hands back, and one TX_32X32 per chroma
5918 // plane -- the same three sets the key frame writer's
5919 // `Superblock::Whole` arm codes, and the same the inter 64x64 root
5920 // uses (`search_skip_64`).
5921 (TxbSet::Luma64, TxbSet::Chroma32)
5922 } else if side == BLOCK {
5923 (TxbSet::Luma32, TxbSet::Chroma16)
5924 } else if side == 8 {
5925 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
5926 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
5927 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
5928 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
5929 // (this branch is still unreached), so leaving `Chroma8` here would
5930 // silently wire the wrong table the moment one does; `Chroma4` is
5931 // what a real caller needs.
5932 (TxbSet::Luma8, TxbSet::Chroma4)
5933 } else {
5934 (TxbSet::Luma16, TxbSet::Chroma8)
5935 };
5936 let at = At {
5937 x,
5938 y,
5939 side,
5940 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
5941 set: luma_set_for(luma_set, search.screen),
5942 };
5943 let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) =
5944 luma.search_block(at, search, mode_bits, fctx);
5945 let mut luma_tx_types = vec![tx_type];
5946 // The depth search runs on the mode the whole-block transform picked --
5947 // libaom's own ordering, and the reason it costs one extra pass per depth
5948 // rather than one per (mode, depth) pair.
5949 let mut tx_depth = 0u8;
5950 // A 64x64 block has no depth to search (`max_tx_depth`), but the writer
5951 // still codes its `tx_depth` symbol off `TX_SIZE_CAT3`, so the incumbent
5952 // pays that zero exactly as a 32x32's depth search makes it pay
5953 // `tx_depth_bits(32, 0)` -- otherwise the 64-versus-four-32 comparison
5954 // below hands the root a symbol for free.
5955 if tx_select && side == SUPERBLOCK {
5956 cost += search.lambda * tx_depth_bits(side, 0);
5957 }
5958 if tx_select && max_tx_depth(side) > 0 {
5959 let mut best = (
5960 cost + search.lambda * tx_depth_bits(side, 0),
5961 0usize,
5962 luma.snapshot(x, y, side),
5963 luma_coeffs,
5964 );
5965 let mut best_types = std::mem::take(&mut luma_tx_types);
5966 // The census wants the flat arm's own (rate, distortion), which
5967 // `search_block` only hands back folded into one cost -- so under the
5968 // env flag alone it is re-coded at depth 0 and the plane restored.
5969 let census_flat = split_census_on().then(|| {
5970 let kept = luma.snapshot(x, y, side);
5971 let (_, sse, bits, _) =
5972 luma.code_tx_depth(at, mode, angle_delta, 0, None, search, fctx);
5973 luma.restore(x, y, side, &kept);
5974 (bits + tx_depth_bits(side, 0), sse)
5975 });
5976 let mut census_split: Option<(f64, f64)> = None;
5977 for depth in 1..=max_tx_depth(side) {
5978 let (levels, sse, bits, types) =
5979 luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
5980 let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth);
5981 let cost_d = sse + search.lambda * split_lambda_mult() * rate;
5982 if census_flat.is_some() {
5983 let c = (bits + tx_depth_bits(side, depth), sse);
5984 if census_split.is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
5985 {
5986 census_split = Some(c);
5987 }
5988 }
5989 if cost_d < best.0 {
5990 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
5991 best_types = types;
5992 }
5993 }
5994 if let (Some(flat), Some(split)) = (census_flat, census_split) {
5995 split_census(0, census_key, side, best.1 > 0, split, flat);
5996 }
5997 luma_tx_types = best_types;
5998 luma.restore(x, y, side, &best.2);
5999 cost = best.0;
6000 tx_depth = best.1 as u8;
6001 luma_coeffs = best.3;
6002 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6003 }
6004 // The palette candidate is priced against the mode the luma search (and
6005 // its transform-depth search) already settled on, so a block only takes
6006 // one when it beats the best ordinary intra coding of the same pixels.
6007 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
6008 // prediction is the colour map, not the DC of its neighbours.
6009 let mut mode = mode;
6010 let mut angle_delta = angle_delta;
6011 let mut palette = None;
6012 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6013 let source: Vec<u8> = (y..y + side)
6014 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
6015 .collect();
6016 let kept = luma.snapshot(x, y, side);
6017 // spec 5.11.50: a block cut by the frame's right/bottom edge codes
6018 // its map over the ON-SCREEN corner only and the decoder replicates
6019 // that outward, so the searched map is folded the same way here --
6020 // the prediction priced, the reconstruction committed and the symbols
6021 // `write_color_index_map` writes are then one and the same map
6022 // (lane-palw).
6023 let on = (
6024 side.min(luma.true_width.saturating_sub(x)),
6025 side.min(luma.true_height.saturating_sub(y)),
6026 );
6027 for mut pal in palette_candidates(&source) {
6028 let n = usize::from(pal.size);
6029 crate::decode::palette_replicate(&mut pal.map, side, side, on);
6030 let prediction: Vec<u8> = pal
6031 .map
6032 .iter()
6033 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
6034 .collect();
6035 let trial = luma.code_from_prediction(
6036 x,
6037 y,
6038 side,
6039 &prediction,
6040 false,
6041 search.base_q_idx,
6042 search.deadzone,
6043 luma_set,
6044 );
6045 let cost_p = trial.sse
6046 + search.lambda
6047 * (trial.bits
6048 + mode_bits[DC_PRED as usize]
6049 + crate::tile::palette_bits(&pal, side, on)
6050 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
6051 if cost_p < cost {
6052 cost = cost_p;
6053 mode = DC_PRED as u8;
6054 angle_delta = 0;
6055 tx_depth = 0;
6056 luma_coeffs = coeffs(&trial.levels, side.min(BLOCK));
6057 luma.commit(x, y, side, &trial);
6058 palette = Some(pal);
6059 }
6060 }
6061 if palette.is_none() {
6062 luma.restore(x, y, side, &kept);
6063 }
6064 }
6065
6066 // The five recursive filter-intra modes (spec 5.11.14), priced against
6067 // whatever the mode, transform-depth and palette searches settled on --
6068 // the same "one candidate loop after the incumbent is known" shape the
6069 // palette above uses. A block that takes one is `DC_PRED` with no palette
6070 // by construction (`av1_filter_intra_allowed`), and its luma transform
6071 // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`).
6072 //
6073 // lane-fitu: on a SCREEN frame the candidate is priced at every transform
6074 // depth the ordinary intra search runs, each unit predicting recursively
6075 // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra`
6076 // arm), so a block whose ordinary winner wanted a split transform is
6077 // compared against a filter arm that may split too.
6078 //
6079 // Measured (native BD table, lane-fitu): searching the depths on EVERY
6080 // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves
6081 // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a
6082 // locally cheaper reconstruction that the film rows go on to predict from
6083 // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen
6084 // content is where it pays, and a non-screen frame keeps the depth-0-only
6085 // arm, byte for byte.
6086 let mut filter_intra: Option<u8> = None;
6087 if filter_intra_on()
6088 && palette.is_none()
6089 && let Some(class) = crate::decode::filter_intra_size_class(side)
6090 {
6091 let row = &cdf::FILTER_INTRA[class];
6092 // With the sequence bit on, EVERY `DC_PRED` block without a luma
6093 // palette carries the flag, so the incumbent pays its zero before the
6094 // comparison -- otherwise the candidate is charged a bit the block
6095 // spends either way (class `price-the-narrowing-not-the-table`).
6096 if mode == DC_PRED {
6097 cost += search.lambda * symbol_bits(row, 0);
6098 }
6099 let one_bits = symbol_bits(row, 1);
6100 let kept = luma.snapshot(x, y, side);
6101 let max_depth = if tx_select && search.screen { max_tx_depth(side) } else { 0 };
6102 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
6103 for fi in 0..5u8 {
6104 for depth in 0..=max_depth {
6105 // A filter-intra block's units are coded through
6106 // `code_from_prediction`, which is `DCT_DCT` throughout, so
6107 // this arm keeps the empty (all-`DCT_DCT`) type list.
6108 let (levels, sse, bits, _) =
6109 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);
6110 let cost_f = sse
6111 + search.lambda
6112 * (bits
6113 + mode_bits[DC_PRED as usize]
6114 + one_bits
6115 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
6116 + if tx_select { tx_depth_bits(side, depth) } else { 0.0 });
6117 if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) {
6118 best = Some((
6119 cost_f,
6120 fi,
6121 depth,
6122 luma.snapshot(x, y, side),
6123 coeffs(&levels, side),
6124 ));
6125 }
6126 }
6127 }
6128 if let Some((cost_f, fi, depth, snapshot, levels)) = best {
6129 cost = cost_f;
6130 mode = DC_PRED;
6131 angle_delta = 0;
6132 tx_depth = depth as u8;
6133 luma_coeffs = levels;
6134 luma.restore(x, y, side, &snapshot);
6135 filter_intra = Some(fi);
6136 } else {
6137 luma.restore(x, y, side, &kept);
6138 }
6139 }
6140
6141 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
6142 // planes; what it costs still counts towards the partition decision.
6143 let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
6144 search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
6145 cost += chroma_cost;
6146
6147 // The intrabc arm is priced against the WHOLE block -- luma and both
6148 // chroma planes, residual-free -- so it is compared after the chroma
6149 // search has added its own cost, not against the luma decision alone.
6150 if let Some(ibc) = ibc {
6151 if let Some((dv, cost_ibc, src)) =
6152 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
6153 {
6154 if cost_ibc < cost {
6155 ibc_commit(luma, chroma, (x, y), src, side);
6156 ibc.last_dv = Some(dv);
6157 ibc.hits += 1;
6158 return (
6159 BlockCoeffs {
6160 skip: true,
6161 dv: Some(dv),
6162 ..BlockCoeffs::default()
6163 },
6164 cost_ibc,
6165 );
6166 }
6167 }
6168 }
6169 // A palette or filter-intra block's luma was recoded through `DCT_DCT`
6170 // (its levels came from `code_from_prediction`), so the searched types
6171 // belong to a block this one no longer is.
6172 if palette.is_some() || filter_intra.is_some() {
6173 luma_tx_types = Vec::new();
6174 }
6175 (
6176 BlockCoeffs {
6177 u,
6178 v,
6179 luma: luma_coeffs,
6180 mode,
6181 uv_mode,
6182 tx_depth,
6183 palette,
6184 palette_uv,
6185 filter_intra,
6186 cfl_alphas,
6187 angle_delta_y: angle_delta as i8,
6188 luma_tx_types,
6189 ..BlockCoeffs::default()
6190 },
6191 cost,
6192 )
6193}
6194
6195/// The chroma modes the search offers, and the only ones it may offer: each
6196/// predicts from the row directly above and the column directly to the left
6197/// and nothing further, so none of them needs the above-right/below-left
6198/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
6199/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
6200/// reconstruction and its own alpha syntax; both are left out here.
6201const CHROMA_MODES: [u8; 7] = [
6202 DC_PRED,
6203 V_PRED,
6204 H_PRED,
6205 SMOOTH_PRED,
6206 SMOOTH_V_PRED,
6207 SMOOTH_H_PRED,
6208 PAETH_PRED,
6209];
6210
6211/// The thirteen intra mode names, for the chroma fire count's print.
6212#[cfg(test)]
6213const UV_MODE_NAMES: [&str; 14] = [
6214 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
6215 "SMOOTH_H", "PAETH", "CFL",
6216];
6217
6218/// How many blocks each chroma mode has won, indexed by the mode itself --
6219/// the fire count that says whether the search below reaches its candidates
6220/// at all (the `gate-blind-to-feature` class), printed once per gate run.
6221static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
6222 [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
6223
6224/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
6225/// won, summed over both chroma planes -- the alpha histogram the gate prints
6226/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
6227/// magnitude only is a search that never left its first candidate).
6228static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
6229 [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
6230
6231/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
6232/// zero on a CfL block", `1..=16` the magnitudes.
6233#[cfg(test)]
6234pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
6235 std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6236}
6237
6238/// How many directional luma blocks won at each `angle_delta_y`, indexed
6239/// `delta + 3` -- the histogram that says whether the refinement below ever
6240/// leaves zero (`gate-blind-to-feature`).
6241static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
6242 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
6243
6244/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
6245#[cfg(test)]
6246pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
6247 std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
6248}
6249
6250/// Whether the luma search refines a directional winner's `angle_delta_y`
6251/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
6252fn angle_delta_on() -> bool {
6253 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6254 crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0")
6255 });
6256 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
6257}
6258
6259/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
6260/// switches it off, which is how the lane measured its own on/off pair).
6261fn cfl_on() -> bool {
6262 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6263 crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0")
6264 });
6265 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
6266}
6267
6268/// Whether the intra search offers the five recursive filter-intra modes at
6269/// all, and with them whether the sequence header sets `enable_filter_intra`
6270/// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
6271/// its own on/off pair -- and how every byte pin written before it still
6272/// reproduces). It is also a speed lever: on at preset 0, off above it.
6273// lane-sb128: `use_128x128_superblock` (spec 5.5.1). `EC_AV1_SB128=0` turns
6274// it off for the whole process (a sequence-header field, so it cannot change
6275// mid-stream anyway), the same env-flag shape `EC_AV1_FILTER_INTRA` uses.
6276// NOT an `EncoderConfig` field: that struct is built by 90 literal sites in
6277// this workspace.
6278
6279/// Whether a sequence codes 128x128 superblocks when the environment says
6280/// nothing. ON since lane-b128 gave the 128 root a real `PARTITION_NONE`
6281/// candidate ([`search_root_128`]): with SPLIT-only roots the size was pure
6282/// cost (lane-sb128b measured film B +24.9 -> +37.5 vs libaom), and with the
6283/// 128x128 block in it every row of the native BD gate is down or flat on
6284/// both columns (BD-rate vs libaom cpu-6 / rav1e s6, 12 frames):
6285///
6286/// | row | 64 superblocks | 128 + the 128 root |
6287/// |---|---|---|
6288/// | bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** |
6289/// | bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** |
6290/// | film A | +20.3 / -5.0 | **+20.1 / -5.2** |
6291/// | film B | +24.6 / -2.0 | **+24.3 / -2.2** |
6292/// | screen capture | +14.6 / -33.2 | **+14.4 / -33.2** |
6293///
6294/// and the long-GOP gate agrees (film A +24.0/-7.6 -> +23.6/-7.9, film B
6295/// +85.8/+7.1 -> +85.1/+6.6). Both arms re-run on lane-b128m's own base.
6296///
6297/// ON since lane-b128m closed the eleven 128-superblock desyncs that held it
6298/// off (the delta_q unit at the 128 superblock, the superblock size travelling
6299/// with a `FrameCtx` copy into a tile search worker, the writer's intrabc DV
6300/// predictor and wavefront, and seven test harnesses that handed the encoder a
6301/// 64-superblock context). `EC_AV1_SB128=0` turns it off.
6302pub(crate) const SB128_DEFAULT: bool = true;
6303
6304/// Whether this process's sequences code 128x128 superblocks. An ENCODER
6305/// knob (like `speed::SPEED`), never read by a decode: read through a
6306/// process-global (not a thread-local) because the tile writers run on
6307/// worker threads; `2` is "the environment has not been read yet".
6308static ENC_SB128: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2);
6309
6310/// Whether this process's sequences code 128x128 superblocks.
6311pub(crate) fn sb128_on() -> bool {
6312 use std::sync::atomic::Ordering::Relaxed;
6313 match ENC_SB128.load(Relaxed) {
6314 2 => {
6315 let on = crate::envflags::var("EC_AV1_SB128")
6316 .ok()
6317 .map_or(SB128_DEFAULT, |v| v != "0");
6318 ENC_SB128.store(u8::from(on), Relaxed);
6319 on
6320 }
6321 v => v == 1,
6322 }
6323}
6324
6325/// Forces [`sb128_on`] for the rest of the process -- the superblock size is
6326/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`),
6327/// exactly like the speed-preset gates.
6328#[cfg(test)]
6329pub(crate) fn force_sb128(on: bool) {
6330 ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed);
6331}
6332
6333/// The luma loop-restoration unit size this sequence codes: a 128 superblock
6334/// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,
6335/// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is
6336/// 128), which is the one filter parameter the superblock size moves.
6337pub(crate) fn lr_unit() -> u32 {
6338 if sb128_on() { 128 } else { 64 }
6339}
6340
6341pub(crate) fn filter_intra_on() -> bool {
6342 #[cfg(test)]
6343 if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) {
6344 return forced;
6345 }
6346 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6347 crate::envflags::var("EC_AV1_FILTER_INTRA").ok().map(|v| v != "0")
6348 });
6349 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
6350}
6351
6352/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
6353/// to its own encode.
6354#[cfg(test)]
6355pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
6356 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6357}
6358
6359/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
6360/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
6361/// Returns each plane's levels, the mode, and what the pair cost (squared
6362/// error plus lambda times bits, the same currency the luma search speaks).
6363///
6364/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
6365/// which is what the luma mode decision was taken against, so what a
6366/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
6367/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
6368/// writer then has to code.
6369#[allow(clippy::too_many_arguments)]
6370/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
6371/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
6372/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
6373/// trials all seven, as before this lever.
6374///
6375/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
6376/// the search's largest trial population by far -- seven modes times two
6377/// planes for every intra block, against 3.7 luma trials -- and the RD
6378/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
6379/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
6380fn chroma_top_k() -> Option<usize> {
6381 static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| {
6382 crate::envflags::var("EC_AV1_CHROMA_K")
6383 .ok()
6384 .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0))
6385 });
6386 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K))
6387}
6388
6389/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
6390/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
6391/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
6392/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
6393/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
6394/// BD swings by about a point in either direction as near-tie chroma modes
6395/// flip, which is the measurement's own sensitivity, not a trend: nothing
6396/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
6397/// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
6398/// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
6399/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
6400pub(crate) const CHROMA_TOP_K: Option<usize> = None;
6401
6402fn search_chroma(
6403 chroma: &mut [Plane; 2],
6404 // The luma plane's RECONSTRUCTION under this block, already committed by
6405 // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
6406 luma: &Plane,
6407 (x, y): (usize, usize),
6408 side: usize,
6409 set: TxbSet,
6410 search: &Search,
6411 luma_mode: u8,
6412 fctx: &crate::decode::FrameCtx,
6413) -> (
6414 [Vec<Coeff>; 2],
6415 u8,
6416 f64,
6417 Option<crate::tile::PaletteUv>,
6418 Option<(i32, i32)>,
6419) {
6420 let at = At {
6421 x: x / 2,
6422 y: y / 2,
6423 side: side / 2,
6424 reach: Reach::none(),
6425 set,
6426 };
6427 // The census's cheap proxy for a chroma mode: the SAD of its prediction
6428 // summed over both planes, ranked by the same rule the luma histogram
6429 // uses. Only built under `EC_AV1_CENSUS`.
6430 // The SAD of each mode's prediction, summed over both planes -- the
6431 // census's ranking rule, and what [`chroma_top_k`] prunes by.
6432 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
6433 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6434 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6435 u.iter()
6436 .zip(v.iter())
6437 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
6438 .collect()
6439 };
6440 let modes: Vec<u8> = match chroma_top_k() {
6441 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
6442 _ => CHROMA_MODES.to_vec(),
6443 };
6444 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
6445 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
6446 let ranking: Vec<(f64, u8)> = if census_on() {
6447 sad_scores(chroma)
6448 } else {
6449 Vec::new()
6450 };
6451 census_add(2, 1);
6452 census_add(3, modes.len());
6453 let mut best: Option<(f64, u8, Trial, Trial)> = None;
6454 for mode in modes {
6455 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
6456 if (V_PRED..=D67_PRED).contains(&mode) {
6457 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
6458 }
6459 // lane-i64: `av1_get_ext_tx_set_type` resolves a CHROMA plane at
6460 // `tx_size_sqr >= TX_32X32` to `EXT_TX_SET_DCTONLY`, so the 32x32
6461 // chroma of a 64x64 block is `DCT_DCT` whatever
6462 // `Intra_Mode_To_Tx_Type` says -- the decoder's own `side >= 32` arm
6463 // (decode.rs `read_chroma_plane`), and ADST is not even defined at 32
6464 // points.
6465 let tx_type = if at.side >= 32 {
6466 TxType::DctDct
6467 } else {
6468 crate::decode::default_intra_tx_type(mode)
6469 };
6470 let u = chroma[0].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6471 let v = chroma[1].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6472 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
6473 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
6474 best = Some((cost, mode, u, v));
6475 }
6476 }
6477 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
6478 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
6479 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
6480 // what keeps `u_colors` ascending and distinct the way
6481 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
6482 // each cluster's own mean, since the colour-index map is SHARED by the
6483 // two planes. Priced against the best ordinary chroma mode above, so a
6484 // block only takes one when it beats it; a palette block's chroma mode is
6485 // `UV_DC_PRED` by construction.
6486 let mut palette_uv = None;
6487 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6488 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
6489 let plane_source = |p: &Plane| -> Vec<u8> {
6490 (at.y..at.y + at.side)
6491 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
6492 .collect()
6493 };
6494 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
6495 // The luma on-screen extent carried into this plane exactly as the
6496 // reader does it (`decode::palette_onscreen_uv`); see the luma arm.
6497 let on_uv = crate::decode::palette_onscreen_uv(
6498 (side, side),
6499 (
6500 side.min(luma.true_width.saturating_sub(x)),
6501 side.min(luma.true_height.saturating_sub(y)),
6502 ),
6503 (at.side, at.side),
6504 // The encoder writes 4:2:0 only (`palette_uv_side` above).
6505 (1, 1),
6506 );
6507 for mut pal in palette_candidates(&u_source) {
6508 let n = usize::from(pal.size);
6509 crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv);
6510 // V's base colour per cluster: the mean of the samples the shared
6511 // map assigns to it (an empty cluster cannot happen -- every
6512 // colour `palette_candidates` returns is some pixel's nearest).
6513 let mut sums = [0u32; 8];
6514 let mut counts = [0u32; 8];
6515 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
6516 let k = usize::from(i).min(n - 1);
6517 sums[k] += u32::from(sample);
6518 counts[k] += 1;
6519 }
6520 let mut v_colors = [0u16; 8];
6521 for k in 0..n {
6522 v_colors[k] = if counts[k] > 0 {
6523 ((sums[k] + counts[k] / 2) / counts[k]) as u16
6524 } else {
6525 0
6526 };
6527 }
6528 let candidate = crate::tile::PaletteUv {
6529 size: pal.size,
6530 u_colors: pal.colors,
6531 v_colors,
6532 map: pal.map,
6533 };
6534 let predict = |colors: &[u16; 8]| -> Vec<u8> {
6535 candidate
6536 .map
6537 .iter()
6538 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
6539 .collect()
6540 };
6541 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
6542 let u_trial = chroma[0].code_from_prediction(
6543 at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
6544 );
6545 let v_trial = chroma[1].code_from_prediction(
6546 at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
6547 );
6548 let cost_p = u_trial.sse
6549 + v_trial.sse
6550 + search.lambda
6551 * (u_trial.bits
6552 + v_trial.bits
6553 + crate::tile::palette_uv_bits(&candidate, side, on_uv));
6554 if cost_p < cost {
6555 cost = cost_p;
6556 mode = DC_PRED;
6557 u = u_trial;
6558 v = v_trial;
6559 palette_uv = Some(candidate);
6560 }
6561 }
6562 }
6563 // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
6564 // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
6565 // nudges every sample by `alpha_q3` times the block's subsampled,
6566 // average-subtracted luma reconstruction. Offered only where
6567 // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
6568 // and priced against the best ordinary chroma mode above, palette
6569 // included, so a block only takes it when it beats both.
6570 let mut cfl_alphas = None;
6571 if side <= 32 && cfl_on() {
6572 // The AC signal, through the decoder's own
6573 // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
6574 let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
6575 i32::from(luma.reconstruction[ly * luma.width + lx])
6576 });
6577 let dc_prediction = |plane: &Plane| -> Vec<u8> {
6578 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
6579 let (above, left, corner) =
6580 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
6581 let mut prediction = vec![0u8; at.side * at.side];
6582 intra_predict_u8(
6583 DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction,
6584 fctx,
6585 );
6586 prediction
6587 };
6588 let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
6589 // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
6590 // add the residual -- which is what [`Plane::code_from_prediction`]
6591 // does with what this returns.
6592 let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
6593 base.iter()
6594 .zip(ac.iter())
6595 .map(|(&b, &a)| {
6596 (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
6597 })
6598 .collect()
6599 };
6600 // The least-squares alpha, then its two neighbours: minimising
6601 // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
6602 // dot-product ratio, and the quantised optimum is one of the two
6603 // integers around it (the clamp and the Q6 rounding are what the SSE
6604 // check below re-decides). libaom sweeps all sixteen magnitudes under
6605 // full RD; three predictions per plane buy nearly the same alpha for a
6606 // thirtieth of the search.
6607 let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
6608 let (mut num, mut den) = (0.0f64, 0.0f64);
6609 for row in 0..at.side {
6610 for col in 0..at.side {
6611 let i = row * at.side + col;
6612 let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
6613 - f64::from(base[i]);
6614 num += d * f64::from(ac[i]);
6615 den += f64::from(ac[i]) * f64::from(ac[i]);
6616 }
6617 }
6618 if den == 0.0 {
6619 return 0;
6620 }
6621 let ideal = 64.0 * num / den;
6622 let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
6623 for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
6624 let alpha = alpha.clamp(-16, 16) as i32;
6625 if alpha == 0 {
6626 continue;
6627 }
6628 let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
6629 if sse < best.0 {
6630 best = (sse, alpha);
6631 }
6632 }
6633 best.1
6634 };
6635 let picked = [
6636 pick_alpha(&chroma[0], &bases[0]),
6637 pick_alpha(&chroma[1], &bases[1]),
6638 ];
6639 if picked != [0, 0] {
6640 let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
6641 let trial = |plane_idx: usize, alpha: i32| -> Trial {
6642 let prediction = if alpha == 0 {
6643 bases[plane_idx].clone()
6644 } else {
6645 apply(&bases[plane_idx], alpha)
6646 };
6647 chroma[plane_idx].code_from_prediction(
6648 at.x,
6649 at.y,
6650 at.side,
6651 &prediction,
6652 false,
6653 search.base_q_idx,
6654 search.deadzone,
6655 set,
6656 )
6657 };
6658 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
6659 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
6660 let combos: [(i32, i32); 3] = [
6661 (picked[0], picked[1]),
6662 (picked[0], 0),
6663 (0, picked[1]),
6664 ];
6665 for &(alpha_u, alpha_v) in &combos {
6666 if (alpha_u, alpha_v) == (0, 0) {
6667 continue;
6668 }
6669 let cu = trial(0, alpha_u);
6670 let cv = trial(1, alpha_v);
6671 let bits =
6672 cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
6673 let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
6674 if cost_cfl < cost {
6675 cost = cost_cfl;
6676 mode = crate::tile::UV_CFL_PRED as u8;
6677 u = cu;
6678 v = cv;
6679 palette_uv = None;
6680 cfl_alphas = Some((alpha_u, alpha_v));
6681 }
6682 }
6683 }
6684 }
6685 if let Some((alpha_u, alpha_v)) = cfl_alphas {
6686 for alpha in [alpha_u, alpha_v] {
6687 CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
6688 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6689 }
6690 }
6691 if census_on() {
6692 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
6693 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6694 }
6695 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6696 chroma[0].commit(at.x, at.y, at.side, &u);
6697 chroma[1].commit(at.x, at.y, at.side, &v);
6698 (
6699 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
6700 mode,
6701 cost,
6702 palette_uv,
6703 cfl_alphas,
6704 )
6705}
6706
6707/// Codes one leaf of a straddling quadrant as whichever costs least of intra
6708/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
6709/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
6710/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
6711/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
6712/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
6713/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
6714/// attempted here: these leaves only ever fill the sliver of real content a
6715/// true edge lands in the middle of a larger block, not a leaf worth a full
6716/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
6717/// (see `write_inter_frame_leaf`'s doc comment).
6718#[allow(clippy::too_many_arguments)]
6719/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
6720/// as [`code_square_inter`] wants them: empty on a frame that codes no
6721/// `reference_select`, or when the leaf compound candidates are switched off.
6722/// One helper because THREE leaf call sites need it -- the split quadrants
6723/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
6724/// `&[]` and so coded no compound block anywhere along the frame's true edge.
6725#[allow(clippy::too_many_arguments)]
6726fn leaf_compound_stacks<'a>(
6727 grid: &MiGrid,
6728 mi_row: usize,
6729 mi_col: usize,
6730 bw4: usize,
6731 bh4: usize,
6732 mi_cols: usize,
6733 mi_rows: usize,
6734 reference_select: bool,
6735 golden: Option<&'a Picture>,
6736 altref: Option<&'a Picture>,
6737) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
6738 if !(reference_select && leaf_compound()) {
6739 return Vec::new();
6740 }
6741 [
6742 (crate::mvstack::GOLDEN_FRAME, golden),
6743 (crate::mvstack::ALTREF_FRAME, altref),
6744 ]
6745 .into_iter()
6746 .filter_map(|(r, pic)| {
6747 pic.map(|p| {
6748 (
6749 r,
6750 p,
6751 crate::mvstack::find_mv_stack_compound(
6752 grid, mi_row, mi_col, bw4, bh4,
6753 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6754 grid.sign_bias_table(), &[(0, 0); 7], None,
6755 ),
6756 )
6757 })
6758 })
6759 .collect()
6760}
6761
6762/// The OBMC prediction of one square single-reference block: this block's own
6763/// translation prediction (`mc::predict`) with every bordering above/left
6764/// neighbour blended into the overlap strips by the DECODER's own plan and
6765/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
6766/// the search prices is what a decoder reconstructs -- never a second
6767/// implementation of the blend. `None` when the block has no overlappable
6768/// neighbour at all (the writer would then code no `motion_mode` symbol) or
6769/// when the plan cannot be built (a neighbour naming a reference this encode
6770/// does not hold).
6771#[allow(clippy::too_many_arguments)]
6772fn obmc_prediction(
6773 grid: &MiGrid,
6774 (mi_row, mi_col): (usize, usize),
6775 (mi_rows, mi_cols): (usize, usize),
6776 (x, y): (usize, usize),
6777 side: usize,
6778 mv: (i32, i32),
6779 refs: &[Option<&Picture>; 8],
6780 // This block's OWN reference planes, luma then both chroma, each as
6781 // (samples, stride, true width, true height).
6782 ref_planes: [(&[u16], usize, usize, usize); 3],
6783 frame_width: usize,
6784 fctx: &crate::decode::FrameCtx,
6785) -> Option<[Vec<u8>; 3]> {
6786 let n4 = side / 4;
6787 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
6788 return None;
6789 }
6790 let refpix = crate::decode::RefPix::ready(*refs);
6791 let plan = crate::decode::obmc_plan(
6792 grid,
6793 &[],
6794 &[],
6795 mi_row,
6796 mi_col,
6797 n4,
6798 n4,
6799 mi_rows,
6800 mi_cols,
6801 side,
6802 side,
6803 side,
6804 side / 2,
6805 x,
6806 y,
6807 x / 2,
6808 y / 2,
6809 &refpix,
6810 Some(fctx.interp_filter.get()),
6811 frame_width,
6812 )
6813 .ok()?;
6814 let mut pred = [
6815 vec![0u16; side * side],
6816 vec![0u16; side * side / 4],
6817 vec![0u16; side * side / 4],
6818 ];
6819 for (i, r) in ref_planes.into_iter().enumerate() {
6820 let luma_plane = i == 0;
6821 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
6822 let s = if luma_plane { side } else { side / 2 };
6823 mc::predict(
6824 r.0,
6825 r.1,
6826 r.2,
6827 r.3,
6828 mv_to_q4(px, mv.1, luma_plane),
6829 mv_to_q4(py, mv.0, luma_plane),
6830 s,
6831 s,
6832 &mut pred[i],
6833 fctx,
6834 );
6835 }
6836 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
6837 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
6838 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
6839 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
6840}
6841
6842fn code_square_inter(
6843 luma: &mut Plane,
6844 chroma: &mut [Plane; 2],
6845 (x, y): (usize, usize),
6846 side: usize,
6847 search: &Search,
6848 mode_bits: &[f64; 13],
6849 reference: &Picture,
6850 stack: &MvStack,
6851 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
6852 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
6853 // `reference_select`, and at the straddling call sites).
6854 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
6855 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
6856 // (`record_mi`, in the writer's own coding order) and this leaf's place in
6857 // it -- what the OBMC candidate's eligibility walk and neighbour plan
6858 // read, the same state the tile writer reads when it codes the leaf's
6859 // `motion_mode` symbol.
6860 grid: &MiGrid,
6861 (mi_row, mi_col): (usize, usize),
6862 (mi_rows, mi_cols): (usize, usize),
6863 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
6864 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
6865 refs: &[Option<&Picture>; 8],
6866 fctx: &crate::decode::FrameCtx,
6867) -> (BlockCoeffs, f64) {
6868 // lane-arfmode: at the top ARF (arm 1) the leaf offers no intra
6869 // candidate at all -- `intra_cost` stays at infinity, so every
6870 // comparison below takes an inter candidate and the fallback arm at the
6871 // tail is unreachable. The planes hold what the caller snapshotted until
6872 // the winner commits: the intra trial used to commit here and be
6873 // overwritten by the inter commit, so skipping it changes no committed
6874 // sample, only work.
6875 let (intra_block, intra_cost) = if search.arf_leaf_intra {
6876 code_square(
6877 luma,
6878 chroma,
6879 (x, y),
6880 side,
6881 search,
6882 mode_bits,
6883 tx_select() && tx_select_inter(),
6884 None,
6885 false,
6886 fctx,
6887 )
6888 } else {
6889 arfmode_hit(0);
6890 (BlockCoeffs::default(), f64::INFINITY)
6891 };
6892 let luma_set = if side == 8 {
6893 TxbSet::Luma8Inter
6894 } else {
6895 TxbSet::Luma16Inter
6896 };
6897 let chroma_set = if side == 8 {
6898 TxbSet::Chroma4
6899 } else {
6900 TxbSet::Chroma8
6901 };
6902
6903 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
6904 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
6905 let single_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
6906 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
6907 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
6908 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
6909
6910 let mv = stack.nearest_mv;
6911 let ref_luma = (
6912 &reference.y,
6913 reference.width,
6914 luma.true_width,
6915 luma.true_height,
6916 );
6917 let ref_u = (
6918 &reference.u,
6919 reference.width / 2,
6920 chroma[0].true_width,
6921 chroma[0].true_height,
6922 );
6923 let ref_v = (
6924 &reference.v,
6925 reference.width / 2,
6926 chroma[1].true_width,
6927 chroma[1].true_height,
6928 );
6929 let luma_trial = mc_trial(
6930 luma,
6931 x,
6932 y,
6933 side,
6934 mv,
6935 true,
6936 ref_luma.0,
6937 ref_luma.1,
6938 ref_luma.2,
6939 ref_luma.3,
6940 false,
6941 search.base_q_idx,
6942 search.deadzone,
6943 luma_set, fctx,
6944 );
6945 let u = mc_trial(
6946 &chroma[0],
6947 x / 2,
6948 y / 2,
6949 side / 2,
6950 mv,
6951 false,
6952 ref_u.0,
6953 ref_u.1,
6954 ref_u.2,
6955 ref_u.3,
6956 false,
6957 search.base_q_idx,
6958 search.deadzone,
6959 chroma_set, fctx,
6960 );
6961 let v = mc_trial(
6962 &chroma[1],
6963 x / 2,
6964 y / 2,
6965 side / 2,
6966 mv,
6967 false,
6968 ref_v.0,
6969 ref_v.1,
6970 ref_v.2,
6971 ref_v.3,
6972 false,
6973 search.base_q_idx,
6974 search.deadzone,
6975 chroma_set, fctx,
6976 );
6977 let skip = luma_trial.levels.iter().all(|&l| l == 0)
6978 && u.levels.iter().all(|&l| l == 0)
6979 && v.levels.iter().all(|&l| l == 0);
6980 let inter_cost = luma_trial.sse
6981 + u.sse
6982 + v.sse
6983 + search.lambda
6984 * (skip_bits(skip)
6985 + intra_inter_bits(true)
6986 + single_ref_bits
6987 + mode_bits_inter
6988 + if skip {
6989 0.0
6990 } else {
6991 luma_trial.bits + u.bits + v.bits
6992 });
6993
6994 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
6995 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
6996 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
6997 // scan's own coverage already reached as far) but a real gap at 4-mi
6998 // leaf geometry. r3 ported the extended scan and, while proving it a
6999 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
7000 // `mvstack.rs`), found and fixed a second bug the extended scan's
7001 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
7002 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
7003 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
7004 // regardless of whether it also casts a ref-frame-matching vote) --
7005 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
7006 // branches), which is what made 8-mi geometry a true no-op instead of
7007 // one that only held when every neighbour happened to be inter.
7008 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
7009 // only ever took the stack's NEARESTMV candidate or went intra, so a
7010 // 32x32 block splitting because its four quarters MOVE differently could
7011 // not code the movement it split for. Same candidate `search_inter_block`
7012 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
7013 // a vector the residual syntax can name -- at this leaf's own side.
7014 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
7015 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
7016 // re-price below can hand it back as the winner's own mode info.
7017 let nearest_info = InterInfo {
7018 ref1: None,
7019 mv1: (0, 0),
7020 ref_frame: crate::mvstack::LAST_FRAME,
7021 mode: InterMode::NearestMv,
7022 mv,
7023 ref_mv_idx: 0,
7024 };
7025 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
7026 // syntax, apart from its residual: the OBMC candidate re-prices the same
7027 // syntax against a different prediction, so both sides of that comparison
7028 // carry it.
7029 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
7030 // This leaf's own `NEWMV` vector, kept whether or not it won the
7031 // single-reference comparison: it seeds the compound half-new candidate
7032 // below, exactly as `search_inter_block` seeds its own from the searches
7033 // it already ran.
7034 let mut searched_new: Option<(i32, i32)> = None;
7035 // What that search cost, kept for the second reference's own early-out
7036 // below (`None` when this leaf ran no search at all).
7037 let mut searched_new_cost: Option<f64> = None;
7038 let source_block = luma.source_block(x, y, side);
7039 if leaf_new_mv() {
7040 let (seeds, seed_n) = mv_seeds(stack);
7041 let found = motion::search(
7042 ref_luma.0,
7043 ref_luma.1,
7044 ref_luma.2,
7045 ref_luma.3,
7046 &source_block,
7047 x,
7048 y,
7049 side,
7050 side,
7051 stack.pred_mv,
7052 &seeds[..seed_n],
7053 search.lambda, fctx,
7054 1,
7055 );
7056 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
7057 searched_new_cost = Some(found.cost);
7058 let mv_residual = mv_residual_bits(new_mv, stack.pred_mv);
7059 if mv_residual.is_none() {
7060 // lane-newmv: a vector the writer cannot name never reaches RD.
7061 newmv_census_block(side, false, f64::INFINITY, best.0, new_mv, stack.nearest_mv, 0.0);
7062 }
7063 if let Some(mv_bits) = mv_residual {
7064 searched_new = Some(new_mv);
7065 // Same reuse as `search_inter_block`: a NEWMV equal to the
7066 // stack's NEARESTMV is the same three trials, already run above.
7067 let (luma_new, u_new, v_new) = if new_mv == mv {
7068 (luma_trial.clone(), u.clone(), v.clone())
7069 } else {
7070 (
7071 mc_trial(
7072 luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2,
7073 ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx,
7074 ),
7075 mc_trial(
7076 &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1,
7077 ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set,
7078 fctx,
7079 ),
7080 mc_trial(
7081 &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1,
7082 ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set,
7083 fctx,
7084 ),
7085 )
7086 };
7087 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
7088 && u_new.levels.iter().all(|&l| l == 0)
7089 && v_new.levels.iter().all(|&l| l == 0);
7090 let drl_bits = if stack.entries.len() > 1 {
7091 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
7092 } else {
7093 0.0
7094 };
7095 let cost_new = luma_new.sse
7096 + u_new.sse
7097 + v_new.sse
7098 + search.lambda
7099 * (skip_bits(skip_new)
7100 + intra_inter_bits(true)
7101 + single_ref_bits
7102 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7103 + drl_bits
7104 + mv_bits
7105 + mv_rate_surcharge(mv_bits)
7106 + if skip_new {
7107 0.0
7108 } else {
7109 luma_new.bits + u_new.bits + v_new.bits
7110 });
7111 newmv_census_block(side, true, cost_new, best.0, new_mv, stack.nearest_mv, mv_bits);
7112 if cost_new < best.0 {
7113 single_syntax = intra_inter_bits(true)
7114 + single_ref_bits
7115 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7116 + drl_bits
7117 + mv_bits;
7118 best = (
7119 cost_new,
7120 Some((
7121 luma_new,
7122 u_new,
7123 v_new,
7124 skip_new,
7125 InterInfo {
7126 ref1: None,
7127 mv1: (0, 0),
7128 ref_frame: crate::mvstack::LAST_FRAME,
7129 mode: InterMode::NewMv,
7130 mv: new_mv,
7131 ref_mv_idx: 0,
7132 },
7133 )),
7134 );
7135 }
7136 }
7137 }
7138
7139 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
7140 // `search_inter_block` prices for a whole 32x32 block:
7141 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
7142 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
7143 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
7144 // too. Priced with the same static-CDF approximation, plus the
7145 // compound-only syntax the writer emits.
7146 if leaf_compound() && !search.arf_leaf_compound && !compound.is_empty() {
7147 // lane-arfmode: arm 4 drops this leaf's compound set (counted once
7148 // per leaf, not once per pair); the single-reference candidates
7149 // above stay.
7150 arfmode_hit(2);
7151 }
7152 for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound() && search.arf_leaf_compound) {
7153 let (ref1, g) = (*ref1, *g);
7154 // The whole `comp_mode` + reference-pair tree at the writer's own
7155 // contexts, for THIS pair (lane-ctx).
7156 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
7157 let mode_ctx =
7158 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
7159 let mode_bits_of =
7160 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
7161 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
7162 (
7163 cstack.nearest_mv,
7164 mode_bits_of(0),
7165 InterInfo {
7166 ref_frame: crate::mvstack::LAST_FRAME,
7167 mode: InterMode::NearestNearestMv,
7168 mv: cstack.nearest_mv.0,
7169 mv1: cstack.nearest_mv.1,
7170 ref1: Some(ref1),
7171 ref_mv_idx: 0,
7172 },
7173 ),
7174 (
7175 ((0, 0), (0, 0)),
7176 mode_bits_of(6),
7177 InterInfo {
7178 ref_frame: crate::mvstack::LAST_FRAME,
7179 mode: InterMode::GlobalGlobalMv,
7180 mv: (0, 0),
7181 mv1: (0, 0),
7182 ref1: Some(ref1),
7183 ref_mv_idx: 0,
7184 },
7185 ),
7186 ];
7187 // Every compound MV residual here is priced against compound stack
7188 // entry 0, which is what `assign_compound_mv` predicts from at
7189 // `ref_mv_idx = 0` -- so it is also what the second-reference search
7190 // below seeds from and rounds to, and no candidate it finds can then
7191 // fail `mv_residual_bits`.
7192 let cbase = cstack
7193 .entries
7194 .first()
7195 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
7196 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
7197 // it a leaf could only name a stack vector for the second half, and
7198 // screen capture showed the consequence: every leaf compound block
7199 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
7200 // extra-reference `NEWMV`, when this reference's own
7201 // `NEAREST_NEARESTMV` vector already prices `margin` times better
7202 // than the `LAST` search of this same leaf did -- one candidate
7203 // evaluation standing in for a whole search.
7204 let margin = leaf_second_new_margin();
7205 let mut second_new: Option<(i32, i32)> = None;
7206 if leaf_second_new_mv() {
7207 newmv_census_global(2);
7208 let skip = margin > 0.0
7209 && searched_new_cost.is_some_and(|last| {
7210 motion::cost_at(
7211 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y,
7212 side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx,
7213 ) * margin
7214 <= last
7215 });
7216 if skip {
7217 newmv_census_global(3);
7218 }
7219 if !skip {
7220 let mut seeds = [(0, 0); 4];
7221 let mut seed_n = 1;
7222 for e in cstack.entries.iter().take(3) {
7223 seeds[seed_n] = e.mv1;
7224 seed_n += 1;
7225 }
7226 let found = motion::search(
7227 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side,
7228 side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1),
7229 );
7230 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
7231 }
7232 }
7233 if let Some(new_mv) = searched_new {
7234 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
7235 ccands.push((
7236 (new_mv, cstack.nearest_mv.1),
7237 mode_bits_of(3) + b0,
7238 InterInfo {
7239 ref_frame: crate::mvstack::LAST_FRAME,
7240 mode: InterMode::NewNearestMv,
7241 mv: new_mv,
7242 mv1: cstack.nearest_mv.1,
7243 ref1: Some(ref1),
7244 ref_mv_idx: 0,
7245 },
7246 ));
7247 }
7248 }
7249 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
7250 // searches this leaf ran, each residual priced against `cbase`.
7251 if let Some(mv1) = second_new {
7252 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
7253 ccands.push((
7254 (cstack.nearest_mv.0, mv1),
7255 mode_bits_of(2) + b1,
7256 InterInfo {
7257 ref_frame: crate::mvstack::LAST_FRAME,
7258 mode: InterMode::NearestNewMv,
7259 mv: cstack.nearest_mv.0,
7260 mv1,
7261 ref1: Some(ref1),
7262 ref_mv_idx: 0,
7263 },
7264 ));
7265 if let Some((new_mv, b0)) =
7266 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
7267 {
7268 ccands.push((
7269 (new_mv, mv1),
7270 mode_bits_of(7) + b0 + b1,
7271 InterInfo {
7272 ref_frame: crate::mvstack::LAST_FRAME,
7273 mode: InterMode::NewNewMv,
7274 mv: new_mv,
7275 mv1,
7276 ref1: Some(ref1),
7277 ref_mv_idx: 0,
7278 },
7279 ));
7280 }
7281 }
7282 }
7283 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
7284 ccands.dedup_by_key(|c| c.0);
7285 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
7286 let g_u = (
7287 g.u.as_slice(),
7288 g.width / 2,
7289 chroma[0].true_width,
7290 chroma[0].true_height,
7291 );
7292 let g_v = (
7293 g.v.as_slice(),
7294 g.width / 2,
7295 chroma[1].true_width,
7296 chroma[1].true_height,
7297 );
7298 for (mvs, bits, info) in ccands {
7299 let luma_c = mc_trial_compound(
7300 luma, x, y, side, mvs, true,
7301 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
7302 search.base_q_idx, search.deadzone, luma_set, fctx,
7303 );
7304 let u_c = mc_trial_compound(
7305 &chroma[0], x / 2, y / 2, side / 2, mvs, false,
7306 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
7307 search.base_q_idx, search.deadzone, chroma_set, fctx,
7308 );
7309 let v_c = mc_trial_compound(
7310 &chroma[1], x / 2, y / 2, side / 2, mvs, false,
7311 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
7312 search.base_q_idx, search.deadzone, chroma_set, fctx,
7313 );
7314 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
7315 && u_c.levels.iter().all(|&l| l == 0)
7316 && v_c.levels.iter().all(|&l| l == 0);
7317 let cost_c = luma_c.sse
7318 + u_c.sse
7319 + v_c.sse
7320 + search.lambda
7321 * (skip_bits(skip_c)
7322 + intra_inter_bits(true)
7323 + bits
7324 + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
7325 if cost_c < best.0 {
7326 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
7327 }
7328 }
7329 }
7330
7331 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
7332 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
7333 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
7334 // the writer codes no symbol for one. The prediction is the decoder's own
7335 // plan and blend over the neighbours this leaf's `grid` already carries
7336 // (published by `record_mi` in the writer's coding order), so the
7337 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
7338 // offered this only at 32x32, which is not where libaom cashes its OBMC
7339 // gain.
7340 let mut motion_won = 0u8;
7341 let single = match &best.1 {
7342 None => Some(nearest_info),
7343 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
7344 Some(_) => None,
7345 };
7346 if let Some(info) = single.filter(|i| {
7347 (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on())
7348 && i.ref_frame == crate::mvstack::LAST_FRAME
7349 }) {
7350 let planes = [
7351 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7352 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7353 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7354 ];
7355 // Which alphabet this block's writer will code the symbol against
7356 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
7357 // 3-symbol one only under `allow_warped_motion` and at least one warp
7358 // sample. Mirrored here so the candidates are priced against the
7359 // table the tile really narrows.
7360 let warp_alphabet = warp_on()
7361 && crate::decode::num_proj_ref(
7362 grid,
7363 mi_row,
7364 mi_col,
7365 side / 4,
7366 side / 4,
7367 mi_cols,
7368 mi_rows,
7369 info.ref_frame,
7370 fctx,
7371 ) >= 1;
7372 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
7373 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
7374 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
7375 if let Some(pred) = obmc_prediction(
7376 grid,
7377 (mi_row, mi_col),
7378 (mi_rows, mi_cols),
7379 (x, y),
7380 side,
7381 info.mv,
7382 refs,
7383 planes,
7384 reference.width,
7385 fctx,
7386 ) {
7387 candidates.push((1, pred));
7388 }
7389 }
7390 if warp_alphabet {
7391 if let Some(pred) = warp_prediction(
7392 grid,
7393 (mi_row, mi_col),
7394 (mi_rows, mi_cols),
7395 (x, y),
7396 side,
7397 info.mv,
7398 info.ref_frame,
7399 planes,
7400 fctx,
7401 ) {
7402 candidates.push((2, pred));
7403 }
7404 }
7405 for (motion, pred) in candidates {
7406 let luma_o = luma.code_from_prediction(
7407 x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set,
7408 );
7409 let u_o = chroma[0].code_from_prediction(
7410 x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone,
7411 chroma_set,
7412 );
7413 let v_o = chroma[1].code_from_prediction(
7414 x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone,
7415 chroma_set,
7416 );
7417 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
7418 && u_o.levels.iter().all(|&l| l == 0)
7419 && v_o.levels.iter().all(|&l| l == 0);
7420 let cost_o = luma_o.sse
7421 + u_o.sse
7422 + v_o.sse
7423 + search.lambda
7424 * (skip_bits(skip_o)
7425 + single_syntax
7426 + mm(motion)
7427 + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits });
7428 // The incumbent pays the motion_mode symbol IT would code, so
7429 // both sides of the comparison carry that syntax.
7430 if cost_o < best.0 + search.lambda * mm(motion_won) {
7431 motion_won = motion;
7432 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
7433 }
7434 }
7435 }
7436
7437 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
7438 if cost < intra_cost {
7439 // A compound winner commits the flat trial it was priced from:
7440 // `commit_inter_luma`'s var-tx trial set is single-reference
7441 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
7442 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
7443 // predicting each half-side trial from BOTH references, verified
7444 // byte-identical to this when its split is disabled) and MEASURED
7445 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
7446 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
7447 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
7448 // compound block's residual is small enough that the four extra
7449 // per-unit txb_skip/eob symbols cost more ladder bytes than this
7450 // encoder's static-CDF estimate prices them at, so the local RD
7451 // win does not convert. lane-av1txbits REBUILT it on top of a
7452 // search that prices against the tables the frame is really
7453 // written with (`tile::arm_pricing_cdfs`, the estimate error on
7454 // these very blocks measured down from +31% to +3%) and measured
7455 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
7456 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
7457 // same build without it. The static-CDF estimate was NOT what
7458 // held the compound var-tx trial back. The flat trial stays.
7459 // An OBMC winner commits the flat trial too: `commit_inter_luma`
7460 // re-predicts each var-tx unit by plain translation, which is not
7461 // the prediction this candidate was priced from.
7462 // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
7463 // 0.05 (both rejections above were measured at 0.1, the weight
7464 // the lambda lane showed was 2x too heavy): a compound winner is
7465 // offered the same var-tx split, its units predicted from BOTH
7466 // references (`mc_trial_compound`). RE-MEASURED native: film
7467 // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
7468 // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
7469 // one row 0.2 down, two flat, short of the two-down-one-flat keep
7470 // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
7471 // rather than change the default on a single 0.2 row. It fires:
7472 // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
7473 // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
7474 // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
7475 // 1.3/1.2 down there, which is where the upgrade path is if this
7476 // is picked up again.
7477 let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
7478 refs[r as usize].map(|g| {
7479 (
7480 info.mv1,
7481 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
7482 )
7483 })
7484 });
7485 let (levels, tx_depth, dcost, luma_tx_types) = if motion_won != 0
7486 || (info.ref1.is_some() && second.is_none())
7487 {
7488 luma.commit(x, y, side, &luma_new);
7489 (luma_new.levels.clone(), 0, 0.0, Vec::new())
7490 } else {
7491 commit_inter_luma(
7492 luma, (x, y), side, info.mv,
7493 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7494 search, &luma_new, skip_new, second, fctx,
7495 )
7496 };
7497 // lane-txrd: chroma follows the luma type the search just chose.
7498 let [u_new, v_new] = match luma_tx_types.first().copied() {
7499 Some(t) => recode_inter_chroma(
7500 chroma, (x, y), side, info.mv,
7501 [
7502 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7503 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7504 ],
7505 info.ref1.filter(|_| motion_won == 0).and_then(|r| {
7506 refs[r as usize].map(|g| {
7507 (
7508 info.mv1,
7509 [
7510 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
7511 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
7512 ],
7513 )
7514 })
7515 }),
7516 search, chroma_set, t, fctx,
7517 )
7518 .unwrap_or([u_new, v_new]),
7519 None => [u_new, v_new],
7520 };
7521 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
7522 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
7523 return (
7524 BlockCoeffs {
7525 angle_delta_y: 0,
7526 cfl_alphas: None,
7527 filter_intra: None,
7528 luma: coeffs(&levels, side),
7529 u: coeffs(&u_new.levels, side / 2),
7530 v: coeffs(&v_new.levels, side / 2),
7531 mode: DC_PRED as u8,
7532 uv_mode: DC_PRED,
7533 skip: skip_new,
7534 eight: None,
7535 dv: None,
7536 palette: None,
7537 palette_uv: None,
7538 tx_depth,
7539 luma_tx_types,
7540 inter: Some(info),
7541 motion_mode: motion_won,
7542 },
7543 cost + dcost,
7544 );
7545 }
7546 }
7547
7548 census_add(8, 1);
7549 if skip {
7550 census_add(10, 1);
7551 }
7552 if inter_cost >= intra_cost {
7553 census_add(9, 1);
7554 }
7555 if inter_cost < intra_cost {
7556 let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma(
7557 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,
7558 );
7559 // lane-txrd: chroma follows the luma type (this tail's block is
7560 // single-reference `NEARESTMV`, so no compound second half).
7561 let [u, v] = match luma_tx_types.first().copied() {
7562 Some(t) => recode_inter_chroma(
7563 chroma, (x, y), side, mv,
7564 [
7565 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7566 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7567 ],
7568 None, search, chroma_set, t, fctx,
7569 )
7570 .unwrap_or([u, v]),
7571 None => [u, v],
7572 };
7573 chroma[0].commit(x / 2, y / 2, side / 2, &u);
7574 chroma[1].commit(x / 2, y / 2, side / 2, &v);
7575 (BlockCoeffs {
7576 luma_tx_types,
7577 angle_delta_y: 0,
7578 cfl_alphas: None,
7579 filter_intra: None,
7580 luma: coeffs(&levels, side),
7581 u: coeffs(&u.levels, side / 2),
7582 v: coeffs(&v.levels, side / 2),
7583 mode: DC_PRED as u8,
7584 uv_mode: DC_PRED,
7585 skip,
7586 eight: None,
7587 dv: None,
7588 palette: None,
7589 palette_uv: None,
7590 tx_depth,
7591 motion_mode: 0,
7592 inter: Some(InterInfo {
7593 ref1: None,
7594 mv1: (0, 0),
7595 ref_frame: crate::mvstack::LAST_FRAME,
7596 mode: InterMode::NearestMv,
7597 mv,
7598 ref_mv_idx: 0,
7599 }),
7600 }, inter_cost + dcost)
7601 } else {
7602 (intra_block, intra_cost)
7603 }
7604}
7605
7606/// Publishes one coded inter-frame block into the `mi` grid the next block's
7607/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
7608/// block casts no vote but is still a coded cell (see `code_square_inter`'s
7609/// note on `processed_rows`/`processed_cols`).
7610fn record_mi(
7611 grid: &mut MiGrid,
7612 mi_row: usize,
7613 mi_col: usize,
7614 size: u8,
7615 inter: Option<InterInfo>,
7616 // lane-ctx: the block's own `skip`, so the next block's MV stack can hand
7617 // the RD pricer the two cells the writer's `skip_ctx` sums.
7618 skip: bool,
7619) {
7620 let info = match inter {
7621 Some(info) => MiInfo {
7622 is_inter: true,
7623 ref_frame: info.ref_frame,
7624 // A COMPOUND block votes with BOTH of its references and both of
7625 // its vectors, exactly as the tile writer publishes it: recording
7626 // a compound block as a single-reference one here left the
7627 // encoder's own grid disagreeing with the writer's from the first
7628 // compound block on, so every later stack it searched against was
7629 // not the stack the decoder derives.
7630 ref_frame1: info.ref1.unwrap_or(NO_REF1),
7631 mv1: mv16(info.mv1),
7632 mv: mv16(info.mv),
7633 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
7634 // side, compound modes 2/3/7 on the other.
7635 is_new_mv: matches!(
7636 info.mode,
7637 InterMode::NewMv
7638 | InterMode::NewNewMv
7639 | InterMode::NearestNewMv
7640 | InterMode::NewNearestMv
7641 ),
7642 size,
7643 size_h: size,
7644 is_global_mv0: false,
7645 is_global_mv1: false,
7646 },
7647 None => MiInfo {
7648 is_inter: false,
7649 ref_frame: -1,
7650 ref_frame1: NO_REF1,
7651 mv1: (0, 0),
7652 mv: (0, 0),
7653 is_new_mv: false,
7654 size,
7655 size_h: size,
7656 is_global_mv0: false,
7657 is_global_mv1: false,
7658 },
7659 };
7660 for dr in 0..usize::from(size) {
7661 for dc in 0..usize::from(size) {
7662 grid.set(mi_row + dr, mi_col + dc, info);
7663 grid.set_skip(mi_row + dr, mi_col + dc, skip);
7664 }
7665 }
7666}
7667
7668/// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the
7669/// writer's own `write_inter_block_128_rect` makes, so the second half of a
7670/// HORZ/VERT 128 root searches against the stack the writer will rebuild.
7671fn record_mi_rect(
7672 grid: &mut MiGrid,
7673 mi_row: usize,
7674 mi_col: usize,
7675 (w_mi, h_mi): (usize, usize),
7676 inter: Option<InterInfo>,
7677 skip: bool,
7678) {
7679 record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip);
7680 // `record_mi` stamped the square corner; widen it to the true footprint,
7681 // with the block's own (rect) size fields.
7682 let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded");
7683 info.size = w_mi as u8;
7684 info.size_h = h_mi as u8;
7685 for dr in 0..h_mi {
7686 for dc in 0..w_mi {
7687 grid.set(mi_row + dr, mi_col + dc, info);
7688 grid.set_skip(mi_row + dr, mi_col + dc, skip);
7689 }
7690 }
7691}
7692
7693/// The reconstructed samples one 32x32 square covers in all three planes, so
7694/// that a partition trial can be undone.
7695/// One square of a plane, row-major, the inverse of [`Plane::restore`].
7696///
7697/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
7698/// which allocated and freed a `Vec` per row of every block it copied --
7699/// `Plane::snapshot` runs once per partition trial.
7700fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
7701 let mut out = vec![0u8; side * side];
7702 for row in 0..side {
7703 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
7704 }
7705 out
7706}
7707
7708fn snapshot(
7709 luma: &Plane,
7710 chroma: &[Plane; 2],
7711 (x, y): (usize, usize),
7712 side: usize,
7713) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
7714 [
7715 luma.snapshot(x, y, side),
7716 chroma[0].snapshot(x / 2, y / 2, side / 2),
7717 chroma[1].snapshot(x / 2, y / 2, side / 2),
7718 ]
7719}
7720
7721/// Puts such a snapshot back.
7722fn restore(
7723 luma: &mut Plane,
7724 chroma: &mut [Plane; 2],
7725 (x, y): (usize, usize),
7726 side: usize,
7727 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
7728) {
7729 luma.restore(x, y, side, &saved[0]);
7730 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
7731 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
7732}
7733
7734/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
7735/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
7736/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
7737/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
7738/// rule shared with the key-frame path, not a second one that could diverge.
7739fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
7740 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
7741 let dc_entry = dc_pos.map(|i| scored.remove(i));
7742 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
7743 scored.truncate(if dc_entry.is_some() {
7744 top_k.saturating_sub(1)
7745 } else {
7746 top_k
7747 });
7748 if let Some(dc_entry) = dc_entry {
7749 scored.push(dc_entry);
7750 }
7751 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
7752 modes.iter().copied().filter(|m| keep.contains(m)).collect()
7753}
7754
7755fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
7756 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
7757 [INTRA_MODE_CTX[usize::from(left_mode)]];
7758 std::array::from_fn(|mode| {
7759 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
7760 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
7761 } else {
7762 0.0
7763 };
7764 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
7765 })
7766}
7767
7768/// What the luma mode search picks between, and under what terms.
7769#[derive(Clone, Copy)]
7770struct Search<'a> {
7771 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
7772 /// luma search then offers a palette candidate beside the intra modes.
7773 screen: bool,
7774 base_q_idx: u8,
7775 deadzone: f64,
7776 lambda: f64,
7777 modes: &'a [u8],
7778 /// How many of `modes` the full RD trial (forward transform, quantize,
7779 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
7780 /// pre-pass on the prediction residual alone plus DC (always kept, since
7781 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
7782 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
7783 /// mode through full RD, unchanged from before this lever.
7784 top_k: Option<usize>,
7785 /// lane-arfmode: the top ARF's offer set ([`crate::speed::ARFMODE`])
7786 /// -- `false` cuts the named candidate group from the whole-32 search
7787 /// ([`search_inter_block`]), the 16x16/8x8 leaf search
7788 /// ([`code_square_inter`]) and the 8x8 split offer, at the top ARF
7789 /// ([`DqLevel::TopArf`] frames only). `true` everywhere else, which is
7790 /// the pre-lane behaviour: the mid and quarter hidden frames, the shown
7791 /// leaves and the flat path keep intra and compound, and the
7792 /// straddling-edge 8x8s are only mode-gated, never partition-gated.
7793 /// The probe's correction: with the leaf gate ALONE the film A stream
7794 /// was byte-identical to the control -- the ARF's intra area lives at
7795 /// the whole-32 level, so the intra arm must cut it there too.
7796 arf_leaf_intra: bool,
7797 arf_leaf8: bool,
7798 arf_leaf_compound: bool,
7799}
7800
7801/// [`Search`]'s ARF fields' source: [`crate::speed::ARFMODE`], or what
7802/// `EC_AV1_ARFMODE` names on one build (a missing or broken value keeps the
7803/// shipped table -- 0, bit-exact with the pre-lane encoder).
7804fn arfmode() -> u8 {
7805 match ARFMODE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
7806 u8::MAX => {}
7807 n => return n,
7808 }
7809 static ENV: std::sync::LazyLock<Option<u8>> = std::sync::LazyLock::new(|| {
7810 crate::envflags::var("EC_AV1_ARFMODE").ok().and_then(|v| v.parse().ok())
7811 });
7812 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ARFMODE))
7813}
7814
7815/// [`ARFMODE_OVERRIDE`]: `u8::MAX` clears it.
7816static ARFMODE_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
7817
7818/// Sets [`ARFMODE_OVERRIDE`]; `None` clears it. Test-only: the env is a
7819/// process constant ([`crate::envflags`]), so an in-process witness needs
7820/// this to arm the lever.
7821#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
7822pub(crate) fn set_arfmode(n: Option<u8>) {
7823 ARFMODE_OVERRIDE.store(n.unwrap_or(u8::MAX), std::sync::atomic::Ordering::Relaxed);
7824}
7825
7826/// How often each armed [`crate::speed::ARFMODE`] arm actually fired since
7827/// the last take (class `gate-blind-to-feature`): 0 = a top-ARF leaf coded
7828/// with its intra candidate skipped, 1 = a top-ARF 16x16 leaf whose 8x8
7829/// split the search would have offered and the arm refused, 2 = a top-ARF
7830/// leaf whose compound set was dropped. A green gate over counts of zero
7831/// proves nothing about the lever.
7832static ARFMODE_HITS: [std::sync::atomic::AtomicUsize; 3] = [
7833 std::sync::atomic::AtomicUsize::new(0),
7834 std::sync::atomic::AtomicUsize::new(0),
7835 std::sync::atomic::AtomicUsize::new(0),
7836];
7837
7838/// Records one such hit.
7839fn arfmode_hit(which: usize) {
7840 ARFMODE_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7841}
7842
7843/// [`arfmode_hit`]`(1)` and "no": the `||` arm of the top ARF's 8x8-offer
7844/// condition, so the counter only runs when every other prune let the split
7845/// through and the arm alone refuses it.
7846fn arfmode_hit_and_no() -> bool {
7847 arfmode_hit(1);
7848 false
7849}
7850
7851/// Takes (and clears) the counts. `pub` for `examples/enc_probe`, so a
7852/// probe point can print a non-zero engagement count under the env knob
7853/// itself -- the counter the gate BD numbers are read against.
7854pub fn take_arfmode_hits() -> [usize; 3] {
7855 [0, 1, 2].map(|i| ARFMODE_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
7856}
7857
7858fn prune_top_k() -> Option<usize> {
7859 #[cfg(test)]
7860 {
7861 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
7862 return k;
7863 }
7864 }
7865 let swept = std::env::var("EC_AV1_PRUNE_K")
7866 .ok()
7867 .and_then(|v| v.parse::<usize>().ok());
7868 match swept {
7869 Some(k) if cfg!(test) => Some(k),
7870 _ => crate::speed::at(&crate::speed::PRUNE_K),
7871 }
7872}
7873
7874// A per-thread override [`prune_top_k`] checks first, so one test can sweep
7875// `top_k` in-process without mutating the environment (forbidden here --
7876// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
7877#[cfg(test)]
7878thread_local! {
7879 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
7880 const { std::cell::Cell::new(None) };
7881}
7882
7883#[cfg(test)]
7884fn set_test_top_k_override(value: Option<usize>) {
7885 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
7886}
7887
7888/// The default: unpruned, thirteen full trials per block, same as before this
7889/// lever. Set from the sweep in the lane report if the quality gate clears it.
7890pub(crate) const PRUNE_TOP_K: Option<usize> = None;
7891
7892/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
7893/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
7894/// quality gates were measured separately and may land on different
7895/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
7896/// [`EC_AV1_PRUNE_K`] or the key-frame path.
7897fn prune_top_k_inter() -> Option<usize> {
7898 #[cfg(test)]
7899 {
7900 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
7901 return k;
7902 }
7903 }
7904 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
7905 .ok()
7906 .and_then(|v| v.parse::<usize>().ok());
7907 match swept {
7908 Some(k) if cfg!(test) => Some(k),
7909 _ => crate::speed::at(&crate::speed::PRUNE_K_INTER),
7910 }
7911}
7912
7913// A per-thread override [`prune_top_k_inter`] checks first, same reason as
7914// [`TEST_TOP_K_OVERRIDE`].
7915#[cfg(test)]
7916thread_local! {
7917 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
7918 const { std::cell::Cell::new(None) };
7919}
7920
7921#[cfg(test)]
7922fn set_test_top_k_override_inter(value: Option<usize>) {
7923 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
7924}
7925
7926/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
7927/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
7928/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
7929/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
7930/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
7931/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
7932/// pruning them costs less quality here.
7933pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
7934
7935// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
7936// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
7937// inter frame's cost can be attributed to a bucket without changing what
7938// the search actually does. Index: 0 = whole-call time inside
7939// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
7940// [`crate::mc::predict`] (every call, from the motion search's own
7941// candidates and from a committed inter block's final prediction alike),
7942// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
7943#[cfg(test)]
7944thread_local! {
7945 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
7946 std::cell::Cell::new(0),
7947 std::cell::Cell::new(0),
7948 std::cell::Cell::new(0),
7949 std::cell::Cell::new(0),
7950 ];
7951}
7952
7953/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and
7954/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran
7955/// per transform trial and per `mc::predict` call whether or not anyone was
7956/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile).
7957/// The clock is now read only when [`crate::par::stage_times`] is on, which
7958/// is what prints the breakdown in the first place.
7959#[cfg(test)]
7960pub(crate) fn stage_start() -> Option<std::time::Instant> {
7961 crate::par::stage_times().then(std::time::Instant::now)
7962}
7963
7964#[cfg(test)]
7965pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) {
7966 if let Some(t) = t {
7967 stage_add(bucket, t.elapsed());
7968 }
7969}
7970
7971#[cfg(test)]
7972pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
7973 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
7974}
7975
7976#[cfg(test)]
7977fn stage_reset() {
7978 crate::par::set_stage_times(true);
7979 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
7980}
7981
7982#[cfg(test)]
7983fn stage_read() -> [std::time::Duration; 4] {
7984 crate::par::set_stage_times(false);
7985 STAGE_NS.with(|c| {
7986 c.each_ref()
7987 .map(|cell| std::time::Duration::from_nanos(cell.get()))
7988 })
7989}
7990
7991/// One mode's coding of one block, before it is committed.
7992#[derive(Clone)]
7993struct Trial {
7994 levels: Vec<i32>,
7995 reconstruction: Vec<u8>,
7996 sse: f64,
7997 bits: f64,
7998}
7999
8000/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part
8001/// of a 64-point transform that is actually coded (everything outside it is
8002/// zeroed by [`crate::transform::quantize`] already, so this only reshapes).
8003fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> {
8004 let mut out = vec![0i32; to * to];
8005 for row in 0..to {
8006 out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]);
8007 }
8008 out
8009}
8010
8011/// The non-zero levels of a block, as the tile writer takes them.
8012fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
8013 levels
8014 .iter()
8015 .enumerate()
8016 .filter(|&(_, &level)| level != 0)
8017 .map(|(i, &level)| Coeff {
8018 row: (i / side) as u8,
8019 col: (i % side) as u8,
8020 level,
8021 })
8022 .collect()
8023}
8024
8025thread_local! {
8026 /// The tile grid the next frame is coded with, as `(TileColsLog2,
8027 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
8028 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
8029 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
8030 /// one tile per frame, what every caller that never arms anything gets
8031 /// and what every stream this crate wrote before tiles existed carries.
8032 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
8033}
8034
8035/// Arms this thread's next frame encodes with a tile grid (log2 counts).
8036pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
8037 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
8038}
8039
8040fn armed_tiles() -> (u32, u32) {
8041 let armed = TILE_LOG2.with(std::cell::Cell::get);
8042 if armed != (0, 0) {
8043 return armed;
8044 }
8045 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
8046 // (which codes through `encode_sequence`, not the facade) can measure what
8047 // a tile grid costs without a knob of its own -- same shape as
8048 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
8049 match std::env::var("EC_AV1_TILES").ok() {
8050 Some(v) if cfg!(test) => {
8051 let mut f = v.split(':');
8052 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
8053 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
8054 (cols, rows)
8055 }
8056 _ => armed,
8057 }
8058}
8059
8060/// Codes a frame's `tiles` tiles, each entirely on its own (see
8061/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
8062/// the crate's own pool, and hands back their payloads in tile order plus
8063/// whatever `code` returned for tile `store` -- the CDF state
8064/// `context_update_tile_id` names. The result cannot depend on the thread
8065/// count: each job writes one tile from the frame's own starting tables into
8066/// its own slot.
8067fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
8068where
8069 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
8070{
8071 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
8072 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
8073 let threads = crate::par::tile_threads().min(tiles);
8074 let mut slots: Vec<Slot> = Vec::new();
8075 if threads <= 1 {
8076 for index in 0..tiles {
8077 slots.push(Some(code(index)));
8078 }
8079 } else {
8080 let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8081 {
8082 let batch = crate::par::Batch::new("ec-av1-tile");
8083 for (from, to) in crate::par::bands(tiles, threads) {
8084 let done = &done;
8085 let code = &code;
8086 batch.submit(move || {
8087 for index in from..to {
8088 let coded = code(index);
8089 done.lock().expect("tile slots")[index] = Some(coded);
8090 }
8091 });
8092 }
8093 }
8094 slots = done.into_inner().expect("tile slots");
8095 }
8096 let mut out = Vec::with_capacity(tiles);
8097 let mut stored = None;
8098 for (index, slot) in slots.into_iter().enumerate() {
8099 let (bytes, cdfs) = slot.expect("every tile was coded")?;
8100 if index == store {
8101 stored = cdfs;
8102 }
8103 out.push(bytes);
8104 }
8105 Ok((out, stored))
8106}
8107
8108/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
8109/// workers, and returns the results in tile order. The counterpart of
8110/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
8111/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
8112/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
8113/// availability is already tile-relative (`clip_planes_to_tile`,
8114/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
8115/// other tiles have run -- gated by
8116/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
8117/// covers the search as well as the write.
8118///
8119/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
8120/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
8121/// does it for the decoder's filter bands.
8122fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
8123where
8124 T: Send,
8125 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
8126{
8127 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
8128 let threads = crate::par::tile_threads().min(tiles);
8129 if threads <= 1 {
8130 return (0..tiles).map(|index| job(index, fctx)).collect();
8131 }
8132 type Slot<T> = Option<Result<T>>;
8133 let done: std::sync::Mutex<Vec<Slot<T>>> =
8134 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8135 {
8136 let batch = crate::par::Batch::new("ec-av1-tile-search");
8137 for (from, to) in crate::par::bands(tiles, threads) {
8138 let done = &done;
8139 let job = &job;
8140 let ctx = crate::decode::filter_ctx_copy(fctx);
8141 batch.submit(move || {
8142 for index in from..to {
8143 let searched = job(index, &ctx);
8144 done.lock().expect("tile slots")[index] = Some(searched);
8145 }
8146 });
8147 }
8148 }
8149 done.into_inner()
8150 .expect("tile slots")
8151 .into_iter()
8152 .map(|slot| slot.expect("every tile was searched"))
8153 .collect()
8154}
8155
8156/// One tile job's own copy of a plane: the frame's source, a blank
8157/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
8158/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
8159/// of the frame's reconstruction because a tile's prediction never reads a
8160/// sample outside its own rectangle, and every sample inside it is written
8161/// before it is read.
8162fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
8163 Plane {
8164 source,
8165 reconstruction: vec![128; source.len()],
8166 width,
8167 height,
8168 true_width,
8169 true_height,
8170 tile_x0: 0,
8171 tile_y0: 0,
8172 tile_x1: width,
8173 tile_y1: height,
8174 ctx: CoefCtxMap::default(),
8175 }
8176}
8177
8178/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
8179/// the frame's plane, through the [`crate::par::Shared`] every job holds.
8180///
8181/// corner-cut: the disjointness that makes the aliasing sound is the caller's
8182/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
8183/// rectangles partition it -- checked end-to-end by
8184/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
8185/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
8186/// row-range `split_at_mut` plumbing through `Plane`, which would have to
8187/// thread an origin offset through every prediction and transform call site
8188/// for the same bytes.
8189#[allow(unsafe_code)]
8190fn copy_rect(
8191 dst: crate::par::Shared<'_, Vec<u8>>,
8192 src: &[u8],
8193 stride: usize,
8194 x0: usize,
8195 y0: usize,
8196 x1: usize,
8197 y1: usize,
8198) {
8199 // SAFETY: this job touches only its own tile rectangle (see above).
8200 let dst = unsafe { dst.get() };
8201 for y in y0..y1 {
8202 let (a, b) = (y * stride + x0, y * stride + x1);
8203 dst[a..b].copy_from_slice(&src[a..b]);
8204 }
8205}
8206
8207/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
8208/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
8209/// tables the frame stores (spec 7.20), which is what
8210/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
8211/// below publish.
8212fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
8213 ec_av1_syntax::TileInfo {
8214 uniform_spacing: true,
8215 cols: layout.cols(),
8216 rows: layout.rows(),
8217 cols_log2: layout.cols_log2,
8218 rows_log2: layout.rows_log2,
8219 mi_col_starts: layout.mi_col_starts(),
8220 mi_row_starts: layout.mi_row_starts(),
8221 context_update_tile_id: layout.largest_tile() as u32,
8222 tile_size_bytes,
8223 }
8224}
8225
8226/// Clips the three planes' intra edge reads to `rect`, the tile the
8227/// superblock about to be searched belongs to (the encoder side of the
8228/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
8229/// raster order -- which is a linear extension of every tile's own coding
8230/// order, so a block still only ever predicts from samples already
8231/// reconstructed -- and only availability is tile-relative.
8232fn clip_planes_to_tile(
8233 luma: &mut Plane<'_>,
8234 chroma: &mut [Plane<'_>; 2],
8235 rect: crate::tile::TileRect,
8236) {
8237 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8238 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8239 luma.set_tile(x0, y0, x1, y1);
8240 for plane in chroma.iter_mut() {
8241 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
8242 }
8243}
8244
8245/// Encodes one picture as a key frame.
8246///
8247/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
8248/// picks its coefficient CDFs from one of four q contexts by that index.
8249/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
8250/// smaller values trade fidelity for rate.
8251///
8252/// The picture may be any even width and height: the encoder pads it by edge
8253/// replication to a whole number of 32x32 blocks internally, and the frame it
8254/// writes crops back to the picture's own size (`render_width`/
8255/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
8256/// own size, never the padded one.
8257///
8258/// # Errors
8259/// Returns an error when the picture's width or height is zero or odd, or
8260/// when its planes are not 4:2:0 of that size.
8261/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
8262/// stream. The per-frame decode state this needs lives for exactly this call.
8263///
8264/// # Errors
8265/// Returns an error under the same conditions
8266/// [`encode_key_frame_with_modes`] does.
8267pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
8268 encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder())
8269}
8270
8271/// [`encode_key_frame`] with the per-block intra modes given rather than
8272/// searched.
8273///
8274/// # Errors
8275/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
8276/// is empty, or when a block's coefficients do not fit the coded frame.
8277pub fn encode_key_frame_with_modes(
8278 picture: &Picture,
8279 base_q_idx: u8,
8280 deadzone: f64,
8281 modes: &[u8],
8282) -> Result<Encoded> {
8283 encode_key_frame_with_modes_with_ctx(
8284 picture,
8285 base_q_idx,
8286 deadzone,
8287 modes,
8288 &crate::decode::FrameCtx::for_encoder(),
8289 )
8290}
8291
8292/// Codes `pictures` as one key frame followed by inter frames.
8293///
8294/// Camera material is coded under [`crate::encoder::Pyramid::default`] since
8295/// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a
8296/// `show_existing_frame` header, so `stream` is in CODING order while
8297/// `frames` stays in display order (`EncodedSequence::coding_order` is the
8298/// map). Screen content codes flat, decided once per sequence by the same
8299/// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0`
8300/// puts every stream back on the flat path for an A/B.
8301///
8302/// # Errors
8303/// Returns an error under the same conditions [`encode_key_frame`] and the
8304/// inter frame path do.
8305pub fn encode_sequence(
8306 pictures: &[Picture],
8307 base_q_idx: u8,
8308 deadzone: f64,
8309) -> Result<EncodedSequence> {
8310 encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder())
8311}
8312
8313pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
8314 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
8315}
8316
8317/// Encodes one picture as a key frame, choosing each block's luma mode from
8318/// `modes` alone.
8319///
8320/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
8321/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
8322/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
8323/// uses.
8324///
8325/// # Errors
8326/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
8327/// names a mode [`crate::intra::predict`] does not predict.
8328pub(crate) fn encode_key_frame_with_modes_with_ctx(
8329 picture: &Picture,
8330 base_q_idx: u8,
8331 deadzone: f64,
8332 modes: &[u8], fctx: &crate::decode::FrameCtx,
8333) -> Result<Encoded> {
8334 picture.check_even()?;
8335 let padded = picture.padded_to(BLOCK);
8336 let encoded = encode_key_frame_inner(
8337 &padded,
8338 base_q_idx,
8339 deadzone,
8340 modes,
8341 split_blocks(),
8342 (picture.width, picture.height),
8343 unspecified_color_config(), fctx,
8344 )?;
8345 Ok(crop_encoded(&encoded, picture.width, picture.height))
8346}
8347
8348/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
8349/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
8350/// already padded to a whole number of 32x32 blocks; `render` is the real
8351/// (pre-pad) size the frame header tells a decoder to crop back to.
8352pub(crate) fn encode_key_frame_inner(
8353 picture: &Picture,
8354 base_q_idx: u8,
8355 deadzone: f64,
8356 modes: &[u8],
8357 split_blocks: bool,
8358 render: (usize, usize),
8359 color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
8360) -> Result<Encoded> {
8361 // lane-refs: an intra frame runs no motion compensation, and the
8362 // context is shared across the sequence -- put the kernel back to the
8363 // default so nothing reads the previous inter frame's.
8364 fctx.interp_filter.set(mc::InterpFilterKind::Regular);
8365 picture.check()?;
8366 if modes.is_empty() {
8367 return Err(Error::unsupported(
8368 "AV1 encode",
8369 "a mode search needs at least one mode to choose from",
8370 ));
8371 }
8372 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
8373 return Err(Error::unsupported(
8374 "AV1 encode",
8375 format!("intra mode {bad} is not one the encoder predicts"),
8376 ));
8377 }
8378 // The header carries the frame's true (unpadded) size as `frame_width`/
8379 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
8380 // `mi_rows` derived from that same true size (spec `compute_image_size`).
8381 // `render_width`/`render_height` come out equal to it too, so
8382 // `render_and_frame_size_different` is false and no render_size bits are
8383 // written, mirroring libaom/rav1e: the padded `picture` below is only the
8384 // internal coding surface, never what the header names.
8385 // Screen-content detection runs on the SOURCE luma, before any header is
8386 // built: it decides this sequence's `seq_force_screen_content_tools` (and
8387 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
8388 // this frame's own `allow_screen_content_tools`.
8389 let screen = screen_content(
8390 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
8391 picture.width,
8392 (picture.width).min(render.0),
8393 (picture.height).min(render.1),
8394 );
8395 arm_seq_screen(screen);
8396 // A key frame's writer really does start from the defaults, and a search
8397 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
8398 // disarm, or a key frame's bits would depend on which thread searched it.
8399 crate::tile::arm_pricing_cdfs(None, false);
8400 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
8401 // forces deblocking, CDEF and loop restoration OFF for this frame
8402 // (frame.rs:194/210/252/272), so it is only set when the source repeats
8403 // itself enough for the copied blocks to pay that back
8404 // ([`intrabc_worth_it`]).
8405 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
8406 // grid across every tile while this writer builds one per tile, so a
8407 // multi-tile allow_intrabc frame would predict its DVs off a different
8408 // grid than the decoder does. corner-cut, ceiling named: the upgrade
8409 // path is a frame-scoped grid shared by the tile writers.
8410 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
8411 intrabc_worth_it(
8412 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
8413 picture.width,
8414 picture.width.min(render.0),
8415 picture.height.min(render.1),
8416 )
8417 } else {
8418 (false, 0.0)
8419 };
8420 IBC_SHARE.with(|c| c.set(ibc_share));
8421 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
8422 header.allow_screen_content_tools = screen;
8423 // lane-txi: the wider `tx_type` alphabets, gated by the same content
8424 // rule the type search itself stands behind ([`wide_tx_set`]).
8425 header.reduced_tx_set = !wide_tx_set(screen);
8426 header.allow_intrabc = allow_intrabc;
8427 header.render_width = render.0 as u32;
8428 header.render_height = render.1 as u32;
8429 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
8430 // its luma transform below its own side (`crate::tile::write_luma_select`).
8431 // Set here rather than in `key_frame_headers_colour` so the header
8432 // builders' other callers -- the hand-built tile writers, which code no
8433 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
8434 let tx_select = tx_select();
8435 if tx_select {
8436 header.tx_mode = TxMode::Select;
8437 }
8438 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
8439
8440 // Prediction reads no further than this, in each plane's own units --
8441 // see `Plane::true_width`/`true_height`.
8442 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
8443 // lane-palw: the encoder's own in-process reconstruct reads its palette
8444 // colour-index maps back through `decode::palette_onscreen`, which takes
8445 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
8446 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
8447 // them here so the reconstruct clamps a block cut by the frame edge
8448 // exactly as the writer now does.
8449 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
8450 fctx.seg_mi_dims.set(frame_mi_dims);
8451 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
8452 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
8453 // design (see `intra_predict_u8`'s doc comment), so narrow the source
8454 // once here.
8455 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
8456 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
8457 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
8458 let mut luma = Plane {
8459 source: &picture_y8,
8460 reconstruction: vec![128; picture_y8.len()],
8461 width: picture.width,
8462 height: picture.height,
8463 true_width,
8464 true_height,
8465 tile_x0: 0,
8466 tile_y0: 0,
8467 tile_x1: picture.width,
8468 tile_y1: picture.height,
8469 ctx: CoefCtxMap::default(),
8470 };
8471 let mut chroma = [
8472 Plane {
8473 source: &picture_u8,
8474 reconstruction: vec![128; picture_u8.len()],
8475 width: picture.width / 2,
8476 height: picture.height / 2,
8477 true_width: true_width / 2,
8478 true_height: true_height / 2,
8479 tile_x0: 0,
8480 tile_y0: 0,
8481 tile_x1: picture.width / 2,
8482 tile_y1: picture.height / 2,
8483 ctx: CoefCtxMap::default(),
8484 },
8485 Plane {
8486 source: &picture_v8,
8487 reconstruction: vec![128; picture_v8.len()],
8488 width: picture.width / 2,
8489 height: picture.height / 2,
8490 true_width: true_width / 2,
8491 true_height: true_height / 2,
8492 tile_x0: 0,
8493 tile_y0: 0,
8494 tile_x1: picture.width / 2,
8495 tile_y1: picture.height / 2,
8496 ctx: CoefCtxMap::default(),
8497 },
8498 ];
8499
8500 // The search trades a bit for the squared error it saves, in the units the
8501 // reconstruction is measured in: one step of the quantizer, squared.
8502 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
8503 let search = Search {
8504 base_q_idx,
8505 deadzone,
8506 lambda: lambda_scale() * key_lambda_factor() * step * step,
8507 modes,
8508 top_k: prune_top_k(),
8509 screen,
8510 arf_leaf_intra: true,
8511 arf_leaf8: true,
8512 arf_leaf_compound: true,
8513 };
8514
8515 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
8516 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
8517 // which may be fewer columns/rows than the padded picture has room for
8518 // -- a block whose origin sits past the true bound is not coded at all,
8519 // matching what a decoder derives from `frame_width`/`frame_height` and
8520 // so never visits either.
8521 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
8522 let (cols, rows) = (cols as usize, rows as usize);
8523 // The luma mode of the block above and of the block to the left, which is
8524 // what picks the CDF the next block's mode is coded against -- the same
8525 // bookkeeping the tile writer keeps, so that the search is costing the
8526 // symbol the writer will actually write.
8527 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
8528 // because a 32x32 block may be split into four 16x16 ones.
8529 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
8530 // This frame's tile grid (one tile unless the facade armed more).
8531 let layout =
8532 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
8533 header.tile_info = tile_info_of(&layout, 1);
8534 // The filter search re-decodes this frame's tiles; the decoder derives
8535 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
8536 // `mi_row_starts`), which is what makes the writer's rects and the
8537 // reader's the same rects.
8538 let header_tile_info = header.tile_info.clone();
8539 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
8540 // once over the whole frame. Each tile job builds its own reconstruction
8541 // planes and its own `above_mode`/`left_mode` bands, which is also what
8542 // the tile writer reads -- a tile resets its neighbour contexts (spec
8543 // 5.11.1), so a block at a tile's left edge must cost its mode against
8544 // the default context, not against whatever the tile to its west left in
8545 // that row. At one tile the bands are the frame's, exactly as before.
8546 let (frame_width, frame_height) = (picture.width, picture.height);
8547 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
8548 let [cb, cr] = &mut chroma;
8549 let chroma_out = [
8550 crate::par::Shared::new(&mut cb.reconstruction),
8551 crate::par::Shared::new(&mut cr.reconstruction),
8552 ];
8553 let search_tile = |index: usize,
8554 fctx: &crate::decode::FrameCtx|
8555 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
8556 crate::tile::arm_pricing_cdfs(None, false);
8557 let rect = layout.rect(index);
8558 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
8559 let mut chroma = [
8560 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
8561 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
8562 ];
8563 clip_planes_to_tile(&mut luma, &mut chroma, rect);
8564 let mut above_mode = vec![DC_PRED; cols * 2];
8565 let mut left_mode = vec![DC_PRED; rows * 2];
8566 let mut ibc = allow_intrabc.then(|| {
8567 Ibc::new(
8568 (
8569 rect.mi_col0 as usize * 4,
8570 rect.mi_row0 as usize * 4,
8571 (rect.mi_col1 as usize * 4).min(true_width),
8572 (rect.mi_row1 as usize * 4).min(true_height),
8573 ),
8574 &picture_y8,
8575 frame_width,
8576 )
8577 });
8578 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
8579 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
8580 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
8581 let mut modes = Vec::with_capacity(4);
8582 // The quadrants of a superblock are coded in the order the decoder
8583 // walks them, which for a 64x64 split into 32x32 blocks is raster
8584 // order among the quadrants that are inside the frame.
8585 let mut blocks = Vec::with_capacity(4);
8586 // lane-i64: the whole superblock as ONE 64x64 intra block, tried
8587 // BEFORE its quadrants (so both start from the same
8588 // reconstruction) and compared against the four of them below --
8589 // the shape the inter frame's own 64 root takes
8590 // (`search_skip_64`). A frame that allows intrabc is refused
8591 // outright ([`I64_ROOT`]) because the quadrant searches below
8592 // carry DV state a discarded trial would desync.
8593 let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK);
8594 // lane-corner LIFTED the two guards this root shipped with: the
8595 // frame no longer has to be a whole number of superblocks, and
8596 // the superblock no longer has to be wholly inside the frame.
8597 // The desync the guards were written for (a 248x152 corner's
8598 // chroma disagreeing three ways) does NOT reproduce at this
8599 // revision -- see
8600 // `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`,
8601 // which pins all three planes of the encoder's reconstruction,
8602 // our decoder and ffmpeg on four straddling sizes, three of them
8603 // cut on BOTH axes, with the edge fire count asserted. What the
8604 // guards cost was every key-frame root on an arbitrary export
8605 // size (the `aligned` line switched the whole feature off on, for
8606 // instance, a 1920x792 frame).
8607 let whole_inside = x64 + SUPERBLOCK <= luma.true_width
8608 && y64 + SUPERBLOCK <= luma.true_height;
8609 // lane-corner: and the superblock the true frame edge CUTS
8610 // THROUGH with more than half of each axis still inside, which is
8611 // all AV1 asks of a `PARTITION_NONE` root (spec
8612 // `decode_partition`'s `has_cols`/`has_rows`, the same pair the
8613 // key writer's `Superblock::Whole` arm checks) -- the shape the
8614 // inter root already takes ([`b64_edge`]).
8615 let edge_inside = edge_root_enabled()
8616 && crate::tile::has_half(
8617 sb_col as u32 * crate::tile::SB_MI,
8618 crate::tile::SB_MI,
8619 header.mi_cols,
8620 )
8621 && crate::tile::has_half(
8622 sb_row as u32 * crate::tile::SB_MI,
8623 crate::tile::SB_MI,
8624 header.mi_rows,
8625 );
8626 let sb64_legal = i64_root()
8627 && ibc.is_none()
8628 && sb_row * 2 + 1 < rows
8629 && sb_col * 2 + 1 < cols
8630 && (whole_inside || edge_inside);
8631 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
8632 if sb64_legal {
8633 I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8634 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
8635 let (c64, r64) = (sb_col * 4, sb_row * 4);
8636 let (block, cost) = code_square(
8637 &mut luma,
8638 &mut chroma,
8639 (x64, y64),
8640 SUPERBLOCK,
8641 &search,
8642 &mode_bits(above_mode[c64], left_mode[r64]),
8643 tx_select,
8644 None,
8645 true,
8646 fctx,
8647 );
8648 let cost = cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
8649 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
8650 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
8651 sb64 = Some((cost, block, after));
8652 }
8653 // A superblock whose 64x64 trial already codes almost nothing per
8654 // pixel is taken outright and its quadrants are never searched --
8655 // `split_rd_breakout` one size up, at the threshold the inter
8656 // root clamps to ([`b64_breakout_threshold`]), where this lever
8657 // BUYS wall instead of spending it.
8658 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
8659 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda)
8660 });
8661 // What the four quadrants cost together, including the split
8662 // partition symbol at the superblock level, so the two arms are
8663 // one comparable number.
8664 let mut sb_cost = match sb64 {
8665 Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true),
8666 None => 0.0,
8667 };
8668 for quadrant in 0..if early64 { 0 } else { 4 } {
8669 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
8670 if col >= cols || row >= rows {
8671 continue;
8672 }
8673 let (x, y) = (col * BLOCK, row * BLOCK);
8674 let (c0, r0) = (col * 2, row * 2);
8675 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
8676
8677 // spec `decode_partition`'s hasRows/hasCols recomputed at this
8678 // 32x32 block's own half (see `crate::tile::has_half`): the
8679 // true frame edge can fall inside a quadrant a superblock-level
8680 // check already let through. A quadrant that fails either may
8681 // not be left whole; a 16x16 sub-block that fails either (once
8682 // split) is a leaf this writer has no rectangular transform
8683 // for, so the search must not pick a split that would need one.
8684 let (has_cols32, has_rows32) = (
8685 crate::tile::has_half(
8686 col as u32 * crate::tile::BLOCK_MI,
8687 crate::tile::BLOCK_MI,
8688 header.mi_cols,
8689 ),
8690 crate::tile::has_half(
8691 row as u32 * crate::tile::BLOCK_MI,
8692 crate::tile::BLOCK_MI,
8693 header.mi_rows,
8694 ),
8695 );
8696 let whole_legal = has_cols32 && has_rows32;
8697 // A 16x16 sub-block's own hasCols/hasRows (spec
8698 // `decode_partition`, recomputed at this leaf's own half):
8699 // either axis false is a straddling leaf this writer codes as
8700 // the 8x8 leaves that are inside it
8701 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
8702 // false is the same split with the partition symbol inferred
8703 // rather than coded -- no rectangular transform is needed
8704 // (lane-av1rect).
8705 let sub_half = |sr: usize, sc: usize| {
8706 (
8707 crate::tile::has_half(
8708 sc as u32 * crate::tile::SUB_MI,
8709 crate::tile::SUB_MI,
8710 header.mi_cols,
8711 ),
8712 crate::tile::has_half(
8713 sr as u32 * crate::tile::SUB_MI,
8714 crate::tile::SUB_MI,
8715 header.mi_rows,
8716 ),
8717 )
8718 };
8719 // What the whole 32x32 costs, including the partition symbol
8720 // that says it is not split.
8721 let (whole, mut cost_whole) = code_square(
8722 &mut luma,
8723 &mut chroma,
8724 (x, y),
8725 BLOCK,
8726 &search,
8727 &mode_bits(above_mode[c0], left_mode[r0]),
8728 tx_select,
8729 ibc.as_mut(),
8730 true,
8731 fctx,
8732 );
8733 cost_whole += search.lambda * partition_bits(BLOCK, false);
8734 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
8735
8736 // What four 16x16 blocks cost instead, each searched against
8737 // the reconstruction the ones before it left.
8738 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
8739 let mut split = Vec::with_capacity(4);
8740 let mut cost_split = search.lambda
8741 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
8742 let mut split_modes = Vec::with_capacity(4);
8743 for sub in 0..4 {
8744 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
8745 // Same filter as the writer's `sub_positions` (spec
8746 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
8747 // return): a sub-block whose own origin sits past the
8748 // true frame is never coded, so it must not be searched
8749 // or pushed onto `split` either, or the writer's block
8750 // count will not match what it is prepared to name.
8751 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
8752 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
8753 {
8754 continue;
8755 }
8756 let (has_cols16, has_rows16) = sub_half(sr, sc);
8757 if has_cols16 && has_rows16 {
8758 let (block, cost) = code_square(
8759 &mut luma,
8760 &mut chroma,
8761 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
8762 SUB,
8763 &search,
8764 &mode_bits(above_mode[sc], left_mode[sr]),
8765 tx_select,
8766 ibc.as_mut(),
8767 true,
8768 fctx,
8769 );
8770 cost_split += cost;
8771 split_modes.push(block.mode);
8772 above_mode[sc] = block.mode;
8773 left_mode[sr] = block.mode;
8774 split.push(block);
8775 } else {
8776 // A straddling 16x16: two (or, at a true corner, one)
8777 // 8x8 leaves, in the raster order `write_leaf8`'s
8778 // caller expects. Both leaves cost against the SAME
8779 // enclosing-slot mode context (see
8780 // `crate::tile::write_leaf8`'s doc), and neither
8781 // updates `above_mode`/`left_mode` at this SUB slot --
8782 // the writer never does either, so the search must
8783 // not diverge from what it will actually read next.
8784 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
8785 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
8786 let mut leaves = Vec::with_capacity(2);
8787 for i in 0..4 {
8788 let leaf_x = x_sub + (i % 2) * 8;
8789 let leaf_y = y_sub + (i / 2) * 8;
8790 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
8791 continue;
8792 }
8793 let (leaf, cost) = code_square(
8794 &mut luma,
8795 &mut chroma,
8796 (leaf_x, leaf_y),
8797 8,
8798 &search,
8799 &leaf_mode_bits,
8800 tx_select,
8801 None,
8802 true,
8803 fctx,
8804 );
8805 cost_split += cost;
8806 split_modes.push(leaf.mode);
8807 leaves.push(leaf);
8808 }
8809 split.push(BlockCoeffs {
8810 eight: Some(leaves),
8811 ..BlockCoeffs::default()
8812 });
8813 }
8814 }
8815
8816 // A split whose subs are all whole 16x16 is a real quality
8817 // alternative to `whole`, exactly as before. Through r14, a
8818 // split carrying an 8x8-leaf sub was only ever forced
8819 // (`!whole_legal`), never chosen on cost, because the leaf
8820 // path was not yet proven against a real decoder; r15 proved
8821 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
8822 // the read path (`decode_leaf8`), so leaf8 can now win on
8823 // cost anywhere, same as any other split.
8824 if !whole_legal || (split_blocks && cost_split < cost_whole) {
8825 sb_cost += cost_split;
8826 modes.extend_from_slice(&split_modes);
8827 blocks.push(Quadrant::Split(split));
8828 } else {
8829 sb_cost += cost_whole;
8830 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
8831 for cell in 0..2 {
8832 above_mode[c0 + cell] = whole.mode;
8833 left_mode[r0 + cell] = whole.mode;
8834 }
8835 modes.push(whole.mode);
8836 blocks.push(Quadrant::Whole(whole));
8837 }
8838 }
8839 let index = sb_row * sb_cols + sb_col;
8840 match sb64 {
8841 Some((cost64, block, after)) if early64 || cost64 < sb_cost => {
8842 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
8843 for cell in 0..4 {
8844 above_mode[sb_col * 4 + cell] = block.mode;
8845 left_mode[sb_row * 4 + cell] = block.mode;
8846 }
8847 I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8848 if !whole_inside {
8849 I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8850 }
8851 let mode = block.mode;
8852 coded.push((index, Superblock::Whole(block), vec![mode]));
8853 }
8854 _ => coded.push((index, Superblock::Split(blocks), modes)),
8855 }
8856 }
8857 }
8858 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8859 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8860 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
8861 for (&out, tile) in chroma_out.iter().zip(&chroma) {
8862 copy_rect(
8863 out,
8864 &tile.reconstruction,
8865 frame_width / 2,
8866 x0 / 2,
8867 y0 / 2,
8868 x1.div_ceil(2),
8869 y1.div_ceil(2),
8870 );
8871 }
8872 Ok(coded)
8873 };
8874 let searched = search_tiles(layout.count(), fctx, search_tile)?;
8875 // Back into frame raster order: the tile writer indexes `superblocks` by
8876 // the frame's own superblock index, and `modes` is the coding order the
8877 // ablation drivers read.
8878 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
8879 for (at, superblock, block_modes) in searched.into_iter().flatten() {
8880 in_order[at] = Some((superblock, block_modes));
8881 }
8882 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
8883 let mut modes = Vec::with_capacity(cols * rows);
8884 for slot in in_order {
8885 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
8886 superblocks.push(superblock);
8887 modes.extend_from_slice(&block_modes);
8888 }
8889
8890 #[cfg(test)]
8891 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
8892 // A key frame always starts from the defaults (`primary_ref_frame` is
8893 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
8894 // set, so what it stores into the slots it refreshes is exactly those
8895 // defaults again (spec 7.20's `started_from` arm) -- the first inter
8896 // frame after it therefore starts from the defaults too.
8897 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
8898 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
8899 // lane-txi: the ONE place the writer reads the frame's `reduced_tx_set`
8900 // from -- `Cdfs::txb` widens every luma set under it.
8901 cdfs.reduced_tx_set = header.reduced_tx_set;
8902 let start_cdfs = CdfSnapshot(cdfs);
8903 // The luma restoration-unit grid this frame's `lr_params` implies
8904 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
8905 // swallowed by the one before it), for the tile writer's own per-unit
8906 // walk.
8907 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
8908 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
8909 // Every tile is coded from this frame's OWN starting tables and leaves
8910 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
8911 // loop-restoration reference and its neighbour contexts), so the tiles
8912 // are independent of each other and of the order they are written in.
8913 let code_tiles = |bits: u8,
8914 sb_cols: usize,
8915 grid: &[u8],
8916 units: &[Option<crate::restoration::WienerInfo>]|
8917 -> Result<Vec<Vec<u8>>> {
8918 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
8919 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
8920 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
8921 crate::tile::arm_sb128(sb128_on());
8922 let mut cdfs = start_cdfs.0.clone();
8923 crate::tile::arm_screen(screen);
8924 crate::tile::arm_frame_mi_dims(frame_mi_dims);
8925 crate::tile::arm_filter_intra(filter_intra_on());
8926 crate::tile::arm_intrabc(allow_intrabc);
8927 crate::tile::arm_pricing_cdfs(None, false);
8928 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
8929 mi_cols,
8930 mi_rows,
8931 base_q_idx,
8932 &superblocks,
8933 tx_select,
8934 &mut cdfs,
8935 layout.rect(index),
8936 )?;
8937 Ok((bytes, None))
8938 })?;
8939 Ok(out)
8940 };
8941 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
8942 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
8943 // the tile just coded back to the decoder under each candidate (see
8944 // `crate::filter_search`), and keep the filtered picture that wins as
8945 // the reconstruction -- what a decoder outputs, and what the next
8946 // frame predicts from.
8947 pick_and_apply_filters(
8948 &mut header,
8949 &mut luma,
8950 &mut chroma,
8951 [&picture_y8, &picture_u8, &picture_v8],
8952 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
8953 // and loop restoration off and codes none of their parameters
8954 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
8955 // the encoder's reconstruction is already what a decoder produces.
8956 !allow_intrabc,
8957 &mut tiles,
8958 search.lambda,
8959 fctx,
8960 // A key frame codes no 128x128 root block (the writer has no intra
8961 // path at that size), so every unit carries its own literal.
8962 &[],
8963 // Every re-code starts from this frame's OWN starting tables, never
8964 // from where the first write left them: the second tile is the same
8965 // symbol sequence plus new ones, so it must adapt from the same
8966 // point the decoder will.
8967 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
8968 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
8969 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
8970 crate::decode::decode_key_frame_tiles_lr(
8971 &payloads,
8972 &header_tile_info,
8973 h.mi_cols,
8974 h.mi_rows,
8975 base_q_idx,
8976 h.frame_width,
8977 h.frame_height,
8978 seq.enable_filter_intra,
8979 cdef,
8980 lf,
8981 tx_select,
8982 h.reduced_tx_set,
8983 h.allow_screen_content_tools,
8984 h.allow_intrabc,
8985 lr,
8986 fctx,
8987 )
8988 },
8989 )?;
8990 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
8991 header.tile_info.tile_size_bytes = tile_size_bytes;
8992 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
8993 let mut stream = temporal_delimiter();
8994 stream.extend_from_slice(&sequence_header_obu(&seq)?);
8995 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
8996
8997 let [u, v] = chroma;
8998 Ok(Encoded {
8999 stream,
9000 modes,
9001 inter_block_share: 0.0,
9002 reconstruction: Picture {
9003 width: luma.width,
9004 height: luma.height,
9005 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9006 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9007 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
9008 },
9009 tile,
9010 mi_cols: header.mi_cols,
9011 mi_rows: header.mi_rows,
9012 base_q_idx,
9013 tx_select,
9014 // A key frame codes no inter block, so no motion_mode symbol.
9015 switchable_motion_mode: false,
9016 screen,
9017 reduced_tx_set: header.reduced_tx_set,
9018 next_cdfs: start_cdfs.clone(),
9019 start_cdfs,
9020 loop_filter: header.loop_filter,
9021 cdef: header.cdef,
9022 loop_restoration: header.loop_restoration,
9023 allow_intrabc,
9024 delta: header.delta.clone(),
9025 })
9026}
9027
9028/// Chooses this frame's deblocking levels and CDEF strengths, writes them
9029/// into `header` and
9030/// replaces the frame's own region of the encoder's reconstruction with the
9031/// filtered picture the decoder produced under them
9032/// ([`crate::filter_search::pick_deblock`]).
9033///
9034/// `search == false` leaves the header at level 0 (deblocking off) and the
9035/// reconstruction untouched: the caller's stream is one this crate's own
9036/// decoder cannot read back, so there is nothing to search against.
9037///
9038/// # Errors
9039/// The decoder's own error, when it refuses the tile the encoder just wrote
9040/// -- that is an encoder defect, not a filter one, so it is propagated
9041/// rather than swallowed into "no deblocking".
9042fn pick_and_apply_filters(
9043 header: &mut FrameHeader,
9044 luma: &mut Plane<'_>,
9045 chroma: &mut [Plane<'_>; 2],
9046 source: [&[u8]; 3],
9047 search: bool,
9048 // The coded tiles, one payload per tile of the frame's grid, replaced in
9049 // place when the search chooses a per-64x64 `cdef_idx` list
9050 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
9051 // tile is written a second time under `recode` and the winner
9052 // re-decoded from them.
9053 tiles: &mut Vec<Vec<u8>>,
9054 lambda: f64,
9055 fctx: &crate::decode::FrameCtx,
9056 // lane-edge128: `crate::tile::cdef_unit_owner` for the blocks these tiles
9057 // carry -- empty (the identity map) for a frame whose every block covers
9058 // one 64x64 CDEF unit.
9059 cdef_owner: &[u32],
9060 recode: impl Fn(
9061 u8,
9062 usize,
9063 &[u8],
9064 &[Option<crate::restoration::WienerInfo>],
9065 ) -> Result<Vec<Vec<u8>>>,
9066 decode: impl Fn(
9067 &LoopFilterParams,
9068 &CdefParams,
9069 &FrameHeader,
9070 &[Vec<u8>],
9071 &LoopRestorationParams,
9072 ) -> Result<Picture>,
9073) -> Result<()> {
9074 if !search {
9075 return Ok(());
9076 }
9077 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
9078 let hdr = header.clone();
9079 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
9080 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
9081 let damping = 3 + (header.quantization.base_q_idx >> 6);
9082 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
9083 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
9084 let none_lr = LoopRestorationParams::default();
9085 // Every candidate scores the same coded tile: decode it once and re-run
9086 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
9087 // the encoder's profile before this). The per-64x64 error the CDEF
9088 // preset search reads comes off the REPLAYED picture, which is the same
9089 // picture a decode produces -- that is what the replay is pinned on.
9090 crate::decode::clear_filter_replay();
9091 // lane-av1fpar: the per-tile search is over, so every core is idle from
9092 // here to the end of the frame -- band each candidate's deblock/CDEF
9093 // replay, the capture decode's own filter chain and the loop-restoration
9094 // passes across the same workers the search used.
9095 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
9096 let ft = crate::par::timer(crate::par::S_FILTER);
9097 let search_result = crate::filter_search::pick_filters(
9098 |lf, cdef| {
9099 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
9100 return Ok(picture);
9101 }
9102 crate::decode::arm_filter_replay();
9103 let _t = crate::par::timer(crate::par::S_FIRST);
9104 decode(lf, cdef, &hdr, tiles, &none_lr)
9105 },
9106 source,
9107 luma.width,
9108 (fw, fh),
9109 damping,
9110 (sb_cols, sb_rows),
9111 lambda,
9112 cdef_owner,
9113 );
9114 drop(ft);
9115 let (lf, cdef, idx_grid, picture) = search_result?;
9116 header.loop_filter = lf;
9117 header.cdef = cdef;
9118 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
9119 // in the frame header, so a re-decode under candidate parameters cannot
9120 // search them the way deblocking and CDEF are searched above. What the
9121 // decoder hands back instead is its own filter chain's intermediates
9122 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
9123 // those, through the decoder's own Wiener kernel.
9124 //
9125 // The capture rides the decode this stage was already going to do: the
9126 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
9127 // decode of the tile as it stands. That decode's header still says
9128 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
9129 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
9130 // an approximation inside the SEARCH only; the reconstruction this
9131 // function ends up splicing is always a real decode of the real tile.
9132 let lr_on = restoration_enabled();
9133 // The `cdef_idx` literals live in the tile payload, so a frame that
9134 // chose a per-64x64 preset list codes its tiles a second time.
9135 if !idx_grid.is_empty() {
9136 *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
9137 }
9138 // lane-av1cap: that re-coded tile used to be DECODED here as well --
9139 // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop
9140 // restoration search reads (`crate::decode::FrameCtx::capture_stages`)
9141 // and the picture this function splices. Both come out of ONE more
9142 // replay of the winning parameters on the same captured pre-filter
9143 // planes every candidate was scored on: the same two filter kernels, on
9144 // the same input, in the same order, so the same bytes. Re-coding the
9145 // tile does not move the reconstruction the replay holds -- `cdef_idx`
9146 // is an equiprobable literal, so it adapts no CDF and changes no
9147 // residual.
9148 let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx);
9149 #[cfg(test)]
9150 let replay_was_used = replayed.is_some();
9151 let (mut filtered, mut stages) = match replayed {
9152 Some((picture, stages)) => (picture, stages),
9153 // Nothing captured (the shapes [`crate::decode::FilterReplay`]
9154 // refuses): every candidate was a full decode, so the winner's own
9155 // picture stands, and the stages still need a capturing decode.
9156 None => {
9157 fctx.capture_stages.set(lr_on);
9158 let picture = if idx_grid.is_empty() && !lr_on {
9159 picture
9160 } else {
9161 let _t = crate::par::timer(crate::par::S_CAPTURE);
9162 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
9163 };
9164 fctx.capture_stages.set(false);
9165 (picture, crate::decode::take_filter_stages(fctx))
9166 }
9167 };
9168 #[cfg(test)]
9169 if crate::decode::verify_final_replay() && replay_was_used {
9170 fctx.capture_stages.set(lr_on);
9171 let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?;
9172 fctx.capture_stages.set(false);
9173 let want_stages = crate::decode::take_filter_stages(fctx);
9174 assert!(
9175 (want.width, want.height) == (filtered.width, filtered.height)
9176 && want.y == filtered.y
9177 && want.u == filtered.u
9178 && want.v == filtered.v,
9179 "the final filter replay is not the capture decode it stands in for",
9180 );
9181 // Only the frame's own cropped region: the plane is padded to the
9182 // superblock grid and the columns past the mi extent are written by
9183 // nothing (the decoder's plane pool leaves whatever the last frame
9184 // put there), while the restoration search reads strictly inside
9185 // `fw x fh` -- `restoration::lr_sample` clamps its column to
9186 // `plane_w - 1` and its row to the frame's, and
9187 // `filter_search::pick_restoration`'s own SSE walk never leaves the
9188 // crop either.
9189 let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| {
9190 for row in 0..h {
9191 let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]);
9192 assert!(
9193 x == y,
9194 "{what}: the replayed filter stages are not the ones the capture \
9195 decode returns (row {row} of {h}, width {w}, stride {stride})",
9196 );
9197 }
9198 };
9199 match (&want_stages, &stages) {
9200 (Some(a), Some(b)) => {
9201 assert_eq!(a.stride, b.stride, "the captured plane strides moved");
9202 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9203 for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() {
9204 region(&a.deblocked[i], &b.deblocked[i], a.stride[i], w, h, "deblocked");
9205 region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed");
9206 }
9207 }
9208 (None, None) => {}
9209 _ => panic!("one path captured filter stages and the other did not"),
9210 }
9211 }
9212 // lane-av1cap2: the capture stays live past the restoration search --
9213 // `crate::decode::replay_restoration` filters the same post-CDEF plane
9214 // rather than decoding the re-coded tile. Cleared at the end instead.
9215 let mut lr = LoopRestorationParams::default();
9216 if lr_on {
9217 let unit = lr_unit();
9218 let mut want = LoopRestorationParams {
9219 loop_restoration_size: [unit, unit, unit],
9220 uses_lr: true,
9221 // spec `lr_params`: `RESTORATION_TILESIZE_MAX >> (2 - shift)`, so
9222 // 0 is the 64 unit and 1 the 128 one a 128 superblock forces.
9223 lr_unit_shift: u8::from(unit == 128),
9224 ..LoopRestorationParams::default()
9225 };
9226 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
9227 let lrt = crate::par::timer(crate::par::S_LR);
9228 let units = match stages.take() {
9229 Some(stages) => crate::filter_search::pick_restoration(
9230 &stages,
9231 source[0],
9232 luma.width,
9233 (fw, fh),
9234 &want,
9235 lambda,
9236 fctx,
9237 ),
9238 None => Vec::new(),
9239 };
9240 // A frame no unit restores keeps `RESTORE_NONE` on every plane
9241 // rather than paying ~1 bit per 64x64 for a tile full of
9242 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
9243 // clip whose units never take a filter).
9244 drop(lrt);
9245 if units.iter().any(Option::is_some) {
9246 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
9247 let _t = crate::par::timer(crate::par::S_CAPTURE);
9248 // lane-av1cap2: that re-coded tile used to be DECODED here to
9249 // reach the restored reference frame -- 5.6% of a 4K frame,
9250 // for a filter that reads nothing of the tile but the per-unit
9251 // Wiener filters this stage just chose. Run the decoder's own
9252 // restoration kernel on the replay's post-CDEF plane instead
9253 // (`crate::decode::replay_restoration`), with the real
9254 // post-deblock stripe borders.
9255 match crate::decode::replay_restoration(&want, &units, fctx) {
9256 Some(y) => {
9257 #[cfg(test)]
9258 let margin = fctx
9259 .last_frame_wide_margin
9260 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()));
9261 #[cfg(test)]
9262 if crate::decode::verify_final_replay() {
9263 let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?;
9264 assert!(
9265 (want_pic.width, want_pic.height) == (filtered.width, filtered.height)
9266 && want_pic.u == filtered.u
9267 && want_pic.v == filtered.v,
9268 "the restoration replay moved a chroma plane or the picture size",
9269 );
9270 assert!(
9271 want_pic.y == y,
9272 "the restoration replay is not the decode of the re-coded tile",
9273 );
9274 assert!(
9275 fctx.last_frame_wide_margin
9276 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()))
9277 == margin,
9278 "the restoration replay's wide-margin luma is not the decode's",
9279 );
9280 }
9281 filtered.y = y;
9282 }
9283 // Nothing captured: the winner came out of a full decode,
9284 // so this one does too.
9285 None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?,
9286 }
9287 *tiles = coded;
9288 lr = want;
9289 }
9290 }
9291 crate::decode::clear_filter_replay();
9292 header.loop_restoration = lr;
9293 let dec_cw = filtered.width.div_ceil(2);
9294 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9295 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
9296 crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
9297 crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
9298 Ok(())
9299}
9300
9301/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
9302/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
9303/// since every block this crate's inter tile writer codes is 32x32.
9304const SIZE_GROUP_32: usize = 3;
9305
9306/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
9307/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
9308/// stack this encoder builds is ever asked to predict against.
9309const LAST_FRAME: i8 = 1;
9310
9311/// What an inter frame's intra branch spends to name each of the thirteen
9312/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
9313/// context, since an inter frame's intra blocks do not read their
9314/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
9315/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
9316/// state, so it is built once per frame.
9317fn inter_mode_bits() -> [f64; 13] {
9318 std::array::from_fn(|mode| {
9319 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
9320 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
9321 } else {
9322 0.0
9323 };
9324 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
9325 + angle
9326 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
9327 })
9328}
9329
9330/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
9331/// [`mc::predict`] takes, in the units of the plane it predicts into.
9332///
9333/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
9334/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
9335/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
9336/// domain. `luma` picks which.
9337fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
9338 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
9339}
9340
9341/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
9342/// that module): the magnitude an `MV_CLASS_n` component's own bits start
9343/// counting from.
9344fn mv_class_base(class: usize) -> i32 {
9345 if class == 0 { 0 } else { 2i32 << (class + 2) }
9346}
9347
9348/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
9349/// `tile::mv_class_of`.
9350fn mv_class_of(z: i32) -> usize {
9351 let mut class = 0;
9352 while class < 10 && mv_class_base(class + 1) <= z {
9353 class += 1;
9354 }
9355 class
9356}
9357
9358/// What [`crate::tile::write_mv_component`] (private to that module) would
9359/// spend coding one non-zero motion vector component, against the same
9360/// static default CDFs the writer starts a frame from — the same
9361/// static-table approximation [`mode_bits`] costs the luma mode symbol
9362/// through, not the tile writer's own adapting state, which this encoder has
9363/// no way to read without duplicating it block for block.
9364///
9365/// Returns `None` when `diff` needs eighth-pel precision in a frame coded
9366/// without `allow_high_precision_mv`, which is what [`round_to_valid_mv`]
9367/// exists to avoid ever happening.
9368fn mv_component_bits(diff: i32) -> Option<f64> {
9369 let hp_frame = crate::tile::high_precision_mv();
9370 let mag = diff.unsigned_abs() as i32;
9371 let z = mag - 1;
9372 if !hp_frame && z & 1 == 0 {
9373 return None;
9374 }
9375 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
9376 let class = mv_class_of(z);
9377 bits += symbol_bits(&cdf::MV_CLASS, class);
9378 let local = z - mv_class_base(class);
9379 let hp = (local & 1) as usize;
9380 if class == 0 {
9381 let bit = (local >> 3) & 1;
9382 let fr = (local >> 1) & 3;
9383 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
9384 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
9385 // lane-hpmv: the writer codes the eighth-pel bit in a high-precision
9386 // frame, so the pricer charges for it there and only there.
9387 if hp_frame {
9388 bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
9389 }
9390 } else {
9391 let d = local >> 3;
9392 let fr = (local >> 1) & 3;
9393 for i in 0..class {
9394 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
9395 }
9396 bits += symbol_bits(&cdf::MV_FR, fr as usize);
9397 if hp_frame {
9398 bits += symbol_bits(&cdf::MV_HP, hp);
9399 }
9400 }
9401 Some(bits)
9402}
9403
9404/// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the
9405/// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch,
9406/// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's
9407/// value without the second motion search's wall.
9408fn last2_new_mv() -> bool {
9409 match std::env::var("EC_AV1_LAST2_NEW").ok() {
9410 Some(v) => v != "0",
9411 None => true,
9412 }
9413}
9414
9415/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
9416/// own -- a second motion search per block against that reference's picture,
9417/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
9418/// off in a test build (what the lane measured both arms with).
9419fn extra_ref_new_mv() -> bool {
9420 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
9421 Some(v) if cfg!(test) => v != "0",
9422 _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW),
9423 }
9424}
9425
9426/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
9427/// flat slot plan (`inter_frame_headers_slots`): every reference but
9428/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
9429/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
9430/// frame two back when there is one (otherwise it, too, names the key frame's
9431/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
9432pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
9433 let last = order_hint.wrapping_sub(1) & 0x7f;
9434 let alt = if has_altref {
9435 order_hint.wrapping_sub(2) & 0x7f
9436 } else {
9437 key_hint
9438 };
9439 [last, last, last, key_hint, last, last, alt]
9440}
9441
9442/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
9443/// header bit that lets each block choose between a single and a compound
9444/// reference. Off by default until compound prediction is measured to pay;
9445/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
9446/// runs as), and every block still codes SINGLE, so the only cost is one
9447/// `comp_mode` symbol per inter block.
9448pub(crate) const REFERENCE_SELECT: bool = true;
9449
9450/// [`REFERENCE_SELECT`], with the test-build environment override.
9451pub(crate) fn reference_select() -> bool {
9452 match std::env::var("EC_AV1_COMPOUND").ok() {
9453 Some(v) if cfg!(test) => v != "0",
9454 _ => crate::speed::at(&crate::speed::COMPOUND),
9455 }
9456}
9457
9458/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
9459/// per entry past `start`, `1` to advance and `0` to stop, at most two.
9460fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
9461 let mut bits = 0.0;
9462 let mut idx = start;
9463 while idx < start + 2 && stack.entries.len() > idx + 1 {
9464 let advance = idx < target;
9465 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
9466 if !advance {
9467 break;
9468 }
9469 idx += 1;
9470 }
9471 bits
9472}
9473
9474/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
9475/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
9476/// `assign_mv`), so the same vector costs a different residual from each.
9477fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
9478 let mut best: Option<(f64, u8)> = None;
9479 for idx in 0..3usize {
9480 if idx > 0 && stack.entries.len() <= idx {
9481 break;
9482 }
9483 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
9484 if let Some(b) = mv_residual_bits(mv, base) {
9485 let total = b + drl_bits_for(stack, 0, idx);
9486 if best.is_none_or(|(t, _)| total < t) {
9487 best = Some((total, idx as u8));
9488 }
9489 }
9490 }
9491 best
9492}
9493
9494/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
9495/// zero vector and the stack's own candidates. A neighbour block's vector is
9496/// where this block's motion most often already is, which is what pays for
9497/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
9498/// vs libaom for 0.2 s off a 6 s ladder).
9499fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
9500 let mut seeds = [(0, 0); 4];
9501 let mut n = 1;
9502 for e in stack.entries.iter().take(3) {
9503 seeds[n] = e.mv;
9504 n += 1;
9505 }
9506 (seeds, n)
9507}
9508
9509/// What [`crate::tile::write_mv`] (private to that module) would spend
9510/// coding `mv` as a residual against `pred`: the joint symbol naming which
9511/// components differ, then each differing component. `None` under the same
9512/// condition [`mv_component_bits`] returns `None`.
9513/// How many frames back `ref_frame` sits from the frame being coded, off the
9514/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
9515/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
9516/// what [`crate::motion::search`] scales its starting step by.
9517fn ref_distance(ref_frame: i8) -> u32 {
9518 let (bits, order_hint, hints) = crate::tile::order_hints();
9519 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
9520 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
9521 .unsigned_abs()
9522 .max(1);
9523 if crate::envflags::env_flag!("EC_TRACE_DIST") {
9524 eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]);
9525 }
9526 d
9527}
9528
9529fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
9530 let diff = (mv.0 - pred.0, mv.1 - pred.1);
9531 let joint = match (diff.0 != 0, diff.1 != 0) {
9532 (false, false) => 0,
9533 (false, true) => 1,
9534 (true, false) => 2,
9535 (true, true) => 3,
9536 };
9537 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
9538 for d in [diff.0, diff.1] {
9539 if d != 0 {
9540 bits += mv_component_bits(d)?;
9541 }
9542 }
9543 Some(bits)
9544}
9545
9546/// Rounds `mv` so that its residual against `pred` is one
9547/// [`crate::tile::write_mv_component`] can actually code: each component's
9548/// difference is either zero or has an even magnitude (the eighth-pel bit
9549/// `allow_high_precision_mv` off always infers as one forces the coded
9550/// magnitude odd one step further in, which comes out even here since this
9551/// crate's motion search works in whole units of that same step). Rounding
9552/// down keeps every coded MV — and so every `nearest_mv` a later block's
9553/// stack votes with — built from an even displacement from `(0, 0)`, so the
9554/// invariant holds without this function seeing the whole stack.
9555/// A PROCESS-GLOBAL [`high_precision_mv_at`] override that wins over both
9556/// the threshold and the environment (`u8::MAX` = unset, `0` = never, `1` =
9557/// always), the shape [`set_frame_interp`] has: the witness that has to see
9558/// `mv_hp` symbols coded turns it on through this while holding
9559/// [`crate::speed::knob_write`].
9560static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
9561
9562/// Sets [`HP_MV_OVERRIDE`]; `None` clears it.
9563#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
9564pub(crate) fn set_high_precision_mv(on: Option<bool>) {
9565 HP_MV_OVERRIDE.store(on.map_or(u8::MAX, u8::from), std::sync::atomic::Ordering::Relaxed);
9566}
9567
9568/// The qindex below which an inter frame codes `allow_high_precision_mv`
9569/// (lane-hpmv). libaom's `HIGH_PRECISION_MV_QTHRESH` is 128; `0` is this
9570/// crate's shipped value, i.e. high-precision motion vectors off in every
9571/// frame -- see `lanes/hpmv.report.md` for the sweep that chose it.
9572pub(crate) const HP_MV_QTHRESH: u8 = 0;
9573
9574/// Whether an inter frame at `base_q_idx` carries `allow_high_precision_mv`:
9575/// [`HP_MV_QTHRESH`], overridable by `EC_AV1_HP_MV` (`0`/`off` never, `all`
9576/// always, any number as the threshold) so the BD gate can sweep the policy
9577/// without a rebuild.
9578pub(crate) fn high_precision_mv_at(base_q_idx: u8) -> bool {
9579 match HP_MV_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
9580 0 => return false,
9581 1 => return true,
9582 _ => {}
9583 }
9584 static T: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
9585 let threshold = *T.get_or_init(|| match std::env::var("EC_AV1_HP_MV").ok().as_deref() {
9586 Some("all" | "always") => 256,
9587 Some("0" | "off") => 0,
9588 Some(v) => v.parse().unwrap_or(u16::from(HP_MV_QTHRESH)),
9589 None => u16::from(HP_MV_QTHRESH),
9590 });
9591 u16::from(base_q_idx) < threshold
9592}
9593
9594fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
9595 // lane-hpmv: with `allow_high_precision_mv` on, every eighth-pel
9596 // residual is codable and there is nothing to round away.
9597 if crate::tile::high_precision_mv() {
9598 return mv;
9599 }
9600 let round = |m: i32, p: i32| {
9601 let diff = m - p;
9602 let mag = diff.unsigned_abs() as i32;
9603 let even = mag - mag % 2;
9604 if even == 0 {
9605 p
9606 } else {
9607 p + even * diff.signum()
9608 }
9609 };
9610 (round(mv.0, pred.0), round(mv.1, pred.1))
9611}
9612
9613/// Predicts one `side`-square block by motion compensation from `reference`
9614/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
9615#[allow(clippy::too_many_arguments)]
9616fn mc_trial(
9617 plane: &Plane,
9618 x: usize,
9619 y: usize,
9620 side: usize,
9621 mv: (i32, i32),
9622 luma: bool,
9623 reference: &[u16],
9624 stride: usize,
9625 ref_width: usize,
9626 ref_height: usize,
9627 skip: bool,
9628 base_q_idx: u8,
9629 deadzone: f64,
9630 set: TxbSet,
9631 fctx: &crate::decode::FrameCtx,
9632) -> Trial {
9633 mc_trial_typed(
9634 plane, x, y, side, mv, luma, reference, stride, ref_width, ref_height, skip, base_q_idx,
9635 deadzone, set, TxType::DctDct, fctx,
9636 )
9637}
9638
9639/// [`mc_trial`] coding its residual with a named transform type (lane-txset2).
9640#[allow(clippy::too_many_arguments)]
9641fn mc_trial_typed(
9642 plane: &Plane,
9643 x: usize,
9644 y: usize,
9645 side: usize,
9646 mv: (i32, i32),
9647 luma: bool,
9648 reference: &[u16],
9649 stride: usize,
9650 ref_width: usize,
9651 ref_height: usize,
9652 skip: bool,
9653 base_q_idx: u8,
9654 deadzone: f64,
9655 set: TxbSet,
9656 tx_type: TxType,
9657 fctx: &crate::decode::FrameCtx,
9658) -> Trial {
9659 let x_q4 = mv_to_q4(x, mv.1, luma);
9660 let y_q4 = mv_to_q4(y, mv.0, luma);
9661 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
9662 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
9663 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
9664 // lane-av1speed: both buffers are per-candidate scratch on the hottest
9665 // path in the encoder, so they live on the stack -- `side` is at most
9666 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
9667 // per motion-compensated trial otherwise.
9668 let mut prediction16 = [0u16; BLOCK * BLOCK];
9669 let prediction16 = &mut prediction16[..side * side];
9670 mc::predict(
9671 reference,
9672 stride,
9673 ref_width,
9674 ref_height,
9675 x_q4,
9676 y_q4,
9677 side,
9678 side,
9679 prediction16, fctx,
9680 );
9681 let mut prediction = [0u8; BLOCK * BLOCK];
9682 let prediction = &mut prediction[..side * side];
9683 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
9684 *dst = src as u8;
9685 }
9686 plane.code_from_prediction_typed(
9687 x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type,
9688 )
9689}
9690
9691/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
9692/// references predict into the `CONV_BUF` intermediate domain
9693/// ([`mc::predict_compound_intermediate`]) and are blended by
9694/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
9695/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
9696/// block, so the encoder's reconstruction is the decoder's.
9697#[allow(clippy::too_many_arguments)]
9698fn mc_trial_compound(
9699 plane: &Plane,
9700 x: usize,
9701 y: usize,
9702 side: usize,
9703 mvs: ((i32, i32), (i32, i32)),
9704 luma: bool,
9705 ref0: (&[u16], usize, usize, usize),
9706 ref1: (&[u16], usize, usize, usize),
9707 base_q_idx: u8,
9708 deadzone: f64,
9709 set: TxbSet,
9710 fctx: &crate::decode::FrameCtx,
9711) -> Trial {
9712 mc_trial_compound_typed(
9713 plane, x, y, side, mvs, luma, ref0, ref1, base_q_idx, deadzone, set, TxType::DctDct, fctx,
9714 )
9715}
9716
9717/// [`mc_trial_compound`] coding its residual with a named transform type
9718/// (lane-txset2).
9719#[allow(clippy::too_many_arguments)]
9720fn mc_trial_compound_typed(
9721 plane: &Plane,
9722 x: usize,
9723 y: usize,
9724 side: usize,
9725 (mv0, mv1): ((i32, i32), (i32, i32)),
9726 luma: bool,
9727 ref0: (&[u16], usize, usize, usize),
9728 ref1: (&[u16], usize, usize, usize),
9729 base_q_idx: u8,
9730 deadzone: f64,
9731 set: TxbSet,
9732 tx_type: TxType,
9733 fctx: &crate::decode::FrameCtx,
9734) -> Trial {
9735 let mut inter0 = [0i32; BLOCK * BLOCK];
9736 let mut inter1 = [0i32; BLOCK * BLOCK];
9737 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
9738 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
9739 mc::predict_compound_intermediate(
9740 r.0,
9741 r.1,
9742 r.2,
9743 r.3,
9744 mv_to_q4(x, mv.1, luma),
9745 mv_to_q4(y, mv.0, luma),
9746 mc::REF_NO_SCALE,
9747 side,
9748 side,
9749 fctx.interp_filter.get(),
9750 fctx.interp_filter.get(),
9751 dst, fctx,
9752 );
9753 }
9754 let mut blended16 = [0u16; BLOCK * BLOCK];
9755 let blended16 = &mut blended16[..side * side];
9756 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
9757 let mut prediction = [0u8; BLOCK * BLOCK];
9758 let prediction = &mut prediction[..side * side];
9759 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
9760 *dst = src as u8;
9761 }
9762 plane.code_from_prediction_typed(
9763 x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type,
9764 )
9765}
9766
9767/// Codes one 32x32 block of an inter frame as whichever costs least of: each
9768/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
9769/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
9770/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
9771/// coding a real residual (`skip: false`) whenever one prices out cheaper
9772/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
9773/// missing inter `tx_type` symbol (the desync this function's candidates
9774/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
9775/// fixed.
9776///
9777/// The symbol costs this ranks candidates by use fixed contexts (0) for
9778/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
9779/// contexts for those come from its own neighbour bookkeeping
9780/// (`tile::Neighbours`), which is private to that module and not worth
9781/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
9782/// `drl_mode` contexts come straight from `stack`, which is exact, because
9783/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
9784/// the tile writer derives from the same grid state.
9785#[allow(clippy::too_many_arguments)]
9786/// One prediction of `side` x `side` samples from `reference`, as `u8` --
9787/// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is
9788/// four times the stack scratch that function sizes for [`BLOCK`].
9789fn predict_u8(
9790 reference: &[u16],
9791 stride: usize,
9792 ref_width: usize,
9793 ref_height: usize,
9794 (x, y): (usize, usize),
9795 side: usize,
9796 mv: (i32, i32),
9797 luma: bool,
9798 fctx: &crate::decode::FrameCtx,
9799) -> Vec<u8> {
9800 let mut prediction = vec![0u16; side * side];
9801 mc::predict(
9802 reference,
9803 stride,
9804 ref_width,
9805 ref_height,
9806 mv_to_q4(x, mv.1, luma),
9807 mv_to_q4(y, mv.0, luma),
9808 side,
9809 side,
9810 &mut prediction,
9811 fctx,
9812 );
9813 prediction.iter().map(|&v| v as u8).collect()
9814}
9815
9816/// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's
9817/// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both
9818/// references predict into the `CONV_BUF` intermediate domain and are blended
9819/// at the simple-average split `(8, 8)`, the same path (and so the same
9820/// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes.
9821fn predict_compound_u8(
9822 ref0: (&[u16], usize, usize, usize),
9823 ref1: (&[u16], usize, usize, usize),
9824 (x, y): (usize, usize),
9825 side: usize,
9826 (mv0, mv1): ((i32, i32), (i32, i32)),
9827 luma: bool,
9828 fctx: &crate::decode::FrameCtx,
9829) -> Vec<u8> {
9830 let mut inter = [vec![0i32; side * side], vec![0i32; side * side]];
9831 for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) {
9832 mc::predict_compound_intermediate(
9833 r.0,
9834 r.1,
9835 r.2,
9836 r.3,
9837 mv_to_q4(x, mv.1, luma),
9838 mv_to_q4(y, mv.0, luma),
9839 mc::REF_NO_SCALE,
9840 side,
9841 side,
9842 fctx.interp_filter.get(),
9843 fctx.interp_filter.get(),
9844 dst, fctx,
9845 );
9846 }
9847 let mut blended = vec![0u16; side * side];
9848 mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx);
9849 blended.iter().map(|&v| v as u8).collect()
9850}
9851
9852/// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128
9853/// superblock root, the lever cen3's L1 asks for -- one block, one mode and
9854/// one motion vector where the four 64x64 roots below spend four of each.
9855///
9856/// SKIP only (`residual: false`): a 128x128 block's residual is four
9857/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
9858/// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a
9859/// path for -- offering one here would price a block
9860/// [`crate::tile::write_inter_block_128`] refuses. Single reference only for
9861/// the same reason: the compound arm at this size is untested against the
9862/// writer's own `write_compound_block` window.
9863///
9864/// Only a root whose whole 128x128 lies inside the true frame AND inside
9865/// this tile is offered: the writer's own root codes `PARTITION_NONE` only
9866/// where the spec's `has_rows`/`has_cols` are both set, and a straddling
9867/// block would have to be ranked over its inside part alone.
9868///
9869/// Returns `(cost, lambda, block, reconstruction)` -- the cost already
9870/// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it
9871/// against the four superblocks plus the SPLIT symbol.
9872#[allow(clippy::too_many_arguments)]
9873fn search_root_128(
9874 luma: &mut Plane,
9875 chroma: &mut [Plane; 2],
9876 grid: &crate::mvstack::MiGrid,
9877 (root_r, root_c): (usize, usize),
9878 // The 32x32-block grid this tile's `blocks` vector is indexed on.
9879 (rows, cols): (usize, usize),
9880 // The frame's own mode-info grid, which bounds the root.
9881 (mi_cols, mi_rows): (u32, u32),
9882 search: Search<'_>,
9883 tpl_factors: &Option<Vec<f64>>,
9884 sb_q: Option<&Vec<u8>>,
9885 sb_cols: usize,
9886 tpl_cells_x: usize,
9887 base_q_idx: u8,
9888 // lane-rectdq: `1 << delta_q_res` when this frame codes a delta_q plan,
9889 // zero when it does not -- what [`delta_q_bits_at_root`] prices with.
9890 dq_res: i32,
9891 reference: &Picture,
9892 // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window,
9893 // built by the caller off the same grid the tile writer rebuilds its
9894 // stack from (empty unless the frame carries `reference_select` and
9895 // [`b128_compound`] is on).
9896 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
9897 fctx: &crate::decode::FrameCtx,
9898) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {
9899 const SIDE: usize = SUPERBLOCK * 2;
9900 const SIDE_MI: usize = SIDE / 4;
9901 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
9902 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
9903 if root_r * 2 + 3 >= rows
9904 || root_c * 2 + 3 >= cols
9905 || (mi_row + SIDE_MI) as u32 > mi_rows
9906 || (mi_col + SIDE_MI) as u32 > mi_cols
9907 || x128 + SIDE > luma.true_width
9908 || y128 + SIDE > luma.true_height
9909 {
9910 return None;
9911 }
9912 // One lambda for the whole root, the mean of what its four superblocks
9913 // would each be searched at -- the 128-vs-four comparison weighs one cost
9914 // against four, so both sides have to be priced at the same lambda (the
9915 // same rule the 64 root's own mean-of-sixteen tpl cells follows).
9916 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
9917 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
9918 (None, Some(f)) => {
9919 let mean = (0..16)
9920 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
9921 .sum::<f64>()
9922 / 16.0;
9923 search.lambda * mean
9924 }
9925 (None, None) => search.lambda,
9926 };
9927 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
9928 .iter()
9929 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
9930 .sum::<f64>()
9931 / 4.0;
9932 // The qindex this root is really quantized at: the delta_q unit is the
9933 // 128 superblock, so the root's own top-left cell is the one coded
9934 // (lane-b128m), and the residual arm below has to quantize at exactly it.
9935 let root_search = Search {
9936 lambda,
9937 ..match sb_q {
9938 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
9939 None => search,
9940 }
9941 };
9942 let stack = find_mv_stack(
9943 grid,
9944 mi_row,
9945 mi_col,
9946 SIDE_MI,
9947 SIDE_MI,
9948 LAST_FRAME,
9949 mi_cols as usize,
9950 mi_rows as usize,
9951 );
9952 let base = snapshot(luma, chroma, (x128, y128), SIDE);
9953 let found = search_skip_64(
9954 luma,
9955 chroma,
9956 (x128, y128),
9957 (SIDE, SIDE),
9958 &root_search,
9959 false,
9960 reference,
9961 &stack,
9962 compound,
9963 fctx,
9964 );
9965 let (mut cost, mut block) = found?;
9966 if block.inter.is_some_and(|i| i.ref1.is_some()) {
9967 B128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9968 }
9969 // lane-b128r: the same prediction with a REAL residual, priced against
9970 // the skip arm the search just committed to the planes (which IS the
9971 // winner's prediction, sample for sample). The block's residual is four
9972 // TX_64X64 luma units, one per 64x64 mu chunk, each interleaved with its
9973 // own TX_32X32 chroma pair -- so it is coded here as twelve trials at
9974 // sides the forward network already reaches, never as one 128-point
9975 // transform. Var-tx depth 0 only: the four units ARE the tree's leaves.
9976 //
9977 // The four `txfm_partition` symbols the writer codes for them are not
9978 // priced, exactly as the 64 root does not price its own (their contexts
9979 // are only known at write time); at four symbols a root this is under a
9980 // bit against residuals of hundreds.
9981 if b128_residual() && block.skip {
9982 // Every unit's coded level grid is 32x32 (a 64-point transform codes
9983 // only its top-left corner), packed per plane into one 64-wide grid
9984 // with chunk (cr, cc) at (cr * 32, cc * 32) -- the layout
9985 // `write_inter_block_128` slices back out in the same chunk order.
9986 let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
9987 let mut chunks: Vec<((usize, usize), [Trial; 3])> = Vec::new();
9988 let (mut sse_skip, mut sse_res, mut coeff_bits) = (0.0f64, 0.0f64, 0.0f64);
9989 for (cr, cc) in [(0usize, 0usize), (0, 1), (1, 0), (1, 1)] {
9990 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
9991 let (cx, cy) = (px / 2, py / 2);
9992 let half = SUPERBLOCK / 2;
9993 let pred_y = rows_of(&luma.reconstruction, luma.width, px, py, SUPERBLOCK);
9994 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
9995 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
9996 sse_skip += luma.block_sse(px, py, SUPERBLOCK, &pred_y)
9997 + chroma[0].block_sse(cx, cy, half, &pred_u)
9998 + chroma[1].block_sse(cx, cy, half, &pred_v);
9999 let trials = [
10000 luma.code_from_prediction(
10001 px, py, SUPERBLOCK, &pred_y, false, root_search.base_q_idx,
10002 root_search.deadzone, TxbSet::Luma64,
10003 ),
10004 chroma[0].code_from_prediction(
10005 cx, cy, half, &pred_u, false, root_search.base_q_idx,
10006 root_search.deadzone, TxbSet::Chroma32,
10007 ),
10008 chroma[1].code_from_prediction(
10009 cx, cy, half, &pred_v, false, root_search.base_q_idx,
10010 root_search.deadzone, TxbSet::Chroma32,
10011 ),
10012 ];
10013 for (plane, trial) in trials.iter().enumerate() {
10014 sse_res += trial.sse;
10015 coeff_bits += trial.bits;
10016 for row in 0..32 {
10017 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10018 .copy_from_slice(&trial.levels[row * 32..][..32]);
10019 }
10020 }
10021 chunks.push(((cr, cc), trials));
10022 }
10023 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual
10024 // arm pays the same syntax with `skip` coded 0 instead of 1, plus its
10025 // coefficients.
10026 let unskip = skip_bits_at(&stack, false) - skip_bits_at(&stack, true);
10027 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10028 if res_cost < cost || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed) {
10029 B128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10030 for ((cr, cc), trials) in &chunks {
10031 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
10032 let half = SUPERBLOCK / 2;
10033 luma.commit(px, py, SUPERBLOCK, &trials[0]);
10034 chroma[0].commit(px / 2, py / 2, half, &trials[1]);
10035 chroma[1].commit(px / 2, py / 2, half, &trials[2]);
10036 }
10037 cost = res_cost;
10038 block.skip = false;
10039 block.tx_depth = 0;
10040 block.luma_tx_types = Vec::new();
10041 block.luma = coeffs(&packed[0], 64);
10042 block.u = coeffs(&packed[1], 64);
10043 block.v = coeffs(&packed[2], 64);
10044 }
10045 }
10046 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10047 restore(luma, chroma, (x128, y128), SIDE, &base);
10048 // lane-rectdq: a SKIPPED whole-superblock root is the one shape that
10049 // codes no delta_q group (`write_delta_q`'s `is_whole_sb && skip`); the
10050 // residual arm above codes it like every other block does.
10051 let dq = if block.skip {
10052 0.0
10053 } else {
10054 delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c))
10055 };
10056 Some((
10057 cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq),
10058 lambda,
10059 block,
10060 after,
10061 ))
10062}
10063
10064/// lane-rectres: one rect/AB piece's REAL residual, priced against the skip
10065/// arm the caller's [`search_skip_64`] just committed to the planes (which
10066/// IS the winner's prediction, sample for sample -- the same rule
10067/// [`search_root_128`]'s residual arm runs at the NONE root). The piece's
10068/// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
10069/// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square),
10070/// each trial at sides the forward network already reaches, never a
10071/// rectangular transform; var-tx depth 0 only -- the units ARE the tree's
10072/// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads.
10073///
10074/// The depth-0 `txfm_partition` symbols the writer codes for the units are
10075/// not priced, exactly as [`search_root_128`] does not price its four (their
10076/// contexts are only known at write time); at two symbols a half this is
10077/// under a bit against residuals of hundreds. On a win (or under the witness
10078/// force) the trials are committed to the planes, `block` is flipped to
10079/// carry the packed level grids [`crate::tile::write_inter_block_128_rect`]
10080/// slices back out, and the new cost is returned; otherwise `cost` passes
10081/// through untouched. Counts [`take_b128_rectres_hits`] on a win.
10082#[allow(clippy::too_many_arguments)]
10083fn search_rect_residual(
10084 luma: &mut Plane,
10085 chroma: &mut [Plane; 2],
10086 // The piece's own top-left, in luma samples.
10087 (px, py): (usize, usize),
10088 // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square.
10089 (w, h): (usize, usize),
10090 cost: f64,
10091 lambda: f64,
10092 search: &Search<'_>,
10093 // The piece's own mv stack, for the skip symbol's cost either way.
10094 stack: &crate::mvstack::MvStack,
10095 block: &mut BlockCoeffs,
10096) -> f64 {
10097 /// The 64x64 "mu" chunk side, luma; chroma halves it.
10098 const MU: usize = SUPERBLOCK;
10099 let chunks: [(usize, usize); 2] = match (w, h) {
10100 (128, 64) => [(0, 0), (0, 1)],
10101 (64, 128) => [(0, 0), (1, 0)],
10102 _ => [(0, 0), (0, 0)],
10103 };
10104 let n = if w.max(h) > MU { 2 } else { 1 };
10105 // Every unit's coded level grid is 32x32 (a 64-point transform codes
10106 // only its top-left corner), packed per plane into one 64-wide grid with
10107 // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices
10108 // back out in the same chunk order.
10109 let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
10110 let mut sse_skip = 0.0f64;
10111 let mut sse_res = 0.0f64;
10112 let mut coeff_bits = 0.0f64;
10113 let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n);
10114 for &(cr, cc) in &chunks[..n] {
10115 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10116 let (cx, cy) = (cxx / 2, cyy / 2);
10117 let half = MU / 2;
10118 let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU);
10119 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
10120 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
10121 sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y)
10122 + chroma[0].block_sse(cx, cy, half, &pred_u)
10123 + chroma[1].block_sse(cx, cy, half, &pred_v);
10124 let trials = [
10125 luma.code_from_prediction(
10126 cxx, cyy, MU, &pred_y, false, search.base_q_idx, search.deadzone,
10127 TxbSet::Luma64,
10128 ),
10129 chroma[0].code_from_prediction(
10130 cx, cy, half, &pred_u, false, search.base_q_idx, search.deadzone,
10131 TxbSet::Chroma32,
10132 ),
10133 chroma[1].code_from_prediction(
10134 cx, cy, half, &pred_v, false, search.base_q_idx, search.deadzone,
10135 TxbSet::Chroma32,
10136 ),
10137 ];
10138 for (plane, trial) in trials.iter().enumerate() {
10139 sse_res += trial.sse;
10140 coeff_bits += trial.bits;
10141 for row in 0..32 {
10142 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10143 .copy_from_slice(&trial.levels[row * 32..][..32]);
10144 }
10145 }
10146 trials_per_chunk.push(trials);
10147 }
10148 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm
10149 // pays the same syntax with `skip` coded 0 instead of 1, plus its
10150 // coefficients.
10151 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10152 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10153 if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) {
10154 for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) {
10155 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10156 let (cx, cy) = (cxx / 2, cyy / 2);
10157 let half = MU / 2;
10158 luma.commit(cxx, cyy, MU, &trials[0]);
10159 chroma[0].commit(cx, cy, half, &trials[1]);
10160 chroma[1].commit(cx, cy, half, &trials[2]);
10161 }
10162 block.skip = false;
10163 block.tx_depth = 0;
10164 block.luma_tx_types = Vec::new();
10165 block.luma = coeffs(&packed[0], 64);
10166 block.u = coeffs(&packed[1], 64);
10167 block.v = coeffs(&packed[2], 64);
10168 B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10169 res_cost
10170 } else {
10171 cost
10172 }
10173}
10174
10175/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
10176/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
10177/// shipped NONE machinery halved. Skip-only by default, single reference or
10178/// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual
10179/// ([`search_rect_residual`]) -- exactly what
10180/// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block`
10181/// reads at `sb128_rect`.
10182///
10183/// The FIRST half is published into `grid` before the second is searched --
10184/// the writer publishes it too, so a second half searched against the stale
10185/// grid would be priced (and its mv predicted) off a stack the decoder never
10186/// derives (class `encoder-grid-drift-invisible-to-pixel-gate`). The grid and
10187/// both planes are put back before returning; the caller re-applies the
10188/// winner.
10189///
10190/// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already
10191/// carrying the root's own partition symbol so it ranks against
10192/// [`search_root_128`] and against the four superblocks below.
10193#[allow(clippy::too_many_arguments)]
10194fn search_root_128_rect(
10195 luma: &mut Plane,
10196 chroma: &mut [Plane; 2],
10197 grid: &mut crate::mvstack::MiGrid,
10198 (root_r, root_c): (usize, usize),
10199 (rows, cols): (usize, usize),
10200 (mi_cols, mi_rows): (u32, u32),
10201 search: Search<'_>,
10202 tpl_factors: &Option<Vec<f64>>,
10203 sb_q: Option<&Vec<u8>>,
10204 sb_cols: usize,
10205 tpl_cells_x: usize,
10206 base_q_idx: u8,
10207 // lane-rectdq: see [`search_root_128`]'s own `dq_res`.
10208 dq_res: i32,
10209 reference: &Picture,
10210 // The `LAST` + extra-reference pairs offered at this root; only the
10211 // reference and its picture are read here, since each HALF derives its
10212 // own compound stack at its own rectangular window.
10213 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10214 horz: bool,
10215 fctx: &crate::decode::FrameCtx,
10216) -> Option<(f64, f64, [BlockCoeffs; 2], [(Vec<u8>, Vec<CoefCtx>); 3])> {
10217 const SIDE: usize = SUPERBLOCK * 2;
10218 const SIDE_MI: usize = SIDE / 4;
10219 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10220 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10221 if root_r * 2 + 3 >= rows
10222 || root_c * 2 + 3 >= cols
10223 || (mi_row + SIDE_MI) as u32 > mi_rows
10224 || (mi_col + SIDE_MI) as u32 > mi_cols
10225 || x128 + SIDE > luma.true_width
10226 || y128 + SIDE > luma.true_height
10227 {
10228 return None;
10229 }
10230 // The root's own lambda, the mean of its four superblocks' -- the same
10231 // one [`search_root_128`] prices with, so the three root candidates and
10232 // the four-superblock arm are all comparable.
10233 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10234 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10235 (None, Some(f)) => {
10236 let mean = (0..16)
10237 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10238 .sum::<f64>()
10239 / 16.0;
10240 search.lambda * mean
10241 }
10242 (None, None) => search.lambda,
10243 };
10244 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10245 .iter()
10246 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10247 .sum::<f64>()
10248 / 4.0;
10249 let root_search = Search {
10250 lambda,
10251 ..match sb_q {
10252 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10253 None => search,
10254 }
10255 };
10256 let (w, h) = if horz { (SIDE, SUPERBLOCK) } else { (SUPERBLOCK, SIDE) };
10257 let (w_mi, h_mi) = (w / 4, h / 4);
10258 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10259 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
10260 let mut cost = 0.0f64;
10261 let mut halves: Vec<BlockCoeffs> = Vec::with_capacity(2);
10262 for i in 0..2usize {
10263 let (mr, mc) = if horz {
10264 (mi_row + i * 16, mi_col)
10265 } else {
10266 (mi_row, mi_col + i * 16)
10267 };
10268 let stack = find_mv_stack(
10269 grid,
10270 mr,
10271 mc,
10272 w_mi,
10273 h_mi,
10274 LAST_FRAME,
10275 mi_cols as usize,
10276 mi_rows as usize,
10277 );
10278 let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
10279 .iter()
10280 .map(|&(r, pic, _)| {
10281 (
10282 r,
10283 pic,
10284 crate::mvstack::find_mv_stack_compound(
10285 grid,
10286 mr,
10287 mc,
10288 w_mi,
10289 h_mi,
10290 (LAST_FRAME, r),
10291 mi_cols as usize,
10292 mi_rows as usize,
10293 grid.sign_bias_table(),
10294 &[(0, 0); 7],
10295 None,
10296 ),
10297 )
10298 })
10299 .collect();
10300 let found = search_skip_64(
10301 luma,
10302 chroma,
10303 (mc * 4, mr * 4),
10304 (w, h),
10305 &root_search,
10306 false,
10307 reference,
10308 &stack,
10309 &half_compound,
10310 fctx,
10311 );
10312 match found {
10313 Some((mut c, mut block)) => {
10314 // lane-rectres: the same prediction with a REAL residual,
10315 // priced against the skip arm the search just committed to
10316 // the planes -- two 64x64 mu chunks for a half.
10317 if rectres() && block.skip {
10318 c = search_rect_residual(
10319 luma,
10320 chroma,
10321 (mc * 4, mr * 4),
10322 (w, h),
10323 c,
10324 root_search.lambda,
10325 &root_search,
10326 &stack,
10327 &mut block,
10328 );
10329 }
10330 cost += c;
10331 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
10332 halves.push(block);
10333 }
10334 None => {
10335 restore(luma, chroma, (x128, y128), SIDE, &base);
10336 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10337 return None;
10338 }
10339 }
10340 }
10341 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10342 restore(luma, chroma, (x128, y128), SIDE, &base);
10343 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10344 let symbol = if horz { 1 } else { 2 };
10345 let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;
10346 // lane-rectdq: the FIRST half sits at the root's own mode-info origin and
10347 // codes the delta_q group whether it is skipped or not
10348 // (`write_inter_block_128_rect` passes `is_whole_sb = false`); the second
10349 // half is at a non-origin mi and codes none.
10350 let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c));
10351 Some((
10352 cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq),
10353 lambda,
10354 [b0, b1],
10355 after,
10356 ))
10357}
10358
10359/// lane-ab128: one AB shape at a 128 superblock root -- two 64x64 blocks and
10360/// one 128x64 / 64x128 half, in the order [`ab128_pieces`] gives (the
10361/// decoder's own). Each piece is priced through the same `search_skip_64`
10362/// the NONE and HORZ/VERT arms use, at its own footprint, and is published
10363/// into `grid` before the next is searched -- the writer publishes it too, so
10364/// a later piece searched against a stale grid would be priced (and its mv
10365/// predicted) off a stack the decoder never derives (class
10366/// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
10367/// are put back before returning; the caller re-applies the winner.
10368///
10369/// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a
10370/// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where
10371/// libaom's own AB shapes earn their keep.
10372///
10373/// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
10374/// already carrying the root's own partition symbol so it ranks against the
10375/// other root candidates and against the four superblocks below.
10376#[allow(clippy::too_many_arguments)]
10377fn search_root_128_ab(
10378 luma: &mut Plane,
10379 chroma: &mut [Plane; 2],
10380 grid: &mut crate::mvstack::MiGrid,
10381 (root_r, root_c): (usize, usize),
10382 (rows, cols): (usize, usize),
10383 (mi_cols, mi_rows): (u32, u32),
10384 search: Search<'_>,
10385 tpl_factors: &Option<Vec<f64>>,
10386 sb_q: Option<&Vec<u8>>,
10387 sb_cols: usize,
10388 tpl_cells_x: usize,
10389 base_q_idx: u8,
10390 reference: &Picture,
10391 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10392 // The partition symbol, 4..=7.
10393 symbol: usize,
10394 fctx: &crate::decode::FrameCtx,
10395) -> Option<(f64, f64, [BlockCoeffs; 3], [(Vec<u8>, Vec<CoefCtx>); 3])> {
10396 const SIDE: usize = SUPERBLOCK * 2;
10397 const SIDE_MI: usize = SIDE / 4;
10398 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10399 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10400 if root_r * 2 + 3 >= rows
10401 || root_c * 2 + 3 >= cols
10402 || (mi_row + SIDE_MI) as u32 > mi_rows
10403 || (mi_col + SIDE_MI) as u32 > mi_cols
10404 || x128 + SIDE > luma.true_width
10405 || y128 + SIDE > luma.true_height
10406 {
10407 return None;
10408 }
10409 // The root's own lambda, the mean of its four superblocks' -- the same one
10410 // [`search_root_128`] prices with, so every root candidate and the
10411 // four-superblock arm are comparable.
10412 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10413 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10414 (None, Some(f)) => {
10415 let mean = (0..16)
10416 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10417 .sum::<f64>()
10418 / 16.0;
10419 search.lambda * mean
10420 }
10421 (None, None) => search.lambda,
10422 };
10423 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10424 .iter()
10425 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10426 .sum::<f64>()
10427 / 4.0;
10428 let root_search = Search {
10429 lambda,
10430 ..match sb_q {
10431 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10432 None => search,
10433 }
10434 };
10435 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10436 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
10437 let mut cost = 0.0f64;
10438 let mut pieces: Vec<BlockCoeffs> = Vec::with_capacity(3);
10439 for ((mr, mc), (w, h)) in ab128_pieces(symbol, (mi_row, mi_col)) {
10440 let (w_mi, h_mi) = (w / 4, h / 4);
10441 let stack = find_mv_stack(
10442 grid,
10443 mr,
10444 mc,
10445 w_mi,
10446 h_mi,
10447 LAST_FRAME,
10448 mi_cols as usize,
10449 mi_rows as usize,
10450 );
10451 let piece_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
10452 .iter()
10453 .map(|&(r, pic, _)| {
10454 (
10455 r,
10456 pic,
10457 crate::mvstack::find_mv_stack_compound(
10458 grid,
10459 mr,
10460 mc,
10461 w_mi,
10462 h_mi,
10463 (LAST_FRAME, r),
10464 mi_cols as usize,
10465 mi_rows as usize,
10466 grid.sign_bias_table(),
10467 &[(0, 0); 7],
10468 None,
10469 ),
10470 )
10471 })
10472 .collect();
10473 let found = search_skip_64(
10474 luma,
10475 chroma,
10476 (mc * 4, mr * 4),
10477 (w, h),
10478 &root_search,
10479 false,
10480 reference,
10481 &stack,
10482 &piece_compound,
10483 fctx,
10484 );
10485 match found {
10486 Some((mut c, mut block)) => {
10487 // lane-rectres: the same prediction with a REAL residual,
10488 // priced against the skip arm the search just committed to
10489 // the planes -- one mu chunk for a 64x64 square, two for a
10490 // half. The 64x64 squares are where libaom's own AB shapes
10491 // earn their keep.
10492 if rectres() && block.skip {
10493 c = search_rect_residual(
10494 luma,
10495 chroma,
10496 (mc * 4, mr * 4),
10497 (w, h),
10498 c,
10499 root_search.lambda,
10500 &root_search,
10501 &stack,
10502 &mut block,
10503 );
10504 }
10505 cost += c;
10506 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
10507 pieces.push(block);
10508 }
10509 None => {
10510 restore(luma, chroma, (x128, y128), SIDE, &base);
10511 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10512 return None;
10513 }
10514 }
10515 }
10516 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10517 restore(luma, chroma, (x128, y128), SIDE, &base);
10518 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10519 let [b0, b1, b2] = <[BlockCoeffs; 3]>::try_from(pieces).ok()?;
10520 Some((
10521 cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),
10522 lambda,
10523 [b0, b1, b2],
10524 after,
10525 ))
10526}
10527
10528/// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
10529/// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
10530/// SKIP, priced through the same `symbol_bits` path every other candidate
10531/// uses. The winner's prediction is committed to the planes (it IS the
10532/// reconstruction -- a skip block has no residual); the caller restores them
10533/// if the four quadrants come out cheaper.
10534///
10535/// `None` when no candidate could be coded at all (a `NEWMV` residual the
10536/// writer cannot name is simply not offered, and the other modes always are,
10537/// so this only happens if every candidate is refused).
10538fn search_skip_64(
10539 luma: &mut Plane,
10540 chroma: &mut [Plane; 2],
10541 (x, y): (usize, usize),
10542 // The root's footprint in samples: [`SUPERBLOCK`] square at a 64 root,
10543 // twice that at the 128 one [`search_root_128`] drives (lane-b128), and
10544 // 128x64 / 64x128 at the rect halves of [`search_root_128_rect`]
10545 // (lane-b128hv). Every trial below tiles it into squares of its SHORTER
10546 // side (one square when it is square, two otherwise), and the residual
10547 // arm is only ever asked for at 64 -- a 128 block's residual is four
10548 // TX_64X64 units the writer has no path for.
10549 (bw, bh): (usize, usize),
10550 search: &Search,
10551 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
10552 // screen content -- see that function's doc).
10553 residual: bool,
10554 reference: &Picture,
10555 stack: &MvStack,
10556 // The COMPOUND stack of each `LAST` + extra-reference pair at THIS
10557 // superblock's 16x16-mi window, built off the same grid the tile writer
10558 // rebuilds it from (empty unless the frame carries `reference_select`).
10559 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10560 fctx: &crate::decode::FrameCtx,
10561) -> Option<(f64, BlockCoeffs)> {
10562 debug_assert!(
10563 (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual,
10564 "only a 64 root has a residual arm"
10565 );
10566 // The square units every trial below is taken on: the block itself when
10567 // it is square, its two halves otherwise. Luma first (in raster order),
10568 // then each chroma plane over the same tiling at half the side -- which is
10569 // exactly `[(0, x, y, side), (1, ..), (2, ..)]` at bw == bh.
10570 let sq = bw.min(bh);
10571 let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize)
10572 .flat_map(|plane| {
10573 let (ox, oy, s) = if plane == 0 { (x, y, sq) } else { (x / 2, y / 2, sq / 2) };
10574 (0..bh / sq).flat_map(move |j| {
10575 (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0))
10576 })
10577 })
10578 .collect();
10579 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
10580 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
10581 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
10582 // What every candidate pays whatever its vector: `skip` coded 1, then
10583 // `is_inter` coded 1, then the LAST chain above.
10584 let fixed = skip_bits_at(stack, true) + intra_inter_bits_at(stack, true) + ref_bits;
10585 let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo {
10586 ref1: None,
10587 mv1: (0, 0),
10588 ref_frame: crate::mvstack::LAST_FRAME,
10589 mode,
10590 mv,
10591 ref_mv_idx,
10592 };
10593 let mut cands: Vec<(f64, InterInfo)> = vec![
10594 (
10595 not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
10596 info_of(InterMode::NearestMv, stack.nearest_mv, 0),
10597 ),
10598 (
10599 not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
10600 info_of(InterMode::GlobalMv, (0, 0), 0),
10601 ),
10602 ];
10603 let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
10604 for idx in 1..=2usize {
10605 if let Some(e) = stack.entries.get(idx) {
10606 cands.push((
10607 near_bits + drl_bits_for(stack, 1, idx),
10608 info_of(InterMode::NearMv, e.mv, idx as u8),
10609 ));
10610 }
10611 }
10612 // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV`
10613 // candidate below to pair with the second reference's NEAREST half.
10614 let mut last_new_mv: Option<(i32, i32)> = None;
10615 if leaf_new_mv() {
10616 let source_block = luma.source_block_rect(x, y, bw, bh);
10617 let (seeds, seed_n) = mv_seeds(stack);
10618 let found = motion::search(
10619 &reference.y,
10620 reference.width,
10621 luma.true_width,
10622 luma.true_height,
10623 &source_block,
10624 x,
10625 y,
10626 bw,
10627 bh,
10628 stack.pred_mv,
10629 &seeds[..seed_n],
10630 search.lambda,
10631 fctx,
10632 1,
10633 );
10634 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
10635 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
10636 last_new_mv = Some(mv);
10637 cands.push((
10638 symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits),
10639 info_of(InterMode::NewMv, mv, ref_mv_idx),
10640 ));
10641 }
10642 }
10643
10644 let mut best: Option<(f64, f64, InterInfo, Vec<Trial>)> = None;
10645 for (bits, info) in cands {
10646 let trials: Vec<Trial> = units
10647 .iter()
10648 .map(|&(plane, px, py, s, is_luma)| {
10649 let (samples, stride, w, h) = match plane {
10650 0 => (&reference.y, reference.width, luma.true_width, luma.true_height),
10651 1 => (
10652 &reference.u,
10653 reference.width / 2,
10654 chroma[0].true_width,
10655 chroma[0].true_height,
10656 ),
10657 _ => (
10658 &reference.v,
10659 reference.width / 2,
10660 chroma[1].true_width,
10661 chroma[1].true_height,
10662 ),
10663 };
10664 let prediction = predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx);
10665 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
10666 // `skip` true: the trial is the prediction itself plus its SSE,
10667 // so no transform of any size is involved (the reason a 64x64
10668 // root can be coded at all before a forward TX_64X64 exists).
10669 target.code_from_prediction(
10670 px,
10671 py,
10672 s,
10673 &prediction,
10674 true,
10675 search.base_q_idx,
10676 search.deadzone,
10677 TxbSet::Luma32Inter,
10678 )
10679 })
10680 .collect();
10681 let cost =
10682 trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * (fixed + bits);
10683 if best.as_ref().is_none_or(|b| cost < b.0) {
10684 best = Some((cost, fixed + bits, info, trials));
10685 }
10686 }
10687
10688 // lane-b64b: the COMPOUND candidates at the 64 root, the same three a
10689 // superblock can form without a second motion search ([`b64_compound`]),
10690 // priced through the same `symbol_bits` path -- `fixed` minus the single
10691 // reference's tree, plus the pair tree and the compound mode.
10692 for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) {
10693 let (ref1, g) = (*ref1, *g);
10694 // The whole `comp_mode` + reference-pair tree at the writer's own
10695 // contexts, for THIS pair (lane-ctx).
10696 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
10697 let mode_ctx =
10698 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
10699 let mode_bits_of =
10700 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
10701 let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo {
10702 ref1: Some(ref1),
10703 mv1: mvs.1,
10704 ref_frame: crate::mvstack::LAST_FRAME,
10705 mode,
10706 mv: mvs.0,
10707 ref_mv_idx: 0,
10708 };
10709 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
10710 (
10711 cstack.nearest_mv,
10712 mode_bits_of(0),
10713 compound_info(InterMode::NearestNearestMv, cstack.nearest_mv),
10714 ),
10715 (
10716 ((0, 0), (0, 0)),
10717 mode_bits_of(6),
10718 compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))),
10719 ),
10720 ];
10721 // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search
10722 // above, its residual priced against compound stack entry 0 -- what
10723 // `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
10724 let cbase = cstack
10725 .entries
10726 .first()
10727 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
10728 if let Some(new_mv) = last_new_mv
10729 && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
10730 {
10731 let mvs = (new_mv, cstack.nearest_mv.1);
10732 ccands.push((
10733 mvs,
10734 mode_bits_of(3) + b0,
10735 compound_info(InterMode::NewNearestMv, mvs),
10736 ));
10737 }
10738 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
10739 ccands.dedup_by_key(|c| c.0);
10740 for (mvs, bits, info) in ccands {
10741 let trials: Vec<Trial> = units
10742 .iter()
10743 .map(|&(plane, px, py, s, is_luma)| {
10744 let (r0, r1) = match plane {
10745 0 => (
10746 (reference.y.as_slice(), reference.width, luma.true_width, luma.true_height),
10747 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
10748 ),
10749 1 => (
10750 (
10751 reference.u.as_slice(),
10752 reference.width / 2,
10753 chroma[0].true_width,
10754 chroma[0].true_height,
10755 ),
10756 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
10757 ),
10758 _ => (
10759 (
10760 reference.v.as_slice(),
10761 reference.width / 2,
10762 chroma[1].true_width,
10763 chroma[1].true_height,
10764 ),
10765 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
10766 ),
10767 };
10768 let prediction =
10769 predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx);
10770 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
10771 target.code_from_prediction(
10772 px,
10773 py,
10774 s,
10775 &prediction,
10776 true,
10777 search.base_q_idx,
10778 search.deadzone,
10779 TxbSet::Luma32Inter,
10780 )
10781 })
10782 .collect();
10783 let syntax = fixed - ref_bits + bits;
10784 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * syntax;
10785 if best.as_ref().is_none_or(|b| cost < b.0) {
10786 best = Some((cost, syntax, info, trials));
10787 }
10788 }
10789 }
10790
10791 let (skip_cost, syntax, info, skip_trials) = best?;
10792
10793 // The winner's prediction coded with a REAL residual (lane-tx64): one
10794 // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the
10795 // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per
10796 // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv
10797 // the skip arm already chose is re-coded: the prediction with the lowest
10798 // SSE is also the cheapest residual to code, and a second 64x64 motion
10799 // search per superblock is the wall this root was taken to SAVE.
10800 //
10801 // Priced against the skip arm through the same `symbol_bits` path, so the
10802 // two numbers are comparable: `fixed` charged `skip` coded 1, and this
10803 // arm charges 0 instead and adds its three planes' coefficient bits.
10804 let mut chosen = (skip_cost, true, skip_trials);
10805 // Set when [`commit_inter_luma`] already wrote the residual arm's luma
10806 // into the plane, so the tail below does not commit over its units.
10807 let mut luma_committed = false;
10808 // The residual arm's luma levels and the `txfm_split` depth the writer
10809 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is
10810 // four TX_32X32 units in 64x64 ones.
10811 let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None;
10812 if residual {
10813 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
10814 // Square by construction (the `debug_assert` above), so `units` is
10815 // one entry per plane and `chosen.2[plane]` is that plane's trial.
10816 let residual_trials = [0usize, 1, 2].map(|plane| {
10817 let (target, px, py, s) = if plane == 0 {
10818 (&*luma, x, y, bw)
10819 } else {
10820 (&chroma[plane - 1], x / 2, y / 2, bw / 2)
10821 };
10822 target.code_from_prediction(
10823 px,
10824 py,
10825 s,
10826 &chosen.2[plane].reconstruction,
10827 false,
10828 search.base_q_idx,
10829 search.deadzone,
10830 sets[plane],
10831 )
10832 });
10833 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10834 let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum();
10835 // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the
10836 // four TX_32X32 units of `txfm_split = 1`, taken by the same
10837 // `commit_inter_luma` every other inter block's is (it commits the
10838 // winner and hands back the cost it took off the flat arm).
10839 let (levels, depth, gain, tx_types) = if b64_var_tx() {
10840 let second = info.ref1.and_then(|r1| {
10841 compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| {
10842 (
10843 info.mv1,
10844 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
10845 )
10846 })
10847 });
10848 luma_committed = true;
10849 commit_inter_luma(
10850 luma,
10851 (x, y),
10852 bw,
10853 info.mv,
10854 (&reference.y, reference.width, luma.true_width, luma.true_height),
10855 search,
10856 &residual_trials[0],
10857 false,
10858 second,
10859 fctx,
10860 )
10861 } else {
10862 (residual_trials[0].levels.clone(), 0, 0.0, Vec::new())
10863 };
10864 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
10865 + search.lambda * (syntax + unskip + coeff_bits)
10866 + gain;
10867 if cost < skip_cost {
10868 B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10869 if depth == 1 {
10870 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10871 }
10872 luma_levels = Some((levels, depth, tx_types));
10873 chosen = (cost, false, residual_trials.to_vec());
10874 }
10875 }
10876
10877 let (cost, skip, trials) = chosen;
10878 // `commit_inter_luma` already wrote the residual arm's luma (its four
10879 // split units are not one 64-sided trial); a skip winner overwrites it.
10880 for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) {
10881 match plane {
10882 0 if skip || !luma_committed => luma.commit(px, py, s, trial),
10883 0 => {}
10884 _ => chroma[plane - 1].commit(px, py, s, trial),
10885 }
10886 }
10887 Some((
10888 cost,
10889 BlockCoeffs {
10890 skip,
10891 inter: Some(info),
10892 // The chroma grids are whole TX_32X32; the luma one is the
10893 // 64-point transform's coded 32x32 corner at depth 0 and the
10894 // whole 64-sided block at depth 1 (lane-b64b).
10895 tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d),
10896 luma_tx_types: match (skip, &luma_levels) {
10897 (false, Some((_, _, types))) => types.clone(),
10898 _ => Vec::new(),
10899 },
10900 luma: match (skip, &luma_levels) {
10901 (true, _) => Vec::new(),
10902 (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK),
10903 (false, Some((levels, _, _))) => coeffs(levels, BLOCK),
10904 (false, None) => coeffs(&trials[0].levels, BLOCK),
10905 },
10906 u: if skip { Vec::new() } else { coeffs(&trials[1].levels, bw / 2) },
10907 v: if skip { Vec::new() } else { coeffs(&trials[2].levels, bw / 2) },
10908 ..BlockCoeffs::default()
10909 },
10910 ))
10911}
10912
10913fn search_inter_block(
10914 luma: &mut Plane,
10915 chroma: &mut [Plane; 2],
10916 (x, y): (usize, usize),
10917 search: &Search,
10918 mode_bits: &[f64; 13],
10919 reference: &Picture,
10920 stack: &MvStack,
10921 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
10922 // for the whole GOP, with the stack this block derives against it. Only
10923 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
10924 // second motion search would double the wall of the stage that already
10925 // owns most of it.
10926 extra: &[(i8, &Picture, &MvStack)],
10927 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
10928 // the caller off the same MI grid the tile writer will (empty unless the
10929 // frame carries `reference_select`).
10930 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10931 // lane-av1obmc: the mi grid this search's neighbours were published into
10932 // (`record_mi`) and this block's own place in it -- what the OBMC
10933 // candidate's eligibility walk and neighbour plan read, the same state
10934 // the tile writer will read when it codes the `motion_mode` symbol.
10935 grid: &MiGrid,
10936 (mi_row, mi_col): (usize, usize),
10937 (mi_rows, mi_cols): (usize, usize),
10938 fctx: &crate::decode::FrameCtx,
10939) -> (BlockCoeffs, f64) {
10940 // `luma_set` is the INTRA candidates' table; the two inter candidates
10941 // below price their coefficients through `TxbSet::Luma32Inter`, which is
10942 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
10943 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
10944 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
10945 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
10946
10947 // skip / intra_inter symbol costs at a fixed context -- see this
10948 // function's doc comment.
10949 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
10950 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
10951
10952 struct Candidate {
10953 cost: f64,
10954 luma: Trial,
10955 u: Trial,
10956 v: Trial,
10957 mode: u8,
10958 skip: bool,
10959 inter: Option<InterInfo>,
10960 /// The mode/mv syntax this candidate pays for, apart from its
10961 /// residual -- what the OBMC candidate below has to re-pay when it
10962 /// re-prices the winner's prediction.
10963 mode_bits: f64,
10964 }
10965 let mut best: Option<Candidate> = None;
10966 let mut consider = |candidate: Candidate| {
10967 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
10968 best = Some(candidate);
10969 }
10970 };
10971
10972 // The chroma trial an intra candidate prices does not depend on `mode`
10973 // at all -- both planes always code `DC_PRED` here (a coding choice this
10974 // search inherited, not this loop's to second-guess) at the same `reach:
10975 // Reach::none()` -- so it is the same call with the same inputs on every
10976 // one of the thirteen iterations below; run it once and reuse the result
10977 // rather than repeat an already-priced transform/quantize/entropy call
10978 // twelve times for nothing (bit-identical: the value each iteration
10979 // reads back is exactly what it used to recompute).
10980 let u_trial = chroma[0].trial(
10981 At {
10982 x: x / 2,
10983 y: y / 2,
10984 side: BLOCK / 2,
10985 reach: Reach::none(),
10986 set: chroma_set,
10987 },
10988 DC_PRED,
10989 0,
10990 search.base_q_idx,
10991 search.deadzone, fctx,
10992 );
10993 let v_trial = chroma[1].trial(
10994 At {
10995 x: x / 2,
10996 y: y / 2,
10997 side: BLOCK / 2,
10998 reach: Reach::none(),
10999 set: chroma_set,
11000 },
11001 DC_PRED,
11002 0,
11003 search.base_q_idx,
11004 search.deadzone, fctx,
11005 );
11006
11007 let intra_modes: Vec<u8> = match search.top_k {
11008 Some(k) if k < search.modes.len() => {
11009 let scored = luma.intra_scores(
11010 At {
11011 x,
11012 y,
11013 side: BLOCK,
11014 reach,
11015 set: luma_set,
11016 },
11017 search.modes,
11018 mode_bits,
11019 search.lambda, fctx,
11020 );
11021 prune_by_sad(search.modes, scored, k)
11022 }
11023 _ => search.modes.to_vec(),
11024 };
11025 census_add(5, 1);
11026 census_add(6, if search.arf_leaf_intra { intra_modes.len() } else { 0 });
11027 // lane-arfmode: arm 1 drops the whole-32 block's intra candidates at the
11028 // top ARF too -- the probe proved the ARF's intra AREA lives HERE, not at
11029 // the leaves (film A arm 1 vs control byte-identical with the leaf gate
11030 // alone), so "the 32x32 whole keeps intra as the scene-cut hatch" was a
11031 // hatch nothing else was using. Counted once per block.
11032 if search.arf_leaf_intra {
11033 for &mode in &intra_modes {
11034 let luma_trial = luma.trial(
11035 At {
11036 x,
11037 y,
11038 side: BLOCK,
11039 reach,
11040 set: luma_set,
11041 },
11042 mode,
11043 0,
11044 search.base_q_idx,
11045 search.deadzone, fctx,
11046 );
11047 let u = u_trial.clone();
11048 let v = v_trial.clone();
11049 let cost = luma_trial.sse
11050 + u.sse
11051 + v.sse
11052 + search.lambda
11053 * (luma_trial.bits
11054 + u.bits
11055 + v.bits
11056 + mode_bits[usize::from(mode)]
11057 + skip_bits(false)
11058 + intra_inter_bits(false));
11059 consider(Candidate {
11060 cost,
11061 luma: luma_trial,
11062 u,
11063 v,
11064 mode,
11065 skip: false,
11066 inter: None,
11067 mode_bits: mode_bits[usize::from(mode)],
11068 });
11069 }
11070 } else {
11071 arfmode_hit(0);
11072 }
11073
11074 // The reference frame buffer a spec decoder holds is exactly the true
11075 // (unpadded) coded extent -- a superblock whose partition stops early at
11076 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
11077 // beyond it, so those samples are never part of the decoded picture.
11078 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
11079 // reference sample position clamp), not to this crate's own
11080 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
11081 // here would let a fractional-pel read past the true edge pick up this
11082 // encoder's own uncoded padding instead of the true edge's replicated
11083 // value a decoder computes.
11084 let ref_luma = (
11085 &reference.y,
11086 reference.width,
11087 luma.true_width,
11088 luma.true_height,
11089 );
11090 let ref_u = (
11091 &reference.u,
11092 reference.width / 2,
11093 chroma[0].true_width,
11094 chroma[0].true_height,
11095 );
11096 let ref_v = (
11097 &reference.v,
11098 reference.width / 2,
11099 chroma[1].true_width,
11100 chroma[1].true_height,
11101 );
11102 // Every single-reference mode the writer can code (spec 5.11.24's symbol
11103 // chain, mirrored by `tile::write_inter_mode`), priced with the static
11104 // CDFs at this block's own stack contexts. A candidate is a motion
11105 // vector plus the cheapest syntax that reaches it, so two modes landing
11106 // on the same vector share one set of trials: the added modes cost
11107 // mode-bit arithmetic, not another motion compensation.
11108 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
11109 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
11110 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
11111 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
11112 // the loop cannot reach is never offered below -- every candidate's
11113 // index is one this same loop walks to.
11114 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
11115 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
11116 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
11117 (
11118 stack.nearest_mv,
11119 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
11120 InterInfo {
11121 ref1: None,
11122 mv1: (0, 0),
11123 ref_frame: crate::mvstack::LAST_FRAME,
11124 mode: InterMode::NearestMv,
11125 mv: stack.nearest_mv,
11126 ref_mv_idx: 0,
11127 },
11128 ),
11129 // GLOBALMV is the identity model's zero vector -- this encoder writes
11130 // no `gm_params` -- and the cheapest syntax of the four on the static
11131 // content where that vector is also the right one.
11132 (
11133 (0, 0),
11134 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
11135 InterInfo {
11136 ref1: None,
11137 mv1: (0, 0),
11138 ref_frame: crate::mvstack::LAST_FRAME,
11139 mode: InterMode::GlobalMv,
11140 mv: (0, 0),
11141 ref_mv_idx: 0,
11142 },
11143 ),
11144 ];
11145 let near_bits =
11146 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
11147 for idx in 1..=2usize {
11148 if let Some(e) = stack.entries.get(idx) {
11149 cands.push((
11150 e.mv,
11151 near_bits + drl_bits(1, idx),
11152 InterInfo {
11153 ref1: None,
11154 mv1: (0, 0),
11155 ref_frame: crate::mvstack::LAST_FRAME,
11156 mode: InterMode::NearMv,
11157 mv: e.mv,
11158 ref_mv_idx: idx as u8,
11159 },
11160 ));
11161 }
11162 }
11163
11164 let source_block = luma.source_block(x, y, BLOCK);
11165 let (seeds, seed_n) = mv_seeds(stack);
11166 #[cfg(test)]
11167 let t = stage_start();
11168 let found = motion::search(
11169 ref_luma.0,
11170 ref_luma.1,
11171 ref_luma.2,
11172 ref_luma.3,
11173 &source_block,
11174 x,
11175 y,
11176 BLOCK,
11177 BLOCK,
11178 stack.pred_mv,
11179 &seeds[..seed_n],
11180 search.lambda, fctx,
11181 1,
11182 );
11183 #[cfg(test)]
11184 stage_since(0, t);
11185 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
11186 // lane-newmv: this block's own `NEWMV` vector and what its mv syntax
11187 // costs, for the census below (`None` when the writer cannot name it).
11188 let mut newmv_syntax: Option<((i32, i32), f64)> = None;
11189 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
11190 // the same vector costs a different residual from each: take the index
11191 // whose residual plus DRL bits is cheapest, not entry 0 by default.
11192 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
11193 newmv_syntax = Some((mv, bits));
11194 cands.push((
11195 mv,
11196 last_ref_bits
11197 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
11198 + bits
11199 + mv_rate_surcharge(bits),
11200 InterInfo {
11201 ref1: None,
11202 mv1: (0, 0),
11203 ref_frame: crate::mvstack::LAST_FRAME,
11204 mode: InterMode::NewMv,
11205 mv,
11206 ref_mv_idx,
11207 },
11208 ));
11209 }
11210
11211 // Each extra reference's own `NEWMV` vector, for the compound
11212 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
11213 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
11214 for &(ref_frame, g, gstack) in extra {
11215 let g_ref_bits = single_ref_bits(ref_frame, gstack);
11216 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
11217 cands.push((
11218 gstack.nearest_mv,
11219 g_ref_bits
11220 + g_not_new
11221 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
11222 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
11223 InterInfo {
11224 ref1: None,
11225 mv1: (0, 0),
11226 ref_frame,
11227 mode: InterMode::NearestMv,
11228 mv: gstack.nearest_mv,
11229 ref_mv_idx: 0,
11230 },
11231 ));
11232 cands.push((
11233 (0, 0),
11234 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
11235 InterInfo {
11236 ref1: None,
11237 mv1: (0, 0),
11238 ref_frame,
11239 mode: InterMode::GlobalMv,
11240 mv: (0, 0),
11241 ref_mv_idx: 0,
11242 },
11243 ));
11244 // A motion search of this reference's own: without it, GOLDEN/ALTREF
11245 // can only be coded at a vector some neighbour already found, which
11246 // is why they carried a third of the inter blocks at their two
11247 // search-free modes alone.
11248 // The search is skipped when this reference's own NEARESTMV already
11249 // prices out `margin` times better than LAST's best vector does --
11250 // one candidate evaluation (`motion::cost_at`) standing in for a
11251 // whole search of ~50.
11252 // lane-last2: the SEARCH-FREE arm for the second past leaf picture
11253 // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some
11254 // neighbour already found, which is how GOLDEN/ALTREF were offered
11255 // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's
11256 // own value from the second motion search's wall.
11257 let searched = extra_ref_new_mv()
11258 && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());
11259 let margin = extra_new_skip_margin();
11260 if searched {
11261 newmv_census_global(0);
11262 }
11263 let skip_search = searched
11264 && margin > 0.0
11265 && motion::cost_at(
11266 &g.y,
11267 g.width,
11268 luma.true_width,
11269 luma.true_height,
11270 &source_block,
11271 x,
11272 y,
11273 BLOCK,
11274 BLOCK,
11275 gstack.nearest_mv,
11276 gstack.pred_mv,
11277 search.lambda,
11278 fctx,
11279 ) * margin
11280 <= found.cost;
11281 if skip_search {
11282 newmv_census_global(1);
11283 }
11284 if searched && !skip_search {
11285 let (gseeds, gn) = mv_seeds(gstack);
11286 #[cfg(test)]
11287 let t = stage_start();
11288 let gfound = motion::search(
11289 &g.y,
11290 g.width,
11291 luma.true_width,
11292 luma.true_height,
11293 &source_block,
11294 x,
11295 y,
11296 BLOCK,
11297 BLOCK,
11298 gstack.pred_mv,
11299 &gseeds[..gn],
11300 search.lambda, fctx,
11301 ref_distance(ref_frame),
11302 );
11303 #[cfg(test)]
11304 stage_since(0, t);
11305 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
11306 extra_new_mvs.push((ref_frame, gmv));
11307 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
11308 cands.push((
11309 gmv,
11310 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
11311 InterInfo {
11312 ref1: None,
11313 mv1: (0, 0),
11314 ref_frame,
11315 mode: InterMode::NewMv,
11316 mv: gmv,
11317 ref_mv_idx,
11318 },
11319 ));
11320 }
11321 }
11322 }
11323
11324 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
11325 // trial set each: both references predict the block and the two
11326 // predictions are averaged, which is what pays on content where neither
11327 // reference alone is right. Priced with the same static-CDF approximation
11328 // the single-reference candidates use, plus the compound-only symbols
11329 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
11330 // The two compound-mode arms, each measured alone on the BD gate before
11331 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
11332 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
11333 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
11334 // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on:
11335 // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5,
11336 // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of
11337 // the keep rule. Still behind the knob.
11338 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
11339 let half_new = true;
11340 for (ref1, g, cstack) in compound {
11341 let (ref1, g) = (*ref1, *g);
11342 // The whole `comp_mode` + reference-pair tree at the writer's own
11343 // contexts, for THIS pair (lane-ctx).
11344 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
11345 let mode_ctx =
11346 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
11347 let mode_bits_of =
11348 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
11349 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
11350 (
11351 cstack.nearest_mv,
11352 mode_bits_of(0),
11353 InterInfo {
11354 ref_frame: crate::mvstack::LAST_FRAME,
11355 mode: InterMode::NearestNearestMv,
11356 mv: cstack.nearest_mv.0,
11357 mv1: cstack.nearest_mv.1,
11358 ref1: Some(ref1),
11359 ref_mv_idx: 0,
11360 },
11361 ),
11362 (
11363 ((0, 0), (0, 0)),
11364 mode_bits_of(6),
11365 InterInfo {
11366 ref_frame: crate::mvstack::LAST_FRAME,
11367 mode: InterMode::GlobalGlobalMv,
11368 mv: (0, 0),
11369 mv1: (0, 0),
11370 ref1: Some(ref1),
11371 ref_mv_idx: 0,
11372 },
11373 ),
11374 ];
11375 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
11376 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
11377 // the stack is deep enough for that walk to read one.
11378 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
11379 let drl = if cstack.entries.len() > 2 {
11380 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
11381 } else {
11382 0.0
11383 };
11384 ccands.push((
11385 (e.mv0, e.mv1),
11386 mode_bits_of(1) + drl,
11387 InterInfo {
11388 ref_frame: crate::mvstack::LAST_FRAME,
11389 mode: InterMode::NearNearMv,
11390 mv: e.mv0,
11391 mv1: e.mv1,
11392 ref1: Some(ref1),
11393 ref_mv_idx: 0,
11394 },
11395 ));
11396 }
11397 // The half-new modes and `NEW_NEWMV`, all seeded from the two
11398 // single-reference searches this block already ran -- no joint search
11399 // of its own. Every residual is priced against stack entry 0, which
11400 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
11401 let cbase = cstack
11402 .entries
11403 .first()
11404 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
11405 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
11406 ccands.push((
11407 (mv, cstack.nearest_mv.1),
11408 mode_bits_of(3) + b0,
11409 InterInfo {
11410 ref_frame: crate::mvstack::LAST_FRAME,
11411 mode: InterMode::NewNearestMv,
11412 mv,
11413 mv1: cstack.nearest_mv.1,
11414 ref1: Some(ref1),
11415 ref_mv_idx: 0,
11416 },
11417 ));
11418 }
11419 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
11420 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
11421 ccands.push((
11422 (cstack.nearest_mv.0, mv1),
11423 mode_bits_of(2) + b1,
11424 InterInfo {
11425 ref_frame: crate::mvstack::LAST_FRAME,
11426 mode: InterMode::NearestNewMv,
11427 mv: cstack.nearest_mv.0,
11428 mv1,
11429 ref1: Some(ref1),
11430 ref_mv_idx: 0,
11431 },
11432 ));
11433 }
11434 let base = cbase;
11435 if let (Some(b0), Some(b1)) = (
11436 mv_residual_bits(mv, base.0),
11437 mv_residual_bits(mv1, base.1),
11438 ) {
11439 ccands.push((
11440 (mv, mv1),
11441 mode_bits_of(7) + b0 + b1,
11442 InterInfo {
11443 ref_frame: crate::mvstack::LAST_FRAME,
11444 mode: InterMode::NewNewMv,
11445 mv,
11446 mv1,
11447 ref1: Some(ref1),
11448 ref_mv_idx: 0,
11449 },
11450 ));
11451 }
11452 }
11453 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
11454 ccands.dedup_by_key(|c| c.0);
11455 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
11456 let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height);
11457 let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height);
11458 for (mvs, bits, info) in ccands {
11459 let luma_trial = mc_trial_compound(
11460 luma, x, y, BLOCK, mvs, true,
11461 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
11462 search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx,
11463 );
11464 let u = mc_trial_compound(
11465 &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false,
11466 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
11467 search.base_q_idx, search.deadzone, chroma_set, fctx,
11468 );
11469 let v = mc_trial_compound(
11470 &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false,
11471 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
11472 search.base_q_idx, search.deadzone, chroma_set, fctx,
11473 );
11474 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11475 && u.levels.iter().all(|&l| l == 0)
11476 && v.levels.iter().all(|&l| l == 0);
11477 let cost = luma_trial.sse
11478 + u.sse
11479 + v.sse
11480 + search.lambda
11481 * (skip_bits(skip)
11482 + intra_inter_bits(true)
11483 + bits
11484 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
11485 consider(Candidate {
11486 cost,
11487 luma: luma_trial,
11488 u,
11489 v,
11490 mode: DC_PRED,
11491 skip,
11492 mode_bits: bits,
11493 inter: Some(info),
11494 });
11495 }
11496 }
11497
11498 // One trial set per distinct (reference, vector) pair: sort, cheapest
11499 // syntax first, and drop the rest of each pair's run.
11500 cands.sort_by(|a, b| {
11501 (a.2.ref_frame, a.0)
11502 .cmp(&(b.2.ref_frame, b.0))
11503 .then(a.1.total_cmp(&b.1))
11504 });
11505 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
11506 census_add(7, cands.len());
11507 // lane-newmv: the NEWMV candidate's own RD cost against the best cost
11508 // this block reaches WITHOUT it, taken inside the one loop that prices
11509 // them all (a second pricing pass would be a second oracle).
11510 let (mut new_cost, mut other_cost) = (f64::INFINITY, f64::INFINITY);
11511 {
11512 for (mv, mode_bits_inter, info) in cands {
11513 let (ref_luma, ref_u, ref_v) = match extra
11514 .iter()
11515 .find(|(r, _, _)| *r == info.ref_frame)
11516 {
11517 Some(&(_, g, _)) => (
11518 (&g.y, g.width, luma.true_width, luma.true_height),
11519 (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
11520 (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
11521 ),
11522 None => (ref_luma, ref_u, ref_v),
11523 };
11524 let luma_trial = mc_trial(
11525 luma,
11526 x,
11527 y,
11528 BLOCK,
11529 mv,
11530 true,
11531 ref_luma.0,
11532 ref_luma.1,
11533 ref_luma.2,
11534 ref_luma.3,
11535 false,
11536 search.base_q_idx,
11537 search.deadzone,
11538 TxbSet::Luma32Inter, fctx,
11539 );
11540 let u = mc_trial(
11541 &chroma[0],
11542 x / 2,
11543 y / 2,
11544 BLOCK / 2,
11545 mv,
11546 false,
11547 ref_u.0,
11548 ref_u.1,
11549 ref_u.2,
11550 ref_u.3,
11551 false,
11552 search.base_q_idx,
11553 search.deadzone,
11554 chroma_set, fctx,
11555 );
11556 let v = mc_trial(
11557 &chroma[1],
11558 x / 2,
11559 y / 2,
11560 BLOCK / 2,
11561 mv,
11562 false,
11563 ref_v.0,
11564 ref_v.1,
11565 ref_v.2,
11566 ref_v.3,
11567 false,
11568 search.base_q_idx,
11569 search.deadzone,
11570 chroma_set, fctx,
11571 );
11572 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11573 && u.levels.iter().all(|&l| l == 0)
11574 && v.levels.iter().all(|&l| l == 0);
11575 let cost = luma_trial.sse
11576 + u.sse
11577 + v.sse
11578 + search.lambda
11579 * (skip_bits(skip)
11580 + intra_inter_bits(true)
11581 + mode_bits_inter
11582 + if skip {
11583 0.0
11584 } else {
11585 luma_trial.bits + u.bits + v.bits
11586 });
11587 consider(Candidate {
11588 cost,
11589 luma: luma_trial,
11590 u,
11591 v,
11592 mode: DC_PRED,
11593 skip,
11594 mode_bits: mode_bits_inter,
11595 inter: Some(info),
11596 });
11597 if newmv_census_on() {
11598 if info.mode == InterMode::NewMv
11599 && info.ref1.is_none()
11600 && info.ref_frame == crate::mvstack::LAST_FRAME
11601 {
11602 new_cost = cost;
11603 } else {
11604 other_cost = other_cost.min(cost);
11605 }
11606 }
11607 }
11608 }
11609 if let Some((new_mv, bits)) = newmv_syntax {
11610 newmv_census_block(BLOCK, true, new_cost, other_cost, new_mv, stack.nearest_mv, bits);
11611 } else {
11612 newmv_census_block(BLOCK, false, f64::INFINITY, other_cost, mv, stack.nearest_mv, 0.0);
11613 }
11614
11615 let best = best.expect("the search offers at least the intra modes");
11616 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
11617 // offered to the SINGLE-REFERENCE winner only -- libaom's
11618 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
11619 // compound block, so the writer codes no symbol for one. The prediction
11620 // is built by the DECODER's own plan and blend
11621 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
11622 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
11623 // this search's `grid` already carries, so what is priced here is what a
11624 // decoder reconstructs -- never a second implementation of the blend.
11625 //
11626 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
11627 // on). Native crop BD, the standing recipe, with it on against the same
11628 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
11629 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
11630 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
11631 // one UP -- the keep rule wants two down and one flat, so it stays off.
11632 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
11633 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
11634 // things bound it and are the upgrade path: only the 32x32 winner is
11635 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
11636 // that is where libaom cashes most of its OBMC gain), and the symbol/
11637 // residual price here is the static-CDF estimate.
11638 let mut best = best;
11639 let mut motion_won = 0u8;
11640 if let Some(info) = best.inter.filter(|i| {
11641 i.ref1.is_none()
11642 && (crate::envflags::env_flag!("EC_AV1_OBMC")
11643 || warp_on())
11644 }) {
11645 let mut refs: [Option<&Picture>; 8] = [None; 8];
11646 refs[LAST_FRAME as usize] = Some(reference);
11647 for &(r, p, _) in extra {
11648 refs[r as usize] = Some(p);
11649 }
11650 // This block's OWN reference planes: the single-reference winner may
11651 // be one of the extra references, not LAST.
11652 let planes: [(&[u16], usize, usize, usize); 3] =
11653 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11654 Some(&(_, g, _)) => [
11655 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11656 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11657 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11658 ],
11659 None => [
11660 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
11661 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
11662 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
11663 ],
11664 };
11665 // The alphabet `tile::write_motion_mode` will code this block's
11666 // symbol against, mirrored term for term (libaom
11667 // `motion_mode_allowed`).
11668 let warp_alphabet = warp_on()
11669 && crate::decode::num_proj_ref(
11670 grid,
11671 mi_row,
11672 mi_col,
11673 8,
11674 8,
11675 mi_cols,
11676 mi_rows,
11677 info.ref_frame,
11678 fctx,
11679 ) >= 1;
11680 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
11681 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
11682 if crate::envflags::env_flag!("EC_AV1_OBMC") {
11683 if let Some(pred) = obmc_prediction(
11684 grid,
11685 (mi_row, mi_col),
11686 (mi_rows, mi_cols),
11687 (x, y),
11688 BLOCK,
11689 info.mv,
11690 &refs,
11691 planes,
11692 reference.width,
11693 fctx,
11694 ) {
11695 candidates.push((1, pred));
11696 }
11697 }
11698 if warp_alphabet {
11699 if let Some(pred) = warp_prediction(
11700 grid,
11701 (mi_row, mi_col),
11702 (mi_rows, mi_cols),
11703 (x, y),
11704 BLOCK,
11705 info.mv,
11706 info.ref_frame,
11707 planes,
11708 fctx,
11709 ) {
11710 candidates.push((2, pred));
11711 }
11712 }
11713 for (motion, pred) in candidates {
11714 let luma_trial = luma.code_from_prediction(
11715 x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone,
11716 TxbSet::Luma32Inter,
11717 );
11718 let u = chroma[0].code_from_prediction(
11719 x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone,
11720 chroma_set,
11721 );
11722 let v = chroma[1].code_from_prediction(
11723 x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone,
11724 chroma_set,
11725 );
11726 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11727 && u.levels.iter().all(|&l| l == 0)
11728 && v.levels.iter().all(|&l| l == 0);
11729 let cost = luma_trial.sse
11730 + u.sse
11731 + v.sse
11732 + search.lambda
11733 * (skip_bits(skip)
11734 + intra_inter_bits(true)
11735 + best.mode_bits
11736 + mm(motion)
11737 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
11738 if cost < best.cost + search.lambda * mm(motion_won) {
11739 motion_won = motion;
11740 best = Candidate {
11741 cost,
11742 luma: luma_trial,
11743 u,
11744 v,
11745 mode: DC_PRED,
11746 skip,
11747 mode_bits: best.mode_bits,
11748 inter: best.inter,
11749 };
11750 }
11751 }
11752 }
11753 // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`,
11754 // default OFF): the four 16x16 units of `commit_inter_luma` against the
11755 // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured
11756 // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and
11757 // RE-MEASURED it at 0.05, where the rate weight is half of what rejected
11758 // it, and it is worse again on the deciding native table: film 1080p
11759 // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the
11760 // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off --
11761 // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1
11762 // up against rav1e. (640x384 reads it slightly the other way, +70.0/
11763 // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and
11764 // +28.4/+47.4/-4.0 -- the native table decides.)
11765 //
11766 // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks,
11767 // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing
11768 // either, and the census names the row: the split units' own set
11769 // `Luma16Inter` is priced within 1.4% of what it is written at in every
11770 // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced
11771 // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting,
11772 // so a perfect pricer would split even more, and more splitting is what
11773 // measured worse. The four extra txb_skip/eob symbols simply cost more
11774 // ladder bytes than the local RD saves. The flat 32x32 transform stays.
11775 // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection
11776 // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the
11777 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
11778 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
11779 // plain translation, which is not the prediction it was priced from.
11780 let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) {
11781 Some(info) => {
11782 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11783 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11784 None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
11785 };
11786 let second = info.ref1.and_then(|r| {
11787 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
11788 (
11789 info.mv1,
11790 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11791 )
11792 })
11793 });
11794 match info.ref1.is_some() && second.is_none() {
11795 true => {
11796 luma.commit(x, y, BLOCK, &best.luma);
11797 (best.luma.levels.clone(), 0, 0.0, Vec::new())
11798 }
11799 false => commit_inter_luma(
11800 luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second,
11801 fctx,
11802 ),
11803 }
11804 }
11805 None => {
11806 luma.commit(x, y, BLOCK, &best.luma);
11807 (best.luma.levels.clone(), 0, 0.0, Vec::new())
11808 }
11809 };
11810 // lane-txrd: chroma follows the luma type the var-tx/type search chose.
11811 let [bu, bv] = match (best.inter.filter(|_| motion_won == 0), luma_tx_types.first().copied()) {
11812 (Some(info), Some(t)) => {
11813 let (ou, ov) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11814 Some(&(_, g, _)) => (
11815 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11816 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11817 ),
11818 None => (
11819 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
11820 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
11821 ),
11822 };
11823 let sec = info.ref1.and_then(|r| {
11824 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
11825 (
11826 info.mv1,
11827 [
11828 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11829 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11830 ],
11831 )
11832 })
11833 });
11834 recode_inter_chroma(
11835 chroma, (x, y), BLOCK, info.mv, [ou, ov], sec, search, chroma_set, t, fctx,
11836 )
11837 .unwrap_or([best.u, best.v])
11838 }
11839 _ => [best.u, best.v],
11840 };
11841 let best = Candidate { u: bu, v: bv, ..best };
11842 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
11843 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
11844 (
11845 BlockCoeffs {
11846 luma_tx_types,
11847 angle_delta_y: 0,
11848 cfl_alphas: None,
11849 filter_intra: None,
11850 luma: coeffs(&levels, BLOCK),
11851 u: coeffs(&best.u.levels, BLOCK / 2),
11852 v: coeffs(&best.v.levels, BLOCK / 2),
11853 mode: best.mode,
11854 uv_mode: DC_PRED,
11855 skip: best.skip,
11856 inter: best.inter,
11857 motion_mode: motion_won,
11858 eight: None,
11859 dv: None,
11860 palette: None,
11861 palette_uv: None,
11862 tx_depth,
11863 },
11864 best.cost + dcost,
11865 )
11866}
11867
11868/// lane-av1tpl: the strength `k` of the temporal lambda weighting
11869/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
11870/// is what every measurement before this lane was taken on. Swept by
11871/// `EC_AV1_TPL=<k>`.
11872///
11873/// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs
11874/// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane
11875/// baseline exactly, which is the control the rest of the table is read
11876/// against:
11877///
11878/// | k | film 1080p | film 2160p | screen |
11879/// |---|---|---|---|
11880/// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 |
11881/// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 |
11882/// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** |
11883/// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 |
11884/// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 |
11885///
11886/// 0.5 is the only arm that is at least flat on every row and down on five of
11887/// the six columns, so it ships as the default. The lookahead pass that feeds
11888/// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
11889const TPL_STRENGTH: f64 = 0.5;
11890
11891/// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec
11892/// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then
11893/// byte-identical to the pre-lane one); anything else is the `delta_q_res`
11894/// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off.
11895///
11896/// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has
11897/// nothing to vary the quantizer BY and codes no delta syntax at all.
11898fn deltaq_res_log2() -> Option<u8> {
11899 match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
11900 u8::MAX => {}
11901 4 => return None,
11902 r => return Some(r),
11903 }
11904 match crate::envflags::var("EC_AV1_DELTAQ").ok().as_deref().map(str::trim) {
11905 Some("0") => None,
11906 Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3),
11907 None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4),
11908 }
11909}
11910
11911/// A PROCESS-GLOBAL [`deltaq_res_log2`] override that wins over both the
11912/// environment and the preset -- `u8::MAX` = unset, `4` = off. The gate that
11913/// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
11914/// speed presets take, because the streams every other test pins move under
11915/// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).
11916static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 =
11917 std::sync::atomic::AtomicU8::new(u8::MAX);
11918
11919/// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
11920#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
11921pub(crate) fn set_deltaq_res(res_log2: Option<u8>) {
11922 DELTAQ_OVERRIDE.store(
11923 res_log2.unwrap_or(u8::MAX),
11924 std::sync::atomic::Ordering::Relaxed,
11925 );
11926}
11927
11928/// How much of the derived qindex step is actually taken
11929/// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation).
11930fn deltaq_k() -> f64 {
11931 crate::envflags::var("EC_AV1_DELTAQ_K")
11932 .ok()
11933 .and_then(|v| v.trim().parse::<f64>().ok())
11934 .filter(|k| k.is_finite() && *k >= 0.0)
11935 .unwrap_or(1.0)
11936}
11937
11938/// The largest qindex the map may move a superblock by, either way
11939/// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective
11940/// deltaq around a quarter of the base qindex).
11941fn deltaq_clamp() -> i32 {
11942 crate::envflags::var("EC_AV1_DELTAQ_CLAMP")
11943 .ok()
11944 .and_then(|v| v.trim().parse::<i32>().ok())
11945 .filter(|c| (0..=63).contains(c))
11946 .unwrap_or(16)
11947}
11948
11949/// The qindex a lambda factor `f` asks for, derived rather than fitted.
11950///
11951/// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the
11952/// square of the quantizer step (`encode_inter_frame`'s own
11953/// `lambda = .. * step * step`), so the step this superblock wants is
11954/// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the
11955/// step ratio is inverted through the table itself -- the index whose `ac_q`
11956/// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted
11957/// constant. `k` scales the resulting step (1.0 takes all of it), `clamp`
11958/// bounds it, and the answer is snapped onto the `res` grid so that every
11959/// superblock's qindex is congruent to `base` and the coded delta is a whole
11960/// number of steps.
11961fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 {
11962 let base_ac = f64::from(ac_q(8, i32::from(base)));
11963 let target = base_ac * f.max(1e-6).sqrt();
11964 let exact = (1..=255)
11965 .min_by(|&a, &b| {
11966 let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs();
11967 d(a).partial_cmp(&d(b)).expect("ac_q is finite")
11968 })
11969 .expect("the qindex range is not empty")
11970 - i32::from(base);
11971 let want = (exact as f64 * k).round() as i32;
11972 // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound
11973 // and need not be a whole number of steps, and clamping afterwards would
11974 // hand back a qindex that is not congruent to `base`.
11975 let max_steps = clamp / res;
11976 let steps = (want as f64 / f64::from(res)).round() as i32;
11977 let delta = steps.clamp(-max_steps, max_steps) * res;
11978 (i32::from(base) + delta).clamp(1, 255) as u8
11979}
11980
11981/// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1`
11982/// objective would, from the SAME tpl dependence ratio our own map already
11983/// carries (`EC_AV1_DQ_TPL=1`).
11984///
11985/// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a
11986/// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the
11987/// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very
11988/// same expression at frame scope) by it, and asks
11989/// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose
11990/// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and
11991/// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`,
11992/// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way
11993/// libaom reads `r0`. The offset is clamped to libaom's own
11994/// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than
11995/// twice the +-16 qindex [`deltaq_for_factor`] allows.
11996///
11997/// Two things differ from [`deltaq_for_factor`] and both are the point of the
11998/// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw
11999/// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed,
12000/// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is
12001/// much stronger for the same map. `strength` scales the offset.
12002fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 {
12003 let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6);
12004 let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt();
12005 let exact = (1..=255)
12006 .min_by(|&a, &b| {
12007 let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs();
12008 d(a).partial_cmp(&d(b)).expect("dc_q is finite")
12009 })
12010 .expect("the qindex range is not empty")
12011 - i32::from(base);
12012 let want = exact as f64 * strength;
12013 // Snapped onto the `res` grid first, so the coded delta is a whole number
12014 // of steps, then bounded by libaom's own `res * 9 - 1`.
12015 let max_steps = (res * 9 - 1) / res;
12016 let steps = (want / f64::from(res)).round() as i32;
12017 let delta = steps.clamp(-max_steps, max_steps) * res;
12018 (i32::from(base) + delta).clamp(1, 255) as u8
12019}
12020
12021/// The frame-level `r0` libaom's objective divides by: the log-mean of
12022/// `1 + r` over the frame's cells, minus 1.
12023fn tpl_frame_ratio(ratio: &[f64]) -> f64 {
12024 if ratio.is_empty() {
12025 return 0.0;
12026 }
12027 let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64;
12028 m.exp() - 1.0
12029}
12030
12031/// The [`deltaq_libaom`] strength, or `None` to keep the shipped
12032/// [`deltaq_for_factor`] derivation.
12033///
12034/// `EC_AV1_DQ_TPL=0`/`1` forces the mapping either way and `EC_AV1_DQ_TPL_K`
12035/// the strength (default 1.0 = libaom's own offset when the flag armed it);
12036/// with neither set the preset decides, see [`crate::speed::DQ_TPL_K`].
12037fn dq_tpl_strength(level: DqLevel) -> Option<f64> {
12038 let m = dq_level_k()[level as usize];
12039 let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K")
12040 .ok()
12041 .and_then(|v| v.trim().parse::<f64>().ok())
12042 .filter(|k| k.is_finite() && *k >= 0.0);
12043 let base = match crate::envflags::var("EC_AV1_DQ_TPL").ok().as_deref().map(str::trim) {
12044 Some("0") => return None,
12045 Some(_) => Some(env_k.unwrap_or(1.0)),
12046 None => env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))),
12047 };
12048 base.map(|k| k * m).filter(|k| *k > 0.0)
12049}
12050
12051/// lane-arfq: which pyramid level the frame asking for a
12052/// [`dq_tpl_strength`] sits at. The KEY frame is not here on purpose: it
12053/// codes no `delta_q` syntax at all (the whole lever lives in
12054/// [`encode_inter_frame`]), so a per-level strength cannot touch it -- the
12055/// key's allocation is [`crate::encoder::Pyramid::key_q_offset`]'s job.
12056#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12057pub(crate) enum DqLevel {
12058 /// The mini-GOP's own hidden `ALTREF`, which every other frame of the
12059 /// group predicts from (directly or through the mid level).
12060 TopArf = 0,
12061 /// A hidden mid/quarter-point `ALTREF`, read by the leaves around it.
12062 MidArf = 1,
12063 /// A shown leaf -- and every frame of the flat, non-pyramid path.
12064 Leaf = 2,
12065}
12066
12067/// The per-level multiplier on the [`dq_tpl_strength`] the preset carries:
12068/// `EC_AV1_DQ_K=<top arf>:<mid arf>:<leaf>`, else
12069/// [`crate::speed::DQ_LEVEL_K`]. Three fields, not four: the key frame codes
12070/// no `delta_q` (see [`DqLevel`]).
12071fn dq_level_k() -> [f64; 3] {
12072 dq_level_k_of(crate::envflags::var("EC_AV1_DQ_K").ok().as_deref())
12073}
12074
12075/// [`dq_level_k`]'s parse, pure: a missing spec, a missing field and an
12076/// unparseable one all keep [`crate::speed::DQ_LEVEL_K`]'s entry.
12077fn dq_level_k_of(spec: Option<&str>) -> [f64; 3] {
12078 let mut k = crate::speed::DQ_LEVEL_K;
12079 if let Some(spec) = spec {
12080 for (slot, field) in k.iter_mut().zip(spec.split(':')) {
12081 if let Some(v) =
12082 field.trim().parse::<f64>().ok().filter(|v: &f64| v.is_finite() && *v >= 0.0)
12083 {
12084 *slot = v;
12085 }
12086 }
12087 }
12088 k
12089}
12090
12091/// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the
12092/// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones
12093/// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and
12094/// the same tpl map -- and which of the two the frame actually coded.
12095fn dq_census() -> bool {
12096 crate::envflags::var("EC_AV1_DQ_CENSUS").ok().as_deref().map(str::trim) == Some("1")
12097}
12098
12099/// The histogram/extent summary [`dq_census`] prints for one set of offsets.
12100fn dq_summary(offsets: &[i32]) -> String {
12101 let n = offsets.len().max(1);
12102 let (lo, hi) = offsets.iter().fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o)));
12103 let nz = offsets.iter().filter(|&&o| o != 0).count();
12104 let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64;
12105 let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64;
12106 let mut levels: Vec<i32> = offsets.to_vec();
12107 levels.sort_unstable();
12108 levels.dedup();
12109 format!(
12110 "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}",
12111 offsets.len(),
12112 levels.len()
12113 )
12114}
12115
12116/// How many DISTINCT per-superblock quantizer levels the last inter frame's
12117/// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter
12118/// (class `gate-blind-to-feature`: every exactness assert below passes on a
12119/// grid that is one flat value, i.e. on no delta_q at all). Process-global
12120/// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
12121/// keeps the LARGEST count seen since the last read.
12122static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12123
12124/// [`DELTAQ_LEVELS`], reset to 0.
12125#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
12126pub(crate) fn take_deltaq_levels() -> usize {
12127 DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
12128}
12129
12130/// This superblock's search state: the quantizer it is coded at, and the
12131/// lambda that quantizer implies. RD lambda goes as the square of the step,
12132/// which is exactly the relation [`deltaq_for_factor`] inverted, so with no
12133/// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour
12134/// before lane-deltaq).
12135fn sb_q_search<'m>(
12136 sb_q: &[u8],
12137 sb_cols: usize,
12138 base_q_idx: u8,
12139 (sb_r, sb_c): (usize, usize),
12140 base: Search<'m>,
12141) -> Search<'m> {
12142 let q = sb_q[sb_r * sb_cols + sb_c];
12143 let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx)));
12144 Search { base_q_idx: q, lambda: base.lambda * ratio * ratio, ..base }
12145}
12146
12147fn tpl_strength() -> f64 {
12148 std::env::var("EC_AV1_TPL")
12149 .ok()
12150 .and_then(|v| v.parse::<f64>().ok())
12151 .filter(|k| k.is_finite() && *k >= 0.0)
12152 .unwrap_or(TPL_STRENGTH)
12153}
12154
12155/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
12156/// the frame being coded. 1 turns the weighting off; 2 is the shipped
12157/// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under
12158/// [`tpl_propagating`], which is the map that can actually use them and is
12159/// the default since lane-av1tpl3, so the default window is 8. Swept by
12160/// `EC_AV1_TPL_D=<d>`.
12161///
12162/// The streaming facade holds `depth - 1` pictures back so it feeds
12163/// `encode_inter_frame` the same window `encode_sequence` does; both read
12164/// THIS function, so the two paths cannot disagree about the window.
12165pub(crate) const TPL_DEPTH: usize = 8;
12166
12167/// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
12168/// 0.5 is libaom's own square-root compression of its dependence ratio.
12169const TPL_POWER: f64 = 0.5;
12170
12171/// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the
12172/// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`.
12173///
12174/// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom
12175/// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map
12176/// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]:
12177///
12178/// | k | D | p | film 1080p | film 2160p | screen |
12179/// |---|---|---|---|---|---|
12180/// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 |
12181/// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 |
12182/// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 |
12183/// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 |
12184/// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 |
12185/// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 |
12186/// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 |
12187/// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 |
12188/// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 |
12189/// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** |
12190/// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 |
12191/// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 |
12192///
12193/// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of
12194/// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside
12195/// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p
12196/// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was
12197/// 0.1..0.4 UP on film 2160p, so it shipped off.
12198///
12199/// lane-av1tpl3 found why and turned it on. The denominator is the cell's own
12200/// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour
12201/// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of
12202/// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1
12203/// wherever the window leans on a flat bar, which is exactly where coding is
12204/// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio
12205/// (libaom's own granularity) puts a busy cell's denominator next to the flat
12206/// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed
12207/// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on
12208/// the same native gate (baseline = the shipped one-frame map):
12209///
12210/// | arm | film 1080p | film 2160p | screen |
12211/// |---|---|---|---|
12212/// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 |
12213/// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 |
12214/// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 |
12215/// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 |
12216/// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 |
12217/// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 |
12218/// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 |
12219/// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 |
12220/// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 |
12221/// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** |
12222///
12223/// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4,
12224/// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships
12225/// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The
12226/// floor is a real effect on the ratio and never a win once the aggregation
12227/// is in -- the aggregation is the same fix, done where libaom does it.
12228fn tpl_propagating() -> bool {
12229 std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0")
12230}
12231
12232pub(crate) fn tpl_depth() -> usize {
12233 std::env::var("EC_AV1_TPL_D")
12234 .ok()
12235 .and_then(|v| v.parse::<usize>().ok())
12236 .filter(|d| *d >= 1)
12237 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH))
12238 .max(1)
12239}
12240
12241/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
12242/// process, so the gate can price it against the encode it rides on.
12243static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
12244
12245/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
12246/// the winning displacement and its SAD.
12247///
12248/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
12249/// the left/above winners, first-best tie-break. Built once on the frame's
12250/// own thread and read-only afterwards, so it cannot make a tile's bytes
12251/// depend on the thread count.
12252fn tpl_coarse_pass(
12253 cur: &[u8],
12254 next: &[u8],
12255 width: usize,
12256 height: usize,
12257) -> Vec<((i32, i32), u32)> {
12258 let (cells_x, cells_y) = (width / 16, height / 16);
12259 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
12260 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
12261 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
12262 return u32::MAX;
12263 }
12264 let (sx, sy) = (sx as usize, sy as usize);
12265 let mut sum = 0u32;
12266 for r in 0..16 {
12267 let a = &next[(by + r) * width + bx..][..16];
12268 let b = &cur[(sy + r) * width + sx..][..16];
12269 sum += a.iter().zip(b).map(|(&p, &q)| u32::from(p.abs_diff(q))).sum::<u32>();
12270 }
12271 sum
12272 };
12273 let mut out = Vec::with_capacity(cells_x * cells_y);
12274 let mut above = vec![(0i32, 0i32); cells_x];
12275 for cy in 0..cells_y {
12276 let mut left = (0i32, 0i32);
12277 for cx in 0..cells_x {
12278 let (bx, by) = (cx * 16, cy * 16);
12279 let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
12280 for cand in [left, above[cx]] {
12281 if cand != (0, 0) {
12282 let s = sad(bx, by, cand);
12283 if s < best.0 {
12284 best = (s, cand);
12285 }
12286 }
12287 }
12288 for step in [8i32, 4, 2, 1] {
12289 let centre = best.1;
12290 for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
12291 let mv = (centre.0 + dx, centre.1 + dy);
12292 if mv.0.abs() > 32 || mv.1.abs() > 32 {
12293 continue;
12294 }
12295 let s = sad(bx, by, mv);
12296 if s < best.0 {
12297 best = (s, mv);
12298 }
12299 }
12300 }
12301 left = best.1;
12302 above[cx] = best.1;
12303 out.push((best.1, best.0));
12304 }
12305 }
12306 out
12307}
12308
12309/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
12310/// transform: here, the mean absolute deviation of the cell from its own DC.
12311/// It is the denominator every propagated cost is read against, so only its
12312/// SHAPE across the frame matters, not its scale.
12313fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
12314 let (cells_x, cells_y) = (width / 16, height / 16);
12315 let mut out = Vec::with_capacity(cells_x * cells_y);
12316 for cy in 0..cells_y {
12317 for cx in 0..cells_x {
12318 let (bx, by) = (cx * 16, cy * 16);
12319 let mut sum = 0u32;
12320 for r in 0..16 {
12321 sum += frame[(by + r) * width + bx..][..16].iter().map(|&p| u32::from(p)).sum::<u32>();
12322 }
12323 let dc = ((sum + 128) / 256) as u8;
12324 let mut cost = 0u32;
12325 for r in 0..16 {
12326 cost += frame[(by + r) * width + bx..][..16]
12327 .iter()
12328 .map(|&p| u32::from(p.abs_diff(dc)))
12329 .sum::<u32>();
12330 }
12331 out.push(cost);
12332 }
12333 }
12334 out
12335}
12336
12337/// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS
12338/// frame the next one predicts from, per 16x16 cell -- each cell of `next`
12339/// splats its own area, at its winning displacement, onto the (at most four)
12340/// cells of `cur` it lands on. 1.0 is "referenced exactly once".
12341fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
12342 let start = std::time::Instant::now();
12343 let (cells_x, cells_y) = (width / 16, height / 16);
12344 let pass = tpl_coarse_pass(cur, next, width, height);
12345 let mut area = vec![0.0f64; cells_x * cells_y];
12346 for cy in 0..cells_y {
12347 for cx in 0..cells_x {
12348 let (mv, _) = pass[cy * cells_x + cx];
12349 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
12350 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
12351 for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
12352 let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
12353 for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
12354 let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
12355 area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
12356 }
12357 }
12358 }
12359 }
12360 TPL_NANOS.fetch_add(
12361 start.elapsed().as_nanos() as u64,
12362 std::sync::atomic::Ordering::Relaxed,
12363 );
12364 area
12365}
12366
12367/// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda
12368/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
12369/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
12370/// Decreasing in referenced-ness (a block the next frame leans on is coded
12371/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
12372/// total lambda scale is only redistributed, never moved -- a global move is
12373/// the thing lane-av1lambda already measured inert.
12374fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
12375 let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
12376 let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
12377 let mut out = Vec::with_capacity(sb_cols * sb_rows);
12378 for sr in 0..sb_rows {
12379 for sc in 0..sb_cols {
12380 let mut sum = 0.0;
12381 for r in 0..4 {
12382 for c in 0..4 {
12383 sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
12384 }
12385 }
12386 let w_rel = sum / 16.0 / mean;
12387 out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
12388 }
12389 }
12390 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
12391 let mut hist = [0usize; 8];
12392 for w in map {
12393 hist[((w / mean * 2.0) as usize).min(7)] += 1;
12394 }
12395 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
12396 eprintln!(
12397 "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
12398 sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
12399 map.len(),
12400 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
12401 );
12402 }
12403 out
12404}
12405
12406/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
12407/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
12408/// much of the WHOLE lookahead window leans on that cell.
12409///
12410/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
12411/// coarse pass gives a displacement and an inter cost; a cell's own
12412/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
12413/// cell well saves the frames that predict from it -- and it is splatted,
12414/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
12415/// displacement lands on. Walking `f` from the far end of the window back to
12416/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
12417/// area map could not do at all.
12418///
12419/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
12420/// factor over the frame is exactly 1: a cell the window leans on is coded
12421/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
12422/// scale only moves around, never up or down -- a global move is what
12423/// lane-av1lambda already measured inert.
12424/// Returns the per-cell lambda factors AND the per-cell dependence ratio
12425/// `mc_dep / intra` they were derived from -- the second half is what
12426/// [`deltaq_libaom`] needs, since the factor alone has been through a
12427/// mean normalisation the raw ratio cannot be recovered across.
12428fn tpl_lambda_factors(
12429 frames: &[&[u8]],
12430 width: usize,
12431 height: usize,
12432 k: f64,
12433) -> (Vec<f64>, Vec<f64>) {
12434 let start = std::time::Instant::now();
12435 let (cells_x, cells_y) = (width / 16, height / 16);
12436 let cells = cells_x * cells_y;
12437 let levels = frames.len();
12438 let intra: Vec<Vec<u32>> = frames.iter().map(|f| tpl_intra_costs(f, width, height)).collect();
12439 let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
12440 .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
12441 .collect();
12442 let mut mc_dep = vec![vec![0.0f64; cells]; levels];
12443 for f in (1..levels).rev() {
12444 for cy in 0..cells_y {
12445 for cx in 0..cells_x {
12446 let ci = cy * cells_x + cx;
12447 let (mv, inter) = passes[f - 1][ci];
12448 let saved = f64::from(intra[f][ci].saturating_sub(inter));
12449 let propagate = saved + mc_dep[f][ci];
12450 if propagate <= 0.0 {
12451 continue;
12452 }
12453 // The 16x16 window of the PREVIOUS frame this cell predicted
12454 // from, spread over the cells it overlaps.
12455 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
12456 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
12457 for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
12458 let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
12459 for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
12460 let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
12461 mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
12462 }
12463 }
12464 }
12465 }
12466 }
12467 // The tail compression `p`: `mc_dep/intra` is a ratio with a very long
12468 // tail (a nearly flat cell the window leans on has a tiny denominator),
12469 // and at p = 1 that tail slams into the clamp. libaom reads its own
12470 // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P`
12471 // sweeps the exponent, 1 being the raw ratio.
12472 let power = std::env::var("EC_AV1_TPL_P")
12473 .ok()
12474 .and_then(|v| v.parse::<f64>().ok())
12475 .filter(|p| p.is_finite() && *p > 0.0)
12476 .unwrap_or(TPL_POWER);
12477 // lane-av1tpl3, the three shape fixes, each its own knob so the gate can
12478 // read them apart. `SB` and `LOG` are the shipped shape (set the knob to
12479 // `0` to take either back out); `FLOOR` defaults to off.
12480 //
12481 // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the
12482 // frame's own mean intra cost. A cell of flat content has a near-zero
12483 // MAD, so its ratio explodes exactly where coding is cheap.
12484 // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra
12485 // and mc_dep are summed over the 64x64 superblock first -- libaom's
12486 // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not
12487 // per-16x16 numbers), which is also what makes the ratio survive one
12488 // flat cell next to a busy one.
12489 // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through
12490 // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail
12491 // harder than the `p` exponent alone can.
12492 let floor_frac = std::env::var("EC_AV1_TPL_FLOOR")
12493 .ok()
12494 .and_then(|v| v.parse::<f64>().ok())
12495 .filter(|f| f.is_finite() && *f >= 0.0)
12496 .unwrap_or(0.0);
12497 let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0");
12498 let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0");
12499 let intra_mean =
12500 intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64;
12501 let floor = floor_frac * intra_mean;
12502 let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0);
12503 // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by
12504 // every cell under it. The edge groups are partial and summed as they are.
12505 let ratio: Vec<f64> = if sb_agg {
12506 let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4));
12507 let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows];
12508 for cy in 0..cells_y {
12509 for cx in 0..cells_x {
12510 let e = &mut sb[(cy / 4) * sb_cols + cx / 4];
12511 e.0 += mc_dep[0][cy * cells_x + cx];
12512 e.1 += denom(cy * cells_x + cx);
12513 }
12514 }
12515 (0..cells)
12516 .map(|c| {
12517 let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4];
12518 dep / den.max(1.0)
12519 })
12520 .collect()
12521 } else {
12522 (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect()
12523 };
12524 let mut out: Vec<f64> = ratio
12525 .iter()
12526 .map(|&r| {
12527 let r = if log_beta { (1.0 + r).log2() } else { r };
12528 (1.0 + k * r).powf(-power)
12529 })
12530 .collect();
12531 let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
12532 for f in &mut out {
12533 *f = (*f / mean).clamp(0.25, 4.0);
12534 }
12535 TPL_NANOS.fetch_add(
12536 start.elapsed().as_nanos() as u64,
12537 std::sync::atomic::Ordering::Relaxed,
12538 );
12539 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
12540 let mut hist = [0usize; 8];
12541 for &f in &out {
12542 hist[((f * 4.0) as usize).min(7)] += 1;
12543 }
12544 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
12545 let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
12546 eprintln!(
12547 "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
12548 range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
12549 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
12550 );
12551 }
12552 (out, ratio)
12553}
12554
12555/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
12556/// references name, which slot it refreshes, whether it is shown when it is
12557/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
12558/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
12559/// 0/2 alternation, every frame shown, every reference in the past).
12560///
12561/// The sign bias is carried rather than derived here because only the caller
12562/// knows what order hint each slot holds; it is armed onto the tile writer
12563/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
12564/// the writer scans the same stacks the decoder will.
12565#[derive(Debug, Clone, Copy)]
12566pub(crate) struct PyramidFrame {
12567 /// The slot `LAST_FRAME` (and every reference this encoder does not name
12568 /// apart) reads.
12569 pub last_slot: u8,
12570 /// The single slot `refresh_frame_flags` sets.
12571 pub self_slot: u8,
12572 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
12573 /// pyramid, which is what makes `sign_bias`'s last entry true.
12574 pub altref_slot: u8,
12575 /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past
12576 /// picture (the leaf chain alternates its refresh between two slots, so
12577 /// the frame before `LAST` is still intact). `None` leaves
12578 /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder
12579 /// wrote before, and the caller then passes no `last2` picture either.
12580 pub last2_slot: Option<u8>,
12581 /// `show_frame`: false for a hidden frame, output later by a
12582 /// `show_existing_frame` header.
12583 pub show_frame: bool,
12584 /// lane-arfq: which level's `delta_q` strength this frame reads
12585 /// ([`DqLevel`]) -- the caller knows it, since the top ARF and the mid
12586 /// one share `Level::Arf` and differ only by their q offset.
12587 pub dq_level: DqLevel,
12588 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
12589 pub sign_bias: crate::mvstack::SignBiasTable,
12590}
12591
12592/// lane-arfpred: the temporal filter of a top ARF's SOURCE picture, libaom's
12593/// `temporal_filter` in the small: every 16x16 luma block of `src` is
12594/// motion-compensated from each picture of `window` (the group's own display
12595/// neighbours, nearest first) and averaged in with weight
12596/// `exp(-mse / strength)`, so a neighbour that matches badly contributes
12597/// nothing and one that matches well cancels the grain the block's residual
12598/// would otherwise have to code.
12599///
12600/// `strength` is [`crate::speed::ARF_TF`]; `0` never reaches here. Chroma
12601/// rides the luma block's own vector (halved), which is what libaom does at
12602/// this block size. The picture is the SUPERBLOCK-padded one, so the 16x16
12603/// grid tiles it exactly.
12604///
12605/// Priced before it was built by `encode::tests::arf_pred_census`: on film B
12606/// the filtered ARF's prediction SAD at lag 8 is 11.7% below the unfiltered
12607/// one's (film A 5.9%) with the two past neighbours at strength 30, and the
12608/// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the
12609/// quality the ARF is coded at, so the substitution itself costs little.
12610// lane-lookahead: the CALLER sizes `window` (`ARF_TF_WIN` past neighbours and
12611// `ARF_TF_WIN_FUT` future ones); this takes every picture in it.
12612pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture {
12613 const SIDE: usize = 16;
12614 let neighbours: Vec<&Picture> = window
12615 .iter()
12616 .filter(|p| p.width == src.width && p.height == src.height)
12617 .collect();
12618 if neighbours.is_empty() || strength <= 0.0 {
12619 return src.clone();
12620 }
12621 let mut out = src.clone();
12622 // SAD of `src`'s block at `(bx, by)` against `r` displaced by `mv`, or
12623 // `None` when the displaced block leaves the picture.
12624 let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
12625 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
12626 if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width {
12627 return None;
12628 }
12629 let (sy, sx) = (sy as usize, sx as usize);
12630 let mut acc = 0u64;
12631 for row in 0..SIDE {
12632 let c = &src.y[(by + row) * src.width + bx..][..SIDE];
12633 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
12634 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
12635 }
12636 Some((acc, (sy, sx)))
12637 };
12638 // The log-step diamond `arf_pred_census` priced this with.
12639 let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> {
12640 let mut best = sad(r, bx, by, (0, 0))?;
12641 let mut centre = (0isize, 0isize);
12642 let mut step = 16isize;
12643 while step >= 1 {
12644 let from = centre;
12645 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
12646 let mv = (from.0 + dy * step, from.1 + dx * step);
12647 if let Some(s) = sad(r, bx, by, mv) {
12648 if s.0 < best.0 {
12649 best = s;
12650 centre = mv;
12651 }
12652 }
12653 }
12654 step /= 2;
12655 }
12656 Some(best.1)
12657 };
12658 let (cw, ch) = (src.width / 2, src.height / 2);
12659 for by in (0..src.height).step_by(SIDE) {
12660 for bx in (0..src.width).step_by(SIDE) {
12661 if by + SIDE > src.height || bx + SIDE > src.width {
12662 continue;
12663 }
12664 let mut y_acc = vec![0f64; SIDE * SIDE];
12665 let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]];
12666 let mut wsum = 1.0f64;
12667 // Chroma keeps its OWN weight sum: an edge block whose halved
12668 // vector leaves the chroma plane contributes to luma only, and
12669 // dividing chroma by the luma sum would darken it (class
12670 // `metric blind to a plane`, on the encoder side).
12671 let mut cwsum = 1.0f64;
12672 for row in 0..SIDE {
12673 for col in 0..SIDE {
12674 y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]);
12675 }
12676 }
12677 for row in 0..SIDE / 2 {
12678 for col in 0..SIDE / 2 {
12679 let i = (by / 2 + row) * cw + bx / 2 + col;
12680 c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]);
12681 c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]);
12682 }
12683 }
12684 for r in &neighbours {
12685 let Some((sy, sx)) = search(r, bx, by) else { continue };
12686 let mut sse = 0f64;
12687 for row in 0..SIDE {
12688 for col in 0..SIDE {
12689 let d = f64::from(src.y[(by + row) * src.width + bx + col])
12690 - f64::from(r.y[(sy + row) * r.width + sx + col]);
12691 sse += d * d;
12692 }
12693 }
12694 let w = (-sse / (SIDE * SIDE) as f64 / strength).exp();
12695 for row in 0..SIDE {
12696 for col in 0..SIDE {
12697 y_acc[row * SIDE + col] +=
12698 w * f64::from(r.y[(sy + row) * r.width + sx + col]);
12699 }
12700 }
12701 // Chroma reads the luma vector halved; a block on the picture
12702 // edge whose halved vector would leave the chroma plane is
12703 // left to luma alone rather than clamped to a different
12704 // displacement than the luma it must stay registered with.
12705 let (cy, cx) = (sy / 2, sx / 2);
12706 if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw {
12707 for row in 0..SIDE / 2 {
12708 for col in 0..SIDE / 2 {
12709 let i = (cy + row) * cw + cx + col;
12710 c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]);
12711 c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]);
12712 }
12713 }
12714 cwsum += w;
12715 }
12716 wsum += w;
12717 }
12718 for row in 0..SIDE {
12719 for col in 0..SIDE {
12720 out.y[(by + row) * src.width + bx + col] =
12721 (y_acc[row * SIDE + col] / wsum).round() as u16;
12722 }
12723 }
12724 for row in 0..SIDE / 2 {
12725 for col in 0..SIDE / 2 {
12726 let i = (by / 2 + row) * cw + bx / 2 + col;
12727 out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16;
12728 out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16;
12729 }
12730 }
12731 }
12732 }
12733 out
12734}
12735
12736/// Encodes one picture as an inter frame predicting from `reference`'s
12737/// reconstruction, which the caller decoded (or, for the frame right after
12738/// the key frame, is the key frame's own reconstruction).
12739pub(crate) fn encode_inter_frame(
12740 picture: &Picture,
12741 reference: &Picture,
12742 base_q_idx: u8,
12743 deadzone: f64,
12744 order_hint: u32,
12745 // The order hint each of the seven `ref_frame_idx` entries names, which a
12746 // decoder reads out of its own reference state -- only spec 5.9.22's
12747 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
12748 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
12749 // callers that follow this crate's own flat slot plan.
12750 order_hints: [u32; 7],
12751 render: (usize, usize),
12752 // The tables this frame's writer starts from: what the previous frame
12753 // stored into the slot this one's `primary_ref_frame` names. `None`
12754 // starts from the defaults, which is right only for the frame straight
12755 // after a key frame.
12756 start_cdfs: Option<&crate::cdf_state::Cdfs>,
12757 // The key frame's own (padded) reconstruction, which every frame of the
12758 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
12759 // with `LAST_FRAME` alone, exactly as before.
12760 golden: Option<&Picture>,
12761 // The frame two back, held in the slot this frame is about to refresh
12762 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
12763 // inter frames of a GOP, where the frame two back IS the key frame.
12764 altref: Option<&Picture>,
12765 // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown
12766 // frame BEFORE `reference` on the leaf chain, offered to the 32x32
12767 // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF`
12768 // take. `None` (every caller but the pyramid leaves) codes the frame
12769 // with the reference set unchanged.
12770 last2: Option<&Picture>,
12771 fctx: &crate::decode::FrameCtx,
12772 // Where this frame sits in the coding-order pyramid; `None` is the flat
12773 // one-shown-frame-per-picture stream this encoder wrote before.
12774 pyramid: Option<PyramidFrame>,
12775 // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
12776 // them), padded like this one -- the lookahead window the per-block
12777 // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
12778 // EMPTY slice codes the frame at one lambda, as before.
12779 lookahead: &[Picture],
12780) -> Result<Encoded> {
12781 picture.check()?;
12782 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
12783 return Err(Error::unsupported(
12784 "AV1 encode",
12785 "an inter frame is coded only for a picture that is a whole number \
12786 of 64x64 superblocks -- the inter tile writer never splits a \
12787 superblock's partition below that",
12788 ));
12789 }
12790 if reference.width != picture.width || reference.height != picture.height {
12791 return Err(Error::unsupported(
12792 "AV1 encode",
12793 "the reference picture must be the same size as the one being coded",
12794 ));
12795 }
12796
12797 // The single slot this crate's inter frames ever predict from or
12798 // refresh (`inter_frame_headers`'s contract): every frame both reads and
12799 // overwrites slot 0, so the frame just coded is always what the next one
12800 // predicts against.
12801 const LAST_SLOT: u8 = 0;
12802 // Slot 0 and slot 2 alternate so the frame two back survives one more
12803 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
12804 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
12805 // in the very slot it will overwrite.
12806 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
12807 let last_slot = pyramid.map_or(
12808 if order_hint <= 1 {
12809 LAST_SLOT
12810 } else if (order_hint - 1) % 2 == 1 {
12811 0
12812 } else {
12813 2
12814 },
12815 |p| p.last_slot,
12816 );
12817 // `render`, not `picture.width`/`picture.height`: `picture` here is
12818 // already padded to a whole number of superblocks (`encode_sequence`'s
12819 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
12820 // every true-edge clamp downstream) must come from the frame's real,
12821 // unpadded size, same as `key_frame_headers_colour` takes `render` and
12822 // not the padded picture in `encode_key_frame_inner`.
12823 let (seq, mut header) = inter_frame_headers_slots(
12824 render.0,
12825 render.1,
12826 base_q_idx,
12827 order_hint,
12828 last_slot,
12829 self_slot,
12830 match pyramid {
12831 Some(p) => p.altref_slot,
12832 None if altref.is_some() => self_slot,
12833 None => GOLDEN_SLOT,
12834 },
12835 )?;
12836 header.render_width = render.0 as u32;
12837 header.render_height = render.1 as u32;
12838 // lane-refs: this frame's motion-compensation kernel, written into the
12839 // header AND armed on the context every prediction reads, in one place so
12840 // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched
12841 // tile decodes to different pixels than the encoder scored).
12842 header.interpolation_filter = frame_interp_filter();
12843 fctx.interp_filter.set(mc::InterpFilterKind::from_header(header.interpolation_filter));
12844 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
12845 // The order hint behind each `ref_frame_idx` entry. The flat path's own
12846 // slot plan (`inter_frame_headers_slots`) is: every reference but
12847 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
12848 // `ALTREF_FRAME`, which reads the frame two back when there is one;
12849 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
12850 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
12851 header.order_hints = order_hints;
12852 // lane-last2: `inter_frame_headers_slots` points every un-named
12853 // reference at `last_slot`; the pyramid's leaf chain retains a second,
12854 // older picture and names it here. The caller's `sign_bias` /
12855 // `order_hints` entry 1 is derived from this same slot, so the stack
12856 // scans and `skipModeAllowed` read what the decoder will.
12857 if let Some(slot) = pyramid.and_then(|p| p.last2_slot) {
12858 header.ref_frame_idx[1] = slot;
12859 }
12860 header.reference_select = reference_select();
12861 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
12862 // per-reference order-hint distance is read by the block SEARCH, which
12863 // runs long before the writer arms these (the distance-scaled search step
12864 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
12865 // never reached the tool).
12866 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
12867 // lane-hpmv: armed here for the same reason the order hints are -- the
12868 // block SEARCH reads it (its eighth-pel stage) long before the writer.
12869 let hp_mv = header.allow_high_precision_mv;
12870 crate::tile::arm_high_precision_mv(hp_mv);
12871 if let Some(p) = pyramid {
12872 header.show_frame = p.show_frame;
12873 header.showable_frame = !p.show_frame;
12874 header.ref_frame_sign_bias = p.sign_bias;
12875 }
12876 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
12877 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
12878 // block inside this frame codes and searches its own `tx_depth`, the same
12879 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
12880 let tx_select = tx_select() && tx_select_inter();
12881 if tx_select {
12882 header.tx_mode = TxMode::Select;
12883 }
12884
12885 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
12886 // lane-palw: the encoder's own in-process reconstruct reads its palette
12887 // colour-index maps back through `decode::palette_onscreen`, which takes
12888 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
12889 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
12890 // them here so the reconstruct clamps a block cut by the frame edge
12891 // exactly as the writer now does.
12892 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
12893 fctx.seg_mi_dims.set(frame_mi_dims);
12894 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
12895 // here (see `encode_key_frame_inner`).
12896 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
12897 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
12898 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
12899 // This frame's own `allow_screen_content_tools`. It can only be set when
12900 // the SEQUENCE offers the bit at all, which is the key frame's decision
12901 // ([`SEQ_SCREEN`]): a frame header that contradicts
12902 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
12903 // encode.
12904 let screen = seq_screen()
12905 && screen_content(&picture_y8, picture.width, true_width, true_height);
12906 header.allow_screen_content_tools = screen;
12907 // lane-txi, as on the key frame: the header bit the writer's own
12908 // `Cdfs` then reads for every luma `tx_type` symbol.
12909 header.reduced_tx_set = !wide_tx_set(screen);
12910 // lane-intertx, desync (a): the frame context this value is read back
12911 // through ([`decode::reduce_inherited_chroma_tx_type`] inside
12912 // `recode_inter_chroma`, and every inter decode helper the search's own
12913 // trial decode shares) must carry THIS frame's bit, not whatever the
12914 // previous frame's trial decode last left in the shared cell -- a stale
12915 // `true` here narrows the chroma allowance the search reconstructs
12916 // against under the one the header's bit actually allows.
12917 fctx.reduced_tx_set_inter.set(header.reduced_tx_set);
12918 // The search prices coefficients against the tables this frame's writer
12919 // starts from, not against the defaults (lane-av1txbits) -- but only on a
12920 // frame the screen detector said no to (lane-av1price2): armed HERE, after
12921 // `screen` exists, and again on every search/tile worker below.
12922 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
12923 let mut luma = Plane {
12924 source: &picture_y8,
12925 reconstruction: vec![128; picture_y8.len()],
12926 width: picture.width,
12927 height: picture.height,
12928 true_width,
12929 true_height,
12930 tile_x0: 0,
12931 tile_y0: 0,
12932 tile_x1: picture.width,
12933 tile_y1: picture.height,
12934 ctx: CoefCtxMap::default(),
12935 };
12936 let mut chroma = [
12937 Plane {
12938 source: &picture_u8,
12939 reconstruction: vec![128; picture_u8.len()],
12940 width: picture.width / 2,
12941 height: picture.height / 2,
12942 true_width: true_width / 2,
12943 true_height: true_height / 2,
12944 tile_x0: 0,
12945 tile_y0: 0,
12946 tile_x1: picture.width / 2,
12947 tile_y1: picture.height / 2,
12948 ctx: CoefCtxMap::default(),
12949 },
12950 Plane {
12951 source: &picture_v8,
12952 reconstruction: vec![128; picture_v8.len()],
12953 width: picture.width / 2,
12954 height: picture.height / 2,
12955 true_width: true_width / 2,
12956 true_height: true_height / 2,
12957 tile_x0: 0,
12958 tile_y0: 0,
12959 tile_x1: picture.width / 2,
12960 tile_y1: picture.height / 2,
12961 ctx: CoefCtxMap::default(),
12962 },
12963 ];
12964
12965 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
12966 let top_arf = matches!(
12967 pyramid,
12968 Some(p) if p.dq_level == DqLevel::TopArf
12969 );
12970 let arfmode_v = arfmode();
12971 let search = Search {
12972 base_q_idx,
12973 deadzone,
12974 lambda: lambda_scale()
12975 * match pyramid {
12976 Some(p) if !p.show_frame => hidden_lambda_factor(),
12977 _ => 1.0,
12978 }
12979 * step
12980 * step,
12981 modes: &KEY_FRAME_MODES,
12982 top_k: prune_top_k_inter(),
12983 screen,
12984 // lane-arfmode: the group's own anchor ([`DqLevel::TopArf`], whose
12985 // offset is the pyramid's own `arf_q_offset`) reads its leaf offer
12986 // set from [`crate::speed::ARFMODE`]; every other frame -- the mid
12987 // and quarter hidden frames, the leaves, the flat path -- keeps the
12988 // full set.
12989 arf_leaf_intra: !top_arf || arfmode_v & 1 == 0,
12990 arf_leaf8: !top_arf || arfmode_v & 2 == 0,
12991 arf_leaf_compound: !top_arf || arfmode_v & 4 == 0,
12992 };
12993 let mode_bits_table = inter_mode_bits();
12994 // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
12995 // this frame the NEXT one predicts from. Off (`None`) without a
12996 // lookahead picture or at strength 0.
12997 let tpl_k = tpl_strength();
12998 let window: Vec<&Picture> = lookahead
12999 .iter()
13000 .take_while(|n| n.width == picture.width && n.height == picture.height)
13001 .collect();
13002 let tpl_sources: Vec<Vec<u8>> =
13003 window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect();
13004 let tpl_cells_x = picture.width / 16;
13005 // `.1` is the propagating map's raw per-cell dependence ratio, which only
13006 // [`deltaq_libaom`] reads; the one-frame area map has no such ratio.
13007 let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> =
13008 (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| {
13009 if tpl_propagating() {
13010 let mut frames: Vec<&[u8]> = vec![&picture_y8];
13011 frames.extend(tpl_sources.iter().map(Vec::as_slice));
13012 let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k);
13013 (f, Some(r))
13014 } else {
13015 // The shipped map is one factor per 64x64; it is spread over that
13016 // superblock's own 16 cells so the application site below (which
13017 // averages the four cells of a 32x32 block) reads exactly the
13018 // superblock factor, whichever map fed it.
13019 let map =
13020 tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height);
13021 let cells_y = picture.height / 16;
13022 let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k);
13023 let f: Vec<f64> = (0..tpl_cells_x * cells_y)
13024 .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4])
13025 .collect();
13026 (f, None)
13027 }
13028 });
13029 let (tpl_factors, tpl_ratio) = match tpl_both {
13030 Some((f, r)) => (Some(f), r),
13031 None => (None, None),
13032 };
13033
13034 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
13035 // coding surface's: `blocks` carries one entry per 32x32 block the tile
13036 // writer will actually visit, same count it checks `blocks.len()`
13037 // against, which is fewer than the padded surface's own block count
13038 // whenever the true size is not a 64x64 multiple.
13039 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
13040 let (cols, rows) = (cols as usize, rows as usize);
13041 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
13042 // lane-deltaq: one absolute qindex per 64x64 superblock, from the same
13043 // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present
13044 // only when the map is, and `delta_q_res` follows straight into the frame
13045 // header (`write_delta_q_params`) and into the tile writer's own plan.
13046 // Not on a screen frame ([`b64_residual`]'s content gate): lane-dq3
13047 // measured the per-superblock quantizer as a win on both films and a
13048 // 0.5 loss vs libaom on the desktop capture, so a frame that set
13049 // `allow_screen_content_tools` codes no delta syntax at all and stays
13050 // byte-identical to the pre-lane encoder.
13051 // lane-arfq: the level whose `delta_q` strength this frame reads; the
13052 // flat path (no pyramid) is a leaf.
13053 let dq_level = pyramid.map_or(DqLevel::Leaf, |p| p.dq_level);
13054 let deltaq_res: Option<i32> = tpl_factors
13055 .as_ref()
13056 .filter(|_| !screen)
13057 .and(deltaq_res_log2().map(|r| 1i32 << r));
13058 // The same 16-cell mean the superblock's own lambda takes, clamped to the
13059 // map the frame actually has -- read over the factors or over the raw
13060 // dependence ratios, whichever mapping is asking.
13061 let sb_mean = |m: &[f64], sb: usize| {
13062 let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols);
13063 (0..16)
13064 .map(|i| {
13065 let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4);
13066 m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)]
13067 })
13068 .sum::<f64>()
13069 / 16.0
13070 };
13071 // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the
13072 // raw dependence ratio; without it (and always without a ratio map, i.e.
13073 // on the one-frame area map) the shipped derivation stands.
13074 let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio);
13075 let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option<f64>| -> u8 {
13076 match (libaom, tpl_ratio.as_deref(), r_frame) {
13077 (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res),
13078 _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res),
13079 }
13080 };
13081 let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
13082 (Some(f), Some(res)) => {
13083 let libaom = dq_tpl_strength(dq_level);
13084 let mut g: Vec<u8> =
13085 (0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect();
13086 // lane-b128m: under 128 superblocks the delta_q syntax is coded
13087 // ONCE per 128 root (the reader's own unit), so all four 64x64
13088 // cells of a root have to be searched -- and quantized -- at the
13089 // one qindex the root's top-left cell codes.
13090 if sb128_on() {
13091 for sb_r in 0.._sb_rows {
13092 for sb_c in 0..sb_cols {
13093 let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)];
13094 g[sb_r * sb_cols + sb_c] = q;
13095 }
13096 }
13097 }
13098 Some(g)
13099 }
13100 _ => None,
13101 };
13102 // lane-dq census: both mappings on the SAME superblocks, whether or not
13103 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever
13104 // off, and the census then prices the default `res = 4` grid).
13105 if dq_census() {
13106 if let Some(f) = &tpl_factors {
13107 let res = deltaq_res.unwrap_or(4);
13108 let off = |libaom: Option<f64>| -> Vec<i32> {
13109 (0..sb_cols * _sb_rows)
13110 .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
13111 .collect()
13112 };
13113 let strength = dq_tpl_strength(dq_level);
13114 let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
13115 let coded = match (deltaq_res.is_some(), strength) {
13116 (false, _) => "none".to_string(),
13117 (true, None) => "ours".to_string(),
13118 (true, Some(k)) => format!("libaom k={k}"),
13119 };
13120 eprintln!(
13121 "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
13122 sb_cols * _sb_rows,
13123 r_frame.unwrap_or(f64::NAN),
13124 dq_summary(&ours),
13125 dq_summary(&aom),
13126 );
13127 }
13128 }
13129 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
13130 header.delta.q_present = true;
13131 header.delta.q_res = res.trailing_zeros() as u8;
13132 }
13133 // lane-rectdq: what the tile writer's own `arm_delta_q` is armed with
13134 // below, so the root search prices the group the writer really codes.
13135 let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0);
13136 if let Some(g) = &sb_q {
13137 let mut levels: Vec<u8> = g.clone();
13138 levels.sort_unstable();
13139 levels.dedup();
13140 DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed);
13141 }
13142 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
13143 // This frame's tile grid, as in `encode_key_frame_inner`.
13144 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
13145 let layout =
13146 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
13147 header.tile_info = tile_info_of(&layout, 1);
13148 let header_tile_info = header.tile_info.clone();
13149 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
13150 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
13151 // once per frame (lane-av1rd2), not once per block, which is a whole
13152 // plane's map per 32x32 block and now per leaf too.
13153 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
13154 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
13155 // availability -- intra edges and the MV stack's scans alike -- already
13156 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
13157 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
13158 // giving each job its own planes and its own `MiGrid` therefore leaves
13159 // every decision, and so every coded bit, exactly where the whole-frame
13160 // loop left it, at any tile count and any thread count.
13161 let (frame_width, frame_height) = (picture.width, picture.height);
13162 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
13163 let [cb, cr] = &mut chroma;
13164 let chroma_out = [
13165 crate::par::Shared::new(&mut cb.reconstruction),
13166 crate::par::Shared::new(&mut cr.reconstruction),
13167 ];
13168 let search_tile = |index: usize,
13169 fctx: &crate::decode::FrameCtx|
13170 -> Result<Vec<(usize, Quadrant)>> {
13171 // Thread-local, and this job may be running on a `search_tiles`
13172 // worker: `ref_distance`'s order-hint distance (the scaled motion
13173 // search step) is read by the SEARCH, so every worker arms it or the
13174 // tile's bits depend on the thread count.
13175 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
13176 crate::tile::arm_high_precision_mv(hp_mv);
13177 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
13178 let rect = layout.rect(index);
13179 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
13180 let mut chroma = [
13181 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
13182 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
13183 ];
13184 clip_planes_to_tile(&mut luma, &mut chroma, rect);
13185 let mut grid = MiGrid::new(mi_cols, mi_rows);
13186 grid.set_sign_bias(sign_bias);
13187 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
13188 // built once per tile job (`obmc_prediction`).
13189 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
13190 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
13191 obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2;
13192 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
13193 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
13194 grid.set_tile_bounds(
13195 rect.mi_row0 as usize,
13196 rect.mi_col0 as usize,
13197 rect.mi_row1 as usize,
13198 rect.mi_col1 as usize,
13199 );
13200 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
13201 // lane-b128: under a 128x128 superblock the search walks the roots the
13202 // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root),
13203 // not plain raster -- a search that visits BL before TR builds every mv
13204 // stack and neighbour context off blocks the writer has not coded yet,
13205 // which is what made the write-time drl clamp fire at all (lane-sb128b).
13206 // At a 64 superblock the two orders are identical and this is the same
13207 // raster loop as before.
13208 let sb128_search = sb128_on();
13209 let root_step = if sb128_search { 2 } else { 1 };
13210 let mut roots: Vec<(usize, usize)> = Vec::new();
13211 {
13212 let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize);
13213 let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize);
13214 let mut r = r0;
13215 while r < r1 {
13216 let mut c = c0;
13217 while c < c1 {
13218 roots.push((r, c));
13219 c += root_step;
13220 }
13221 r += root_step;
13222 }
13223 }
13224 for (root_r, root_c) in roots {
13225 // The 64x64 cells of this root, in the writer's own order.
13226 let cells: Vec<(usize, usize)> = if sb128_search {
13227 [(0, 0), (0, 1), (1, 0), (1, 1)]
13228 .into_iter()
13229 .map(|(dr, dc)| (root_r + dr, root_c + dc))
13230 .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize)
13231 .collect()
13232 } else {
13233 vec![(root_r, root_c)]
13234 };
13235 // What the four cells below really cost, against which the whole
13236 // 128x128 candidate is weighed.
13237 let mark128 = blocks.len();
13238 let mut root_cost = 0.0f64;
13239 // The 128 root's own compound pairs, at its 32x32-mi window (the 64
13240 // root builds the same list one size down, per superblock).
13241 let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13242 if header.reference_select && b128_compound() && !screen && sb128_search {
13243 [
13244 (crate::mvstack::GOLDEN_FRAME, golden),
13245 (crate::mvstack::ALTREF_FRAME, altref),
13246 ]
13247 .into_iter()
13248 .filter_map(|(r, pic)| {
13249 pic.map(|p| {
13250 (
13251 r,
13252 p,
13253 crate::mvstack::find_mv_stack_compound(
13254 &grid,
13255 root_r * 16,
13256 root_c * 16,
13257 32,
13258 32,
13259 (crate::mvstack::LAST_FRAME, r),
13260 mi_cols,
13261 mi_rows,
13262 grid.sign_bias_table(),
13263 &[(0, 0); 7],
13264 None,
13265 ),
13266 )
13267 })
13268 })
13269 .collect()
13270 } else {
13271 Vec::new()
13272 };
13273 let root128 = (sb128_search && b128_root() && cells.len() == 4)
13274 .then(|| search_root_128(
13275 &mut luma,
13276 &mut chroma,
13277 &grid,
13278 (root_r, root_c),
13279 (rows, cols),
13280 (header.mi_cols, header.mi_rows),
13281 search,
13282 &tpl_factors,
13283 sb_q.as_ref(),
13284 sb_cols,
13285 tpl_cells_x,
13286 base_q_idx,
13287 dq_res,
13288 reference,
13289 &root_compound,
13290 fctx,
13291 ))
13292 .flatten();
13293 // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts
13294 // are priced; the cheaper one competes with the NONE block and with
13295 // the four superblocks below.
13296 let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed);
13297 let root_rect = (sb128_search && b128_rect() && cells.len() == 4)
13298 .then(|| {
13299 let mut best: Option<(bool, _)> = None;
13300 for horz in [true, false] {
13301 if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 {
13302 continue;
13303 }
13304 let Some(found) = search_root_128_rect(
13305 &mut luma,
13306 &mut chroma,
13307 &mut grid,
13308 (root_r, root_c),
13309 (rows, cols),
13310 (header.mi_cols, header.mi_rows),
13311 search,
13312 &tpl_factors,
13313 sb_q.as_ref(),
13314 sb_cols,
13315 tpl_cells_x,
13316 base_q_idx,
13317 dq_res,
13318 reference,
13319 &root_compound,
13320 horz,
13321 fctx,
13322 ) else {
13323 continue;
13324 };
13325 if best.as_ref().is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0) {
13326 best = Some((horz, found));
13327 }
13328 }
13329 best
13330 })
13331 .flatten();
13332 // lane-ab128: and the same root as one of the four AB shapes -- two
13333 // 64x64 pieces plus one 128x64 / 64x128 half. All four are priced;
13334 // the cheapest joins the candidate list below.
13335 let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed);
13336 let root_ab = (sb128_search
13337 && (b128_ab() || forced_ab != 0)
13338 && cells.len() == 4
13339 && forced_rect == 0)
13340 .then(|| {
13341 let mut best: Option<(usize, _)> = None;
13342 for symbol in 4..=7usize {
13343 if forced_ab != 0 && usize::from(forced_ab) != symbol {
13344 continue;
13345 }
13346 let Some(found) = search_root_128_ab(
13347 &mut luma,
13348 &mut chroma,
13349 &mut grid,
13350 (root_r, root_c),
13351 (rows, cols),
13352 (header.mi_cols, header.mi_rows),
13353 search,
13354 &tpl_factors,
13355 sb_q.as_ref(),
13356 sb_cols,
13357 tpl_cells_x,
13358 base_q_idx,
13359 reference,
13360 &root_compound,
13361 symbol,
13362 fctx,
13363 ) else {
13364 continue;
13365 };
13366 if best.as_ref().is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0) {
13367 best = Some((symbol, found));
13368 }
13369 }
13370 best
13371 })
13372 .flatten();
13373 for (sb_r, sb_c) in cells {
13374 // lane-b64: the whole superblock as ONE 64x64 block, tried before
13375 // its quadrants are (`search_skip_64`) and compared against the
13376 // four of them below. Only a superblock wholly inside the true
13377 // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the
13378 // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask
13379 // only that the block's half is inside, and the trial is ranked
13380 // over the inside part alone ([`Plane::block_sse`]).
13381 let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK);
13382 let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols
13383 && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows
13384 && x64 + SUPERBLOCK <= luma.true_width
13385 && y64 + SUPERBLOCK <= luma.true_height;
13386 let edge_inside = b64_edge()
13387 && crate::tile::has_half(
13388 sb_c as u32 * crate::tile::SB_MI,
13389 crate::tile::SB_MI,
13390 header.mi_cols,
13391 )
13392 && crate::tile::has_half(
13393 sb_r as u32 * crate::tile::SB_MI,
13394 crate::tile::SB_MI,
13395 header.mi_rows,
13396 );
13397 let sb64_legal = b64_root()
13398 && sb_r * 2 + 1 < rows
13399 && sb_c * 2 + 1 < cols
13400 && (whole_inside || edge_inside);
13401 // One lambda for the whole superblock, the same mean the 32x32
13402 // level takes over its own four tpl cells: the 64-vs-four-32
13403 // comparison below weighs one cost against four, so both sides
13404 // have to be priced at the same lambda.
13405 let sb_search = match &tpl_factors {
13406 // lane-deltaq: with a per-superblock quantizer the lambda
13407 // comes from that quantizer, not from the raw map factor --
13408 // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped.
13409 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),
13410 Some(f) if sb64_legal => {
13411 let mean = (0..16)
13412 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
13413 .sum::<f64>()
13414 / 16.0;
13415 Search { lambda: search.lambda * mean, ..search }
13416 }
13417 _ => search,
13418 };
13419 let mark = blocks.len();
13420 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
13421 let mut sb_cost = 0.0f64;
13422 if sb64_legal {
13423 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
13424 let (mi_row, mi_col) = (sb_r * 16, sb_c * 16);
13425 let stack =
13426 find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows);
13427 // lane-b64b: the `LAST` + extra-reference pairs at this
13428 // superblock's own 16x16-mi window, the same stacks the tile
13429 // writer's `Whole64` arm rebuilds. Empty unless the frame
13430 // codes `reference_select`, which is what gates the syntax.
13431 // `!screen` for the same reason the residual arm is gated
13432 // there ([`b64_residual`]): a desktop capture's superblocks
13433 // are flat runs the skip arm already codes for nothing, and
13434 // MEASURED, compound at the root cost it +33.4/-23.8 ->
13435 // +33.7/-23.6 while both film rows gained (step 1's table).
13436 let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13437 if header.reference_select && b64_compound() && !screen {
13438 [
13439 (crate::mvstack::GOLDEN_FRAME, golden),
13440 (crate::mvstack::ALTREF_FRAME, altref),
13441 ]
13442 .into_iter()
13443 .filter_map(|(r, pic)| {
13444 pic.map(|p| {
13445 (
13446 r,
13447 p,
13448 crate::mvstack::find_mv_stack_compound(
13449 &grid,
13450 mi_row,
13451 mi_col,
13452 16,
13453 16,
13454 (crate::mvstack::LAST_FRAME, r),
13455 mi_cols,
13456 mi_rows,
13457 grid.sign_bias_table(),
13458 &[(0, 0); 7],
13459 None,
13460 ),
13461 )
13462 })
13463 })
13464 .collect()
13465 } else {
13466 Vec::new()
13467 };
13468 if let Some((cost, block)) = search_skip_64(
13469 &mut luma,
13470 &mut chroma,
13471 (x64, y64),
13472 (SUPERBLOCK, SUPERBLOCK),
13473 &sb_search,
13474 b64_residual() && !screen,
13475 reference,
13476 &stack,
13477 &sb_compound,
13478 fctx,
13479 ) {
13480 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
13481 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
13482 let cost = cost
13483 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
13484 sb64 = Some((cost, block, after));
13485 }
13486 }
13487 // A superblock whose 64x64 trial already codes almost nothing per
13488 // pixel is taken outright and its quadrants are never searched --
13489 // the same `split_rd_breakout` shape the 32x32 level uses one
13490 // size up, and where this lever BUYS wall instead of spending it.
13491 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
13492 split_rd_breakout_at(
13493 b64_breakout_threshold(),
13494 *c,
13495 SUPERBLOCK,
13496 sb_search.lambda,
13497 )
13498 });
13499 for quadrant in 0..if early64 { 0 } else { 4 } {
13500 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
13501 // lane-av1tpl2: this 32x32 block's own lambda -- every RD
13502 // decision under it (partition, mode, tx, motion) reads
13503 // `search.lambda`, so scaling the one field here scales all
13504 // of them. 32x32 and not the 16x16 the map is built at
13505 // because the whole-vs-split comparison right below weighs
13506 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
13507 // would make those two numbers incomparable.
13508 let search = match &tpl_factors {
13509 // lane-deltaq: the quantizer is a SUPERBLOCK-level
13510 // symbol, so all four quadrants take their superblock's
13511 // own qindex and the lambda it implies. No granularity is
13512 // lost: the shipped map (`EC_AV1_TPL_SB`) is already one
13513 // factor per superblock, shared by its sixteen cells.
13514 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),
13515 Some(f) => {
13516 let mean = (0..4)
13517 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
13518 .sum::<f64>()
13519 / 4.0;
13520 Search { lambda: search.lambda * mean, ..search }
13521 }
13522 None => search,
13523 };
13524 // Same filter as the tile writer's: a quadrant whose own mi
13525 // origin is not inside the true frame is never coded.
13526 if r32 >= rows || c32 >= cols {
13527 continue;
13528 }
13529 // spec `decode_partition`'s hasRows/hasCols recomputed at this
13530 // 32x32 block's own half (`crate::tile::has_half`), same as
13531 // the key frame search: the true frame edge can fall inside a
13532 // quadrant a superblock-level check already let through, and
13533 // such a quadrant cannot be left whole -- it must split into
13534 // the 16x16 leaves that are actually inside the true frame
13535 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
13536 // arm).
13537 let (has_cols32, has_rows32) = (
13538 crate::tile::has_half(
13539 c32 as u32 * crate::tile::BLOCK_MI,
13540 crate::tile::BLOCK_MI,
13541 header.mi_cols,
13542 ),
13543 crate::tile::has_half(
13544 r32 as u32 * crate::tile::BLOCK_MI,
13545 crate::tile::BLOCK_MI,
13546 header.mi_rows,
13547 ),
13548 );
13549 if has_cols32 && has_rows32 {
13550 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
13551 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
13552 let stack =
13553 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
13554 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
13555 (crate::mvstack::LAST2_FRAME, last2),
13556 (crate::mvstack::GOLDEN_FRAME, golden),
13557 (crate::mvstack::ALTREF_FRAME, altref),
13558 ]
13559 .into_iter()
13560 .filter_map(|(r, pic)| {
13561 pic.map(|p| {
13562 (
13563 r,
13564 p,
13565 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
13566 )
13567 })
13568 })
13569 .collect();
13570 let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
13571 .iter()
13572 .map(|(r, p, st)| (*r, *p, st))
13573 .collect();
13574 // The COMPOUND stack of each `LAST` + extra pair, off the
13575 // same grid (and the same armed sign bias) the tile writer
13576 // rebuilds it from. Empty unless this frame codes
13577 // `reference_select`, which is what gates the syntax.
13578 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13579 if header.reference_select {
13580 extra_stacks
13581 .iter()
13582 .map(|&(r, p, _)| {
13583 (
13584 r,
13585 p,
13586 crate::mvstack::find_mv_stack_compound(
13587 &grid,
13588 mi_row,
13589 mi_col,
13590 8,
13591 8,
13592 (crate::mvstack::LAST_FRAME, r),
13593 mi_cols,
13594 mi_rows,
13595 grid.sign_bias_table(),
13596 &[(0, 0); 7],
13597 None,
13598 ),
13599 )
13600 })
13601 .collect()
13602 } else {
13603 Vec::new()
13604 };
13605
13606 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
13607 let (block, mut cost_whole) = search_inter_block(
13608 &mut luma,
13609 &mut chroma,
13610 (x, y),
13611 &search,
13612 &mode_bits_table,
13613 reference,
13614 &stack,
13615 &extra,
13616 &compound,
13617 &grid,
13618 (mi_row, mi_col),
13619 (mi_rows, mi_cols),
13620 fctx,
13621 );
13622 cost_whole += search.lambda * partition_bits(BLOCK, false);
13623 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
13624
13625 // What four 16x16 leaves cost instead (spec
13626 // PARTITION_SPLIT at BLOCK_32X32, which
13627 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
13628 // already writes for a straddling quadrant). Each leaf is
13629 // searched against the reconstruction -- and the `mi`
13630 // grid -- the ones before it left, exactly as the writer
13631 // and the decoder will read them.
13632 //
13633 // A block the whole-32 search left skipped (no residual
13634 // at all) is not offered the split: libaom prunes the
13635 // same way at cpu-used 6, and it is where the wall would
13636 // otherwise go on static content.
13637 let leaf_positions: Vec<(usize, usize)> = (0..4)
13638 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
13639 .collect();
13640 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
13641 crate::tile::has_half(
13642 sc as u32 * crate::tile::SUB_MI,
13643 crate::tile::SUB_MI,
13644 header.mi_cols,
13645 ) && crate::tile::has_half(
13646 sr as u32 * crate::tile::SUB_MI,
13647 crate::tile::SUB_MI,
13648 header.mi_rows,
13649 )
13650 });
13651 // The breakout above: a 32x32 block that codes almost
13652 // nothing is not offered the split at all.
13653 let breakout = split_breakout_coeffs();
13654 let split = (!block.skip
13655 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
13656 && (breakout == 0 || block.luma.len() > 4 * breakout)
13657 && leaves_legal
13658 && split_inter_blocks())
13659 .then(|| {
13660 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
13661 let mut cost = search.lambda * partition_bits(BLOCK, true);
13662 let mut leaves = Vec::with_capacity(4);
13663 for &(sr, sc) in &leaf_positions {
13664 let (mi_row, mi_col) = (sr * 4, sc * 4);
13665 let (lx, ly) = (sc * SUB, sr * SUB);
13666 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
13667 let stack = find_mv_stack(
13668 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
13669 );
13670 let cstacks = leaf_compound_stacks(
13671 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
13672 header.reference_select, golden, altref,
13673 );
13674 let (leaf, leaf_cost) = code_square_inter(
13675 &mut luma,
13676 &mut chroma,
13677 (lx, ly),
13678 SUB,
13679 &search,
13680 &mode_bits_table,
13681 reference,
13682 &stack,
13683 &cstacks,
13684 &grid,
13685 (mi_row, mi_col),
13686 (mi_rows, mi_cols),
13687 &obmc_refs,
13688 fctx,
13689 );
13690 let leaf_cost = leaf_cost
13691 + search.lambda * partition_bits(SUB, false);
13692 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
13693
13694 // And what four 8x8 leaves cost instead --
13695 // the same tree one step further down, which
13696 // the writer codes as a real PARTITION_SPLIT
13697 // at BLOCK_16X16 (lane-av1rd2). Same
13698 // skipped-block prune as the level above.
13699 let eight = (!leaf.skip
13700 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
13701 && (breakout == 0 || leaf.luma.len() > breakout)
13702 && split_inter_8()
13703 // lane-arfmode: arm 2 makes 16x16 the top
13704 // ARF's leaf floor -- the RD-optional 8x8
13705 // comparison is not offered. Counted only
13706 // when every other prune let it through,
13707 // so the counter means "refused", not
13708 // "never considered". The spec-forced 8x8s
13709 // at a straddling 16x16 (the
13710 // `sub_positions` path below) are a
13711 // different site and stay.
13712 && (search.arf_leaf8 || arfmode_hit_and_no()))
13713 .then(|| {
13714 restore(
13715 &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base,
13716 );
13717 let mut cost8 = search.lambda
13718 * (partition_bits(SUB, true)
13719 + 4.0 * partition_bits(8, false));
13720 let mut eight = Vec::with_capacity(4);
13721 for i in 0..4 {
13722 let (mr, mc) =
13723 (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
13724 let stack8 = find_mv_stack(
13725 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
13726 );
13727 let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13728 if header.reference_select && leaf_compound() {
13729 [
13730 (crate::mvstack::GOLDEN_FRAME, golden),
13731 (crate::mvstack::ALTREF_FRAME, altref),
13732 ]
13733 .into_iter()
13734 .filter_map(|(r, pic)| {
13735 pic.map(|p| {
13736 (
13737 r,
13738 p,
13739 crate::mvstack::find_mv_stack_compound(
13740 &grid, mr, mc, 2, 2,
13741 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
13742 grid.sign_bias_table(), &[(0, 0); 7], None,
13743 ),
13744 )
13745 })
13746 })
13747 .collect()
13748 } else {
13749 Vec::new()
13750 };
13751 let (leaf8, cost) = code_square_inter(
13752 &mut luma,
13753 &mut chroma,
13754 (lx + (i % 2) * 8, ly + (i / 2) * 8),
13755 8,
13756 &search,
13757 &mode_bits_table,
13758 reference,
13759 &stack8,
13760 &cstacks8,
13761 &grid,
13762 (mr, mc),
13763 (mi_rows, mi_cols),
13764 &obmc_refs,
13765 fctx,
13766 );
13767 cost8 += cost;
13768 record_mi(&mut grid, mr, mc, 2, leaf8.inter, leaf8.skip);
13769 eight.push(leaf8);
13770 }
13771 (eight, cost8)
13772 });
13773 match eight {
13774 Some((eight, cost8)) if cost8 < leaf_cost => {
13775 partition_hit(3);
13776 cost += cost8;
13777 leaves.push(BlockCoeffs {
13778 eight: Some(eight),
13779 ..BlockCoeffs::default()
13780 });
13781 continue;
13782 }
13783 Some(_) => restore(
13784 &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf,
13785 ),
13786 None => {}
13787 }
13788 partition_hit(2);
13789 cost += leaf_cost;
13790 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter, leaf.skip);
13791 leaves.push(leaf);
13792 }
13793 (leaves, cost)
13794 });
13795 if let Some((leaves, cost)) = split {
13796 if cost < cost_whole {
13797 // The leaves' own `mi` cells are already in the
13798 // grid, and their reconstruction is what the
13799 // planes hold.
13800 partition_hit(1);
13801 sb_cost += cost;
13802 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
13803 continue;
13804 }
13805 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
13806 }
13807 partition_hit(0);
13808 sb_cost += cost_whole;
13809 record_mi(&mut grid, mi_row, mi_col, 8, block.inter, block.skip);
13810 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
13811 } else {
13812 // The sub-positions actually inside the true frame, same
13813 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
13814 let sub_positions: Vec<(usize, usize)> = (0..4)
13815 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
13816 .filter(|&(sr, sc)| {
13817 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
13818 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
13819 })
13820 .collect();
13821 // Each leaf searches intra against its own `NEARESTMV`
13822 // candidate (`code_square_inter`), same real-inter choice
13823 // `search_inter_block` makes for a whole 32x32 block, at
13824 // this leaf's own 4x4-mi mv-stack window -- unless the
13825 // leaf's own half itself straddles the true edge, which
13826 // it codes as two (or one, at a true corner) 8x8 leaves
13827 // (`crate::tile::write_leaf8`'s inter counterpart),
13828 // mirroring the key frame search's straddling-16x16
13829 // handling above (lane-av1inter8).
13830 let mut leaves = Vec::with_capacity(sub_positions.len());
13831 for (sr, sc) in sub_positions {
13832 let (has_cols16, has_rows16) = (
13833 crate::tile::has_half(
13834 sc as u32 * crate::tile::SUB_MI,
13835 crate::tile::SUB_MI,
13836 header.mi_cols,
13837 ),
13838 crate::tile::has_half(
13839 sr as u32 * crate::tile::SUB_MI,
13840 crate::tile::SUB_MI,
13841 header.mi_rows,
13842 ),
13843 );
13844 if has_cols16 && has_rows16 {
13845 let (x, y) = (sc * SUB, sr * SUB);
13846 let (mi_row, mi_col) = (sr * 4, sc * 4);
13847 let stack = find_mv_stack(
13848 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
13849 );
13850 let cstacks = leaf_compound_stacks(
13851 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
13852 header.reference_select, golden, altref,
13853 );
13854 let (block, _) = code_square_inter(
13855 &mut luma,
13856 &mut chroma,
13857 (x, y),
13858 SUB,
13859 &search,
13860 &mode_bits_table,
13861 reference,
13862 &stack,
13863 &cstacks,
13864 &grid,
13865 (mi_row, mi_col),
13866 (mi_rows, mi_cols),
13867 &obmc_refs,
13868 fctx,
13869 );
13870 // One publication point for every coded leaf
13871 // (`record_mi`): this site used to spell the vote
13872 // out with `ref_frame` pinned to LAST and `mv1`
13873 // to (0,0), which is the encoder-grid-drift class
13874 // -- correct only for as long as a leaf can never
13875 // be compound.
13876 record_mi(&mut grid, mi_row, mi_col, 4, block.inter, block.skip);
13877 leaves.push(block);
13878 } else {
13879 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
13880 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
13881 let mut eight = Vec::with_capacity(2);
13882 for i in 0..4 {
13883 let leaf_x = x_sub + (i % 2) * 8;
13884 let leaf_y = y_sub + (i / 2) * 8;
13885 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
13886 continue;
13887 }
13888 let (mi_row, mi_col) =
13889 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
13890 let stack = find_mv_stack(
13891 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
13892 );
13893 let cstacks = leaf_compound_stacks(
13894 &grid, mi_row, mi_col, 2, 2, mi_cols, mi_rows,
13895 header.reference_select, golden, altref,
13896 );
13897 let (leaf, _) = code_square_inter(
13898 &mut luma,
13899 &mut chroma,
13900 (leaf_x, leaf_y),
13901 8,
13902 &search,
13903 &mode_bits_table,
13904 reference,
13905 &stack,
13906 &cstacks,
13907 &grid,
13908 (mi_row, mi_col),
13909 (mi_rows, mi_cols),
13910 &obmc_refs,
13911 fctx,
13912 );
13913 // Same publication point as the 16x16
13914 // straddling leaf above (`record_mi`).
13915 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter, leaf.skip);
13916 eight.push(leaf);
13917 }
13918 leaves.push(BlockCoeffs {
13919 eight: Some(eight),
13920 ..BlockCoeffs::default()
13921 });
13922 }
13923 }
13924 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
13925 }
13926 }
13927 // The 64x64 root against what its four quadrants really cost.
13928 if let Some((cost64, block, after)) = sb64
13929 && (early64
13930 || cost64
13931 < sb_cost
13932 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true))
13933 {
13934 B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13935 if block.inter.is_some_and(|i| i.ref1.is_some()) {
13936 B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13937 }
13938 if !whole_inside {
13939 B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13940 }
13941 blocks.truncate(mark);
13942 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
13943 // Overwrites every 16x16 mi cell the quadrant searches
13944 // published under this superblock, so the next block's stack
13945 // is built off the block that was really coded.
13946 record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter, block.skip);
13947 blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block)));
13948 for q in 1..4 {
13949 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
13950 blocks.push((r32 * cols + c32, Quadrant::Covered));
13951 }
13952 root_cost += cost64;
13953 } else {
13954 root_cost += sb_cost;
13955 }
13956 }
13957 // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's
13958 // `partition_w128` symbol) against what its four superblocks really
13959 // cost, the same weighing the 64 root does one size down. Both sides
13960 // carry their own partition symbol, so the comparison is complete.
13961 // The root candidates, each tagged with the PARTITION symbol its
13962 // writer codes: 0 NONE, 1 HORZ, 2 VERT (lane-b128hv), 4..=7 the AB
13963 // shapes (lane-ab128).
13964 let mut cands: Vec<(f64, f64, usize, Vec<BlockCoeffs>, _)> = Vec::new();
13965 if let Some((c, l, b, a)) = root128 {
13966 cands.push((c, l, 0, vec![b], a));
13967 }
13968 if let Some((horz, (c, l, halves, a))) = root_rect {
13969 cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a));
13970 }
13971 if let Some((symbol, (c, l, pieces, a))) = root_ab {
13972 cands.push((c, l, symbol, pieces.to_vec(), a));
13973 }
13974 // The witness knobs drop every other arm outright: on synthetic
13975 // content the whole block always wins its own comparison.
13976 if forced_rect != 0 {
13977 cands.retain(|c| c.2 == 1 || c.2 == 2);
13978 }
13979 if forced_ab != 0 {
13980 cands.retain(|c| c.2 == usize::from(forced_ab));
13981 }
13982 cands.sort_by(|a, b| a.0.total_cmp(&b.0));
13983 // lane-rectdq class sweep: under a 128 superblock grid the FOUR-
13984 // superblock arm codes the delta_q group too -- the Whole64 writer
13985 // (tile.rs `sb_coeff_inter_frame_tile_cdfs`, the `write_delta_q` call
13986 // with `!sb128_armed()`) and every smaller shape below it pass
13987 // `is_whole_sb = false` under a 128 grid, so the arm's first
13988 // (root-origin) superblock codes the group even when skipped. Only the skipped 128
13989 // NONE root escapes it, so the split side is charged here at the same
13990 // root lambda the candidates are priced with.
13991 let split_dq =
13992 delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c));
13993 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
13994 && (cost128
13995 < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq)
13996 // The witness knobs take the root whatever it costs, so the
13997 // forced block really reaches the writer.
13998 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
13999 || forced_rect != 0
14000 || forced_ab != 0)
14001 {
14002 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
14003 blocks.truncate(mark128);
14004 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
14005 let at = (root_r * 2) * cols + root_c * 2;
14006 match shape {
14007 0 => {
14008 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14009 let block = halves.into_iter().next().expect("the NONE arm's block");
14010 record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);
14011 blocks.push((at, Quadrant::Whole128(block)));
14012 }
14013 // lane-ab128: three pieces, published at their own footprints
14014 // in the writer's own order ([`ab128_pieces`]).
14015 symbol @ 4..=7 => {
14016 B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14017 for (((mr, mc), (w, h)), piece) in
14018 ab128_pieces(symbol, (root_r * 16, root_c * 16)).iter().zip(&halves)
14019 {
14020 record_mi_rect(
14021 &mut grid,
14022 *mr,
14023 *mc,
14024 (w / 4, h / 4),
14025 piece.inter,
14026 piece.skip,
14027 );
14028 }
14029 blocks.push((at, Quadrant::Ab128(symbol as u8, halves)));
14030 }
14031 symbol => {
14032 let horz = symbol == 1;
14033 if horz {
14034 B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14035 } else {
14036 B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14037 }
14038 let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) };
14039 for (i, half) in halves.iter().enumerate() {
14040 let (mr, mc) = if horz {
14041 (root_r * 16 + i * 16, root_c * 16)
14042 } else {
14043 (root_r * 16, root_c * 16 + i * 16)
14044 };
14045 record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip);
14046 }
14047 blocks.push((at, Quadrant::Rect128(horz, halves)));
14048 }
14049 }
14050 for q in 1..16 {
14051 let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
14052 blocks.push((r32 * cols + c32, Quadrant::Covered));
14053 }
14054 }
14055 }
14056 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
14057 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
14058 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
14059 for (&out, tile) in chroma_out.iter().zip(&chroma) {
14060 copy_rect(
14061 out,
14062 &tile.reconstruction,
14063 frame_width / 2,
14064 x0 / 2,
14065 y0 / 2,
14066 x1.div_ceil(2),
14067 y1.div_ceil(2),
14068 );
14069 }
14070 Ok(blocks)
14071 };
14072 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
14073 .into_iter()
14074 .flatten()
14075 {
14076 blocks[at] = quadrant;
14077 }
14078
14079 // lane-b128, `EC_AV1_B128_CENSUS=1`: how many of this INTER frame's 128
14080 // superblock roots the search left whole, so a flat BD result is
14081 // attributable (class `gate-blind-to-feature`). A key frame codes none:
14082 // only the inter writer has a 128x128 block.
14083 if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") {
14084 let whole = blocks
14085 .iter()
14086 .filter(|q| matches!(q, Quadrant::Whole128(_)))
14087 .count();
14088 let roots = blocks
14089 .iter()
14090 .filter(|q| !matches!(q, Quadrant::Covered))
14091 .count();
14092 // lane-b128r: of those roots, how many code a REAL residual rather
14093 // than the skip-only block lane-b128 shipped -- the fire count this
14094 // arm's own gate row is read against.
14095 let residual = blocks
14096 .iter()
14097 .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip))
14098 .count();
14099 // lane-b128r: and how many named a second reference (the compound
14100 // arm at the 128 root).
14101 let compound = blocks
14102 .iter()
14103 .filter(|q| {
14104 matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some()))
14105 })
14106 .count();
14107 // lane-b128hv: and how many roots took a rect cut instead, per shape
14108 // -- the HORZ/VERT fire count the gate rows are read against.
14109 let horz = blocks
14110 .iter()
14111 .filter(|q| matches!(q, Quadrant::Rect128(true, _)))
14112 .count();
14113 let vert = blocks
14114 .iter()
14115 .filter(|q| matches!(q, Quadrant::Rect128(false, _)))
14116 .count();
14117 let rect_compound = blocks
14118 .iter()
14119 .filter(|q| {
14120 matches!(q, Quadrant::Rect128(_, hs)
14121 if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))
14122 })
14123 .count();
14124 // lane-ab128: and how many took each AB shape, in PARTITION_HORZ_A
14125 // .. _VERT_B order -- the per-shape fire count its gate rows are read
14126 // against.
14127 let ab: [usize; 4] = std::array::from_fn(|i| {
14128 blocks
14129 .iter()
14130 .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4))
14131 .count()
14132 });
14133 eprintln!(
14134 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
14135 {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \
14136 compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \
14137 {roots} coded blocks ({:.1}% of the frame's area at 128)",
14138 ab[0],
14139 ab[1],
14140 ab[2],
14141 ab[3],
14142 100.0 * ((whole + horz + vert + ab.iter().sum::<usize>()) * 16) as f64
14143 / blocks.len().max(1) as f64,
14144 );
14145 }
14146 let modes = blocks
14147 .iter()
14148 .flat_map(Quadrant::blocks)
14149 .map(|b| b.mode)
14150 .collect::<Vec<_>>();
14151 let inter_block_share = blocks
14152 .iter()
14153 .flat_map(Quadrant::blocks)
14154 .filter(|b| b.inter.is_some())
14155 .count() as f64
14156 / modes.len() as f64;
14157 for block in blocks.iter().flat_map(Quadrant::blocks) {
14158 if let Some(info) = block.inter {
14159 let r = (info.ref_frame as usize).min(7);
14160 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14161 }
14162 }
14163 #[cfg(test)]
14164 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
14165 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
14166 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
14167 // next frame's writer starts from them -- exactly what
14168 // `crate::stream::stored_cdfs_for` hands the decoder.
14169 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
14170 let mut cdfs = start_cdfs
14171 .cloned()
14172 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
14173 // lane-txi: set per frame, never inherited from the snapshot the
14174 // previous frame stored -- the content gate can flip the bit between
14175 // frames (class `per-tile-state-not-reset`).
14176 cdfs.reduced_tx_set = header.reduced_tx_set;
14177 let start_cdfs = CdfSnapshot(cdfs);
14178 let reference_select_bit = header.reference_select;
14179 let switchable_motion_mode = header.is_motion_mode_switchable;
14180 let warped_motion = header.allow_warped_motion;
14181 let order_hint_bits = seq.order_hint_bits;
14182 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
14183 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
14184 // What this frame stores is the LARGEST tile's end-of-tile tables --
14185 // its own header's `context_update_tile_id` (spec 7.20), which
14186 // `tile_info_of` set to exactly that tile.
14187 let store_tile = layout.largest_tile();
14188 let end_cdfs = std::cell::RefCell::new(None);
14189 // As in `encode_key_frame_inner`: every tile starts from this frame's
14190 // own tables, so no tile depends on any other.
14191 let code_tiles = |bits: u8,
14192 sb_cols: usize,
14193 cdef_grid: &[u8],
14194 units: &[Option<crate::restoration::WienerInfo>]|
14195 -> Result<Vec<Vec<u8>>> {
14196 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
14197 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
14198 crate::tile::arm_delta_q(
14199 deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0),
14200 sb_cols,
14201 sb_q.clone().unwrap_or_default(),
14202 base_q_idx,
14203 );
14204 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
14205 crate::tile::arm_sb128(sb128_on());
14206 crate::tile::arm_sign_bias(sign_bias);
14207 // Thread-locals: every tile job arms its own worker.
14208 crate::tile::arm_reference_select(reference_select_bit);
14209 crate::tile::arm_motion_mode(switchable_motion_mode);
14210 crate::tile::arm_warped_motion(warped_motion);
14211 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
14212 crate::tile::arm_high_precision_mv(hp_mv);
14213 crate::tile::arm_screen(screen);
14214 crate::tile::arm_frame_mi_dims(frame_mi_dims);
14215 crate::tile::arm_filter_intra(filter_intra_on());
14216 let mut cdfs = start_cdfs.0.clone();
14217 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
14218 // Each tile's own MV grid: a candidate scan never reaches past
14219 // the tile's bounds, so a grid holding only this tile's own
14220 // blocks reads exactly as the decoder's frame-wide one does
14221 // under `MiGrid::set_tile_bounds`.
14222 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
14223 mv_grid.set_sign_bias(sign_bias);
14224 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
14225 mi_cols,
14226 mi_rows,
14227 base_q_idx,
14228 &blocks,
14229 tx_select,
14230 &mut cdfs,
14231 layout.rect(index),
14232 &mut mv_grid,
14233 )?;
14234 Ok((bytes, Some(cdfs)))
14235 })?;
14236 if let Some(cdfs) = stored {
14237 *end_cdfs.borrow_mut() = Some(cdfs);
14238 }
14239 Ok(out)
14240 };
14241 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
14242 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
14243 // this tile against the same single-slot reference this encoder predicted
14244 // from, under each candidate level.
14245 // The reference a DECODER holds is this frame's cropped size, not the
14246 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
14247 // reference whose height is not the header's own `frame_height` (spec
14248 // 7.9's compatible-size rule), and the chained-decode round trips prove
14249 // the two predict identically.
14250 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
14251 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
14252 reference.clone()
14253 } else {
14254 Picture {
14255 width: fw,
14256 height: fh,
14257 y: crop_plane(&reference.y, reference.width, fw, fh),
14258 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
14259 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
14260 }
14261 };
14262 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
14263 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
14264 // blocks may name GOLDEN needs that plane too, cropped the same way.
14265 let trial_golden = golden.map(|g| {
14266 if (g.width, g.height) == (fw, fh) {
14267 g.clone()
14268 } else {
14269 Picture {
14270 width: fw,
14271 height: fh,
14272 y: crop_plane(&g.y, g.width, fw, fh),
14273 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
14274 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
14275 }
14276 }
14277 });
14278 let trial_altref = altref.map(|a| {
14279 if (a.width, a.height) == (fw, fh) {
14280 a.clone()
14281 } else {
14282 Picture {
14283 width: fw,
14284 height: fh,
14285 y: crop_plane(&a.y, a.width, fw, fh),
14286 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
14287 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
14288 }
14289 }
14290 });
14291 let trial_last2 = last2.map(|l| {
14292 if (l.width, l.height) == (fw, fh) {
14293 l.clone()
14294 } else {
14295 Picture {
14296 width: fw,
14297 height: fh,
14298 y: crop_plane(&l.y, l.width, fw, fh),
14299 u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2),
14300 v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2),
14301 }
14302 }
14303 });
14304 let mut refs: [Option<&Picture>; 8] = [None; 8];
14305 refs[1] = Some(&trial_ref);
14306 refs[2] = trial_last2.as_ref();
14307 refs[4] = trial_golden.as_ref();
14308 refs[7] = trial_altref.as_ref();
14309 let refpix = crate::decode::RefPix::ready(refs);
14310 // lane-txrd: the frame's luma error BEFORE the loop filters, i.e. the
14311 // sum the block search believed it was minimising. Against the
14312 // post-filter per-frame PSNR the gate prints, this separates a trial
14313 // whose reconstruction is a lie from a filter stage that undoes the win.
14314 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
14315 let sse: u64 = luma
14316 .reconstruction
14317 .chunks(luma.width)
14318 .take(luma.true_height)
14319 .zip(picture_y8.chunks(luma.width))
14320 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
14321 .map(|(&r, &s)| {
14322 let d = i64::from(r) - i64::from(s);
14323 (d * d) as u64
14324 })
14325 .sum();
14326 eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}");
14327 }
14328 let post = |luma: &Plane<'_>, tag: &str| {
14329 if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
14330 return;
14331 }
14332 let sse: u64 = luma
14333 .reconstruction
14334 .chunks(luma.width)
14335 .take(luma.true_height)
14336 .zip(picture_y8.chunks(luma.width))
14337 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
14338 .map(|(&r, &s)| {
14339 let d = i64::from(r) - i64::from(s);
14340 (d * d) as u64
14341 })
14342 .sum();
14343 eprintln!("{tag} q={base_q_idx} luma sse={sse}");
14344 };
14345 pick_and_apply_filters(
14346 &mut header,
14347 &mut luma,
14348 &mut chroma,
14349 [&picture_y8, &picture_u8, &picture_v8],
14350 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
14351 // this frame's own `tx_select`, so the search runs under inter
14352 // `TxMode::Select` too (it used to skip and leave every inter frame
14353 // unfiltered once Select became the default).
14354 true,
14355 &mut tiles,
14356 search.lambda,
14357 fctx,
14358 &crate::tile::cdef_unit_owner(&blocks, mi_cols, mi_rows),
14359 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
14360 // are what the NEXT frame writes from, so the winning re-code
14361 // publishes its own into `end_cdfs` -- the first write's are stale
14362 // the moment a second tile is coded.
14363 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
14364 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
14365 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
14366 crate::decode::decode_inter_frame_tiles_lr(
14367 &payloads,
14368 &header_tile_info,
14369 h.mi_cols,
14370 h.mi_rows,
14371 base_q_idx,
14372 h.frame_width,
14373 h.frame_height,
14374 &refpix,
14375 cdef,
14376 lf,
14377 h.allow_high_precision_mv,
14378 h.force_integer_mv,
14379 Some(fctx.interp_filter.get()),
14380 seq.enable_dual_filter,
14381 h.reference_select,
14382 // lane-txi: this frame's own bit, not the hardcoded `true`
14383 // the wrapper used to pass.
14384 h.reduced_tx_set,
14385 tx_select,
14386 lr,
14387 // The trial decode re-reads the tile the writer just wrote,
14388 // so it starts from the same tables the writer did (this
14389 // frame's `start_cdfs`), not from the defaults.
14390 Some(start_cdfs.0.clone()),
14391 sign_bias,
14392 h.allow_screen_content_tools,
14393 switchable_motion_mode,
14394 h.allow_warped_motion,
14395 seq.enable_filter_intra,
14396 // lane-deltaq: this frame's own delta_q/delta_lf params, so
14397 // the trial decode reads the per-superblock `delta_qindex`
14398 // syntax the writer just wrote.
14399 h.delta.clone(),
14400 fctx,
14401 )
14402 },
14403 )?;
14404 post(&luma, "EC_POSTFILTER");
14405 let mut cdfs = end_cdfs
14406 .into_inner()
14407 .unwrap_or_else(|| start_cdfs.0.clone());
14408 cdfs.reset_counts();
14409 let next_cdfs = CdfSnapshot(cdfs);
14410 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
14411 header.tile_info.tile_size_bytes = tile_size_bytes;
14412 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
14413 let mut stream = temporal_delimiter();
14414 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
14415
14416 let [u, v] = chroma;
14417 Ok(Encoded {
14418 stream,
14419 modes,
14420 inter_block_share,
14421 reconstruction: Picture {
14422 width: luma.width,
14423 height: luma.height,
14424 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14425 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14426 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14427 },
14428 tile,
14429 mi_cols: header.mi_cols,
14430 mi_rows: header.mi_rows,
14431 base_q_idx,
14432 tx_select,
14433 switchable_motion_mode,
14434 screen,
14435 reduced_tx_set: header.reduced_tx_set,
14436 start_cdfs,
14437 next_cdfs,
14438 loop_filter: header.loop_filter,
14439 cdef: header.cdef,
14440 loop_restoration: header.loop_restoration,
14441 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
14442 // intra frames only).
14443 allow_intrabc: false,
14444 delta: header.delta.clone(),
14445 })
14446}
14447
14448/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
14449/// frame's temporal unit followed by one inter frame's temporal unit per
14450/// remaining picture, all sharing the key frame's sequence header -- and
14451/// each frame's own [`Encoded`], in coding order.
14452#[derive(Clone, Debug)]
14453pub struct EncodedSequence {
14454 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
14455 /// sequence header and the key frame) followed by each later frame's
14456 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
14457 /// the sequence header the key frame carried).
14458 pub stream: Vec<u8>,
14459 /// One entry per picture, in DISPLAY order — the order a decoder outputs
14460 /// them and the order `pictures` came in. Without a pyramid that is also
14461 /// the coding order; with one the two differ, and `coding_order` is the
14462 /// map between them.
14463 pub frames: Vec<Encoded>,
14464 /// The index into `frames` of each coded frame, in CODING order — what a
14465 /// per-coded-frame census (`take_predicted_bits`) must be zipped against.
14466 /// `0..frames.len()` on the flat path.
14467 pub coding_order: Vec<usize>,
14468}
14469
14470/// Encodes a sequence of pictures as a key frame followed by one inter frame
14471/// per remaining picture, each predicting from the previous frame's own
14472/// decoded reconstruction — never from the source, which is what a decoder
14473/// cannot see. Every picture must be the same even size (any even width and
14474/// height — each is padded to a whole number of 64x64 superblocks
14475/// internally, which is what lets an inter frame's reference always match
14476/// the frame being coded against it), and `pictures` must be non-empty.
14477///
14478/// # Errors
14479/// Returns an error when `pictures` is empty, when any picture besides the
14480/// first is not the same size as the first, or under the same conditions
14481/// [`encode_key_frame`] and the inter frame path do.
14482pub(crate) fn encode_sequence_with_ctx(
14483 pictures: &[Picture],
14484 base_q_idx: u8,
14485 deadzone: f64, fctx: &crate::decode::FrameCtx,
14486) -> Result<EncodedSequence> {
14487 let Some((first, rest)) = pictures.split_first() else {
14488 return Err(Error::unsupported(
14489 "AV1 encode",
14490 "a sequence needs at least one picture",
14491 ));
14492 };
14493 first.check_even()?;
14494 let render = (first.width, first.height);
14495 // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is
14496 // coded as mini-GOPs -- a hidden ALTREF ahead of its display position,
14497 // the leaves that predict backward off it, and a `show_existing_frame`
14498 // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for
14499 // an A/B. Screen content stays flat (the content gate in
14500 // `Av1Encoder::encode_frames`, whose detector this asks first so the
14501 // whole sequence path is decided in one place), and so does a run that
14502 // asks for a quantizer rounding offset the facade does not carry: the
14503 // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone --
14504 // the ablations' -- must keep the flat path rather than be silently
14505 // ignored.
14506 //
14507 // The reordering itself is NOT reimplemented here: it is the facade's
14508 // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]),
14509 // called with this sequence's shape, so the two paths cannot drift.
14510 let pyramid = crate::encoder::Pyramid::from_env()
14511 .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON)
14512 .filter(|_| !picture_is_screen(first));
14513 LAST_SEQ_PYRAMID.with(|c| c.set(pyramid));
14514 if let Some(pyramid) = pyramid {
14515 for picture in rest {
14516 picture.check_even()?;
14517 if (picture.width, picture.height) != render {
14518 return Err(Error::unsupported(
14519 "AV1 encode",
14520 "every picture in a sequence must be the same size as the first",
14521 ));
14522 }
14523 }
14524 return crate::encoder::Av1Encoder::encode_sequence_pyramid(
14525 pictures,
14526 base_q_idx,
14527 pyramid,
14528 armed_tiles(),
14529 );
14530 }
14531 // The key frame and every inter frame after it are coded at the same
14532 // padded size, so the reference each inter frame predicts from -- the
14533 // previous frame's own uncropped reconstruction, at the size a decoder's
14534 // reference buffer actually holds -- always matches the frame being
14535 // coded against it.
14536 let key = encode_key_frame_inner(
14537 &first.padded_to(SUPERBLOCK),
14538 base_q_idx,
14539 deadzone,
14540 &KEY_FRAME_MODES,
14541 split_blocks(),
14542 render,
14543 unspecified_color_config(), fctx,
14544 )?;
14545 let mut stream = key.stream.clone();
14546 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
14547 // key frame refreshes every slot, each inter frame only slot 0), which is
14548 // what `GOLDEN_FRAME` names.
14549 let golden = key.reconstruction.clone();
14550 // The frame two back, once there is one that is not the key frame
14551 // itself (which `GOLDEN_FRAME` already names).
14552 let mut prev2: Option<Picture> = None;
14553 let mut carried = key.next_cdfs.clone();
14554 let mut reference = key.reconstruction.clone();
14555 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
14556 for (i, picture) in rest.iter().enumerate() {
14557 picture.check_even()?;
14558 // lane-av1tpl2: the lookahead window the per-block lambda weighting
14559 // propagates back through -- the next [`tpl_depth`] - 1 pictures'
14560 // sources at this frame's coded (padded) size. The tail of the
14561 // sequence gets a shorter window, and the last frame none at all.
14562 let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
14563 .iter()
14564 .take(tpl_depth() - 1)
14565 .map(|n| n.padded_to(SUPERBLOCK))
14566 .collect();
14567 if (picture.width, picture.height) != render {
14568 return Err(Error::unsupported(
14569 "AV1 encode",
14570 "every picture in a sequence must be the same size as the first",
14571 ));
14572 }
14573 let order_hint = (i + 1) as u32;
14574 let inter = encode_inter_frame(
14575 &picture.padded_to(SUPERBLOCK),
14576 &reference,
14577 base_q_idx,
14578 deadzone,
14579 order_hint,
14580 flat_order_hints(order_hint, 0, prev2.is_some()),
14581 render,
14582 Some(&carried.0),
14583 Some(&golden),
14584 prev2.as_ref(),
14585 None,
14586 fctx,
14587 None,
14588 &lookahead,
14589 )?;
14590 stream.extend_from_slice(&inter.stream);
14591 carried = inter.next_cdfs.clone();
14592 prev2 = Some(std::mem::replace(
14593 &mut reference,
14594 inter.reconstruction.clone(),
14595 ));
14596 frames.push(crop_encoded(&inter, render.0, render.1));
14597 }
14598 Ok(EncodedSequence {
14599 stream,
14600 coding_order: (0..frames.len()).collect(),
14601 frames,
14602 })
14603}
14604
14605#[cfg(test)]
14606mod tests {
14607
14608 /// Every (site, frame type, block side) the census can be called with
14609 /// lands in its own ten-counter bucket, inside the array (class
14610 /// `enumerate-table-domain`: an off-by-one here would silently add two
14611 /// sites' trials together).
14612 #[test]
14613 fn the_split_census_buckets_are_distinct_and_in_bounds() {
14614 let mut seen = std::collections::BTreeSet::new();
14615 for site in 0..2 {
14616 for key in [true, false] {
14617 for side in [8usize, 16, 32, 64] {
14618 let base = super::split_census_base(site, key, side);
14619 assert!(base + 10 <= super::SPLIT_CENSUS.len(), "{site} {key} {side}");
14620 assert!(seen.insert(base), "{site} {key} {side} collides");
14621 }
14622 }
14623 }
14624 assert_eq!(seen.len(), 16);
14625 }
14626
14627 /// An [`crate::mvstack::MvStack`] with every context at zero and no
14628 /// neighbours, for the pricer tests below to fill the one band each of
14629 /// them is about.
14630 /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
14631 /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
14632 /// against the same stack -- an offer the writer clamps prices the
14633 /// residual against a predictor the decoder never derives, which is the
14634 /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
14635 /// side, so the stream stays legal; here the pricer's own offer set is
14636 /// enumerated, class `enumerate-table-domain`).
14637 ///
14638 /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
14639 #[test]
14640 fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
14641 for n in 0..=4usize {
14642 let mut stack = bare_stack();
14643 for i in 0..n {
14644 stack.entries.push(crate::mvstack::StackEntry {
14645 mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
14646 weight: 1,
14647 });
14648 stack.drl_ctx.push(0);
14649 }
14650 stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
14651 stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
14652 stack.pred_mv = stack.nearest_mv;
14653 // Aim the vector at each entry in turn, so every index the offer
14654 // set holds is the one that wins at least once.
14655 for target in 0..n.max(1) {
14656 let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
14657 let (_, idx) = best_new_mv_syntax(&stack, mv)
14658 .expect("a zero residual is always codable");
14659 let idx = usize::from(idx);
14660 assert_eq!(
14661 crate::tile::signalled_drl_idx(n, 0, idx),
14662 idx,
14663 "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
14664 );
14665 }
14666 // The NEARMV arm's own offer set (`search_inter_block`,
14667 // `search_skip_64`): indices 1 and 2, offered only when the stack
14668 // really holds that entry.
14669 for idx in 1..=2usize {
14670 if stack.entries.get(idx).is_some() {
14671 assert_eq!(
14672 crate::tile::signalled_drl_idx(n, 1, idx),
14673 idx,
14674 "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
14675 );
14676 }
14677 }
14678 }
14679 }
14680
14681 fn bare_stack() -> crate::mvstack::MvStack {
14682 crate::mvstack::MvStack {
14683 entries: Default::default(),
14684 nearest_mv: (0, 0),
14685 near_mv: (0, 0),
14686 pred_mv: (0, 0),
14687 new_mv_ctx: 0,
14688 ref_mv_ctx: 0,
14689 zero_mv_ctx: 0,
14690 drl_ctx: Default::default(),
14691 above_refs: (None, None),
14692 left_refs: (None, None),
14693 above_nbr: None,
14694 left_nbr: None,
14695 above_skip: false,
14696 left_skip: false,
14697 }
14698 }
14699
14700 /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
14701 /// `write_compound_ref_frames` codes for a pair, each at that symbol's
14702 /// own neighbour-derived context. Red before lane-ctx, where the pricer
14703 /// spent four constants at CDF row 0 that assumed the pair was
14704 /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
14705 /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
14706 #[test]
14707 fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {
14708 use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
14709 use crate::encode::symbol_bits as b;
14710 use crate::mvstack::{
14711 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
14712 LAST_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx,
14713 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
14714 single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
14715 };
14716 // (pair, unidirectional?, the tree's symbols as (table, p index,
14717 // context selector, value)) -- transcribed from the writer.
14718 // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.
14719 type Sym = (char, usize, usize, usize);
14720 let cases: [((i8, i8), bool, &[Sym]); 7] = [
14721 ((LAST_FRAME, LAST2_FRAME), true, &[('u', 0, 1, 0), ('u', 1, 7, 0)]),
14722 (
14723 (LAST_FRAME, LAST3_FRAME),
14724 true,
14725 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)],
14726 ),
14727 (
14728 (LAST_FRAME, GOLDEN_FRAME),
14729 true,
14730 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)],
14731 ),
14732 ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]),
14733 (
14734 (LAST_FRAME, ALTREF_FRAME),
14735 false,
14736 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)],
14737 ),
14738 (
14739 (LAST_FRAME, BWDREF_FRAME),
14740 false,
14741 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 0)],
14742 ),
14743 (
14744 (LAST_FRAME, ALTREF2_FRAME),
14745 false,
14746 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 1)],
14747 ),
14748 ];
14749 let nbr = |ref0, ref1: Option<i8>| {
14750 Some(NeighbourRef {
14751 is_inter: true,
14752 ref0,
14753 ref1,
14754 uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)),
14755 })
14756 };
14757 // No neighbours (every context zero), then a mixed pair that puts the
14758 // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.
14759 for (above_nbr, left_nbr, above_refs, left_refs) in [
14760 (None, None, (None, None), (None, None)),
14761 (
14762 nbr(LAST_FRAME, None),
14763 nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)),
14764 (Some(LAST_FRAME), None),
14765 (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)),
14766 ),
14767 ] {
14768 let stack = crate::mvstack::MvStack {
14769 above_nbr,
14770 left_nbr,
14771 above_refs,
14772 left_refs,
14773 ..bare_stack()
14774 };
14775 let (a, a1) = above_refs;
14776 let (l, l1) = left_refs;
14777 let ctx_of = |sel: usize| match sel {
14778 1 => single_ref_p1_ctx(a, a1, l, l1),
14779 2 => single_ref_p2_ctx(a, a1, l, l1),
14780 3 => single_ref_p3_ctx(a, a1, l, l1),
14781 4 => single_ref_p4_ctx(a, a1, l, l1),
14782 5 => single_ref_p5_ctx(a, a1, l, l1),
14783 6 => single_ref_p6_ctx(a, a1, l, l1),
14784 _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
14785 };
14786 for (pair, unidir, symbols) in cases {
14787 let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
14788 + b(
14789 &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
14790 usize::from(!unidir),
14791 );
14792 for &(table, p, sel, v) in symbols {
14793 let row = ctx_of(sel);
14794 want += match table {
14795 'u' => b(&UNI_COMP_REF[row][p], v),
14796 'c' => b(&COMP_REF[row][p], v),
14797 _ => b(&COMP_BWDREF[row][p], v),
14798 };
14799 }
14800 let got = super::compound_ref_bits(pair, &stack);
14801 assert!(
14802 (got - want).abs() < 1e-9,
14803 "pair {pair:?} above {above_refs:?} left {left_refs:?}: \
14804 priced {got} bits, writer codes {want}"
14805 );
14806 }
14807 }
14808 }
14809
14810 /// The `skip` and `is_inter` symbols are priced at the SAME context
14811 /// tile.rs codes them with -- `above_skip + left_skip` for the first and
14812 /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
14813 /// on every neighbour configuration whose context is not zero (class
14814 /// pricer-context-zero).
14815 #[test]
14816 fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
14817 use crate::cdf::{INTRA_INTER, SKIP};
14818 use crate::encode::symbol_bits as b;
14819 use crate::mvstack::NeighbourRef;
14820 let nbr = |is_inter| NeighbourRef {
14821 is_inter,
14822 ref0: if is_inter { crate::mvstack::LAST_FRAME } else { 0 },
14823 ref1: None,
14824 uni: false,
14825 };
14826 for (above, left, above_skip, left_skip) in [
14827 (None, None, false, false),
14828 (Some(nbr(true)), Some(nbr(true)), true, false),
14829 (Some(nbr(false)), Some(nbr(false)), true, true),
14830 (Some(nbr(false)), None, false, true),
14831 (None, Some(nbr(true)), true, true),
14832 ] {
14833 let stack = crate::mvstack::MvStack {
14834 above_nbr: above,
14835 left_nbr: left,
14836 above_skip,
14837 left_skip,
14838 ..bare_stack()
14839 };
14840 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
14841 let ii_ctx = crate::tile::intra_inter_ctx(
14842 above.is_some(),
14843 left.is_some(),
14844 above.is_some_and(|n| n.is_inter),
14845 left.is_some_and(|n| n.is_inter),
14846 );
14847 for v in [false, true] {
14848 let (got, want) = (
14849 super::skip_bits_at(&stack, v),
14850 b(&SKIP[skip_ctx], usize::from(v)),
14851 );
14852 assert!(
14853 (got - want).abs() < 1e-9,
14854 "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
14855 );
14856 let (got, want) = (
14857 super::intra_inter_bits_at(&stack, v),
14858 b(&INTRA_INTER[ii_ctx], usize::from(v)),
14859 );
14860 assert!(
14861 (got - want).abs() < 1e-9,
14862 "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
14863 );
14864 }
14865 }
14866 }
14867
14868 /// [`super::single_ref_bits`] pays exactly what tile.rs'
14869 /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD
14870 /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at
14871 /// the context that symbol's own `single_ref_p*_ctx` derives from the
14872 /// block's above/left neighbours. Red before lane-pricer, where every
14873 /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
14874 #[test]
14875 fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
14876 use crate::cdf::SINGLE_REF as SR;
14877 use crate::encode::symbol_bits as b;
14878 use crate::mvstack::{
14879 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
14880 LAST_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
14881 single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
14882 };
14883 let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
14884 above_refs,
14885 left_refs,
14886 above_nbr,
14887 left_nbr,
14888 ..bare_stack()
14889 };
14890 let nbr = |ref0, ref1| {
14891 Some(crate::mvstack::NeighbourRef { is_inter: true, ref0, ref1, uni: false })
14892 };
14893 // (reference, the symbols `write_single_ref` emits as (p index, value))
14894 let cases: [(i8, &[(usize, usize)]); 7] = [
14895 (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),
14896 (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),
14897 (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),
14898 (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),
14899 (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),
14900 (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),
14901 (ALTREF_FRAME, &[(0, 1), (1, 1)]),
14902 ];
14903 // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair
14904 // that puts every p* context on a different row -- the second with a
14905 // COMPOUND left neighbour, which is what takes `reference_mode_ctx`
14906 // off row 0.
14907 for (above_refs, left_refs, above_nbr, left_nbr) in [
14908 ((None, None), (None, None), None, None),
14909 (
14910 (Some(LAST_FRAME), None),
14911 (Some(ALTREF_FRAME), Some(LAST_FRAME)),
14912 nbr(LAST_FRAME, None),
14913 nbr(ALTREF_FRAME, Some(LAST_FRAME)),
14914 ),
14915 ] {
14916 let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr);
14917 let (a, a1) = above_refs;
14918 let (l, l1) = left_refs;
14919 let ctx_of = |p: usize| match p {
14920 0 => single_ref_p1_ctx(a, a1, l, l1),
14921 1 => single_ref_p2_ctx(a, a1, l, l1),
14922 2 => single_ref_p3_ctx(a, a1, l, l1),
14923 3 => single_ref_p4_ctx(a, a1, l, l1),
14924 4 => single_ref_p5_ctx(a, a1, l, l1),
14925 _ => single_ref_p6_ctx(a, a1, l, l1),
14926 };
14927 for (ref_frame, symbols) in cases {
14928 // Plus the `comp_mode = 0` symbol the writer codes ahead of
14929 // the reference syntax on a `reference_select` frame.
14930 let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
14931 if super::reference_select() {
14932 want += b(
14933 &crate::cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(
14934 above_nbr, left_nbr,
14935 )],
14936 0,
14937 );
14938 }
14939 let got = super::single_ref_bits(ref_frame, &stack);
14940 assert!(
14941 (got - want).abs() < 1e-9,
14942 "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \
14943 priced {got} bits, writer codes {want}"
14944 );
14945 }
14946 }
14947 }
14948
14949 /// lane-av1tpl2's propagated map, on the two properties every decision
14950 /// under it rests on: a frame the whole lookahead window repeats exactly
14951 /// (uniform texture) leans on every cell alike, so every factor is 1 and
14952 /// the weighting is a no-op; and where the window really does save bits
14953 /// by predicting -- the textured half of a frame whose other half is
14954 /// flat -- the factor FALLS below 1, i.e. that half is coded more
14955 /// distortion-averse than the half nothing gains from.
14956 /// The distortion metric itself (lane-sse): a block the true frame edge
14957 /// cuts through is scored over its INSIDE part only, so a difference that
14958 /// lives entirely in the padding costs nothing and a block wholly past
14959 /// the edge scores zero. Before this, the search ranked modes,
14960 /// transforms and partition trees on samples the display crop throws
14961 /// away -- which lane-b64b had fixed for the 64x64 root alone.
14962 #[test]
14963 fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
14964 // A 40x40 true frame on a 64x64 padded coding surface.
14965 let source = vec![10u8; 64 * 64];
14966 let plane = fresh_plane(&source, 64, 64, 40, 40);
14967 let mut reconstruction = vec![10u8; 64 * 64];
14968 // Off by 190 at (50, 50) -- past the true edge in both axes.
14969 reconstruction[50 * 64 + 50] = 200;
14970 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 0.0, "padding was scored");
14971 // Off by 10 at (39, 39) -- the last sample the decoder shows.
14972 reconstruction[39 * 64 + 39] = 20;
14973 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 100.0, "inside was not scored");
14974 // A 16x16 block whose every sample is padding.
14975 let block = vec![200u8; 16 * 16];
14976 assert_eq!(plane.block_sse(48, 0, 16, &block), 0.0, "a block past the edge scored");
14977 // A 16x16 block the edge cuts: 8 of its columns are inside.
14978 assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
14979 }
14980
14981 /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
14982 /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the
14983 /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
14984 #[test]
14985 fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
14986 let (base, res) = (162u8, 4i32);
14987 let rf = 2.0;
14988 // A superblock the window leans on more than the frame average is
14989 // coded FINER (lower qindex); a slack one coarser; the average one
14990 // exactly at the base.
14991 assert!(super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base, "leaned-on SB must go finer");
14992 assert!(super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base, "idle SB must go coarser");
14993 assert_eq!(super::deltaq_libaom(base, rf, rf, 1.0, res), base, "the average SB moves 0");
14994 // Every offset is a whole number of steps and inside +-(res * 9 - 1).
14995 let max = ((res * 9 - 1) / res) * res;
14996 for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {
14997 for k in [0.5f64, 1.0, 1.5] {
14998 let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
14999 let d = q - i32::from(base);
15000 assert_eq!(d % res, 0, "r={r} k={k}: offset {d} is not a whole {res}-step");
15001 assert!(d.abs() <= max, "r={r} k={k}: offset {d} past libaom's +-{max}");
15002 }
15003 }
15004 // The clamp is REACHED from both ends, so the bound is a real bound
15005 // and not a formula that never gets there.
15006 assert_eq!(i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base), -max);
15007 assert_eq!(i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base), max);
15008 // A stronger `k` never moves less than a weaker one.
15009 let d = |k: f64| (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs();
15010 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));
15011 // The frame reference is libaom's log-mean: flat in, the same value out.
15012 assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9);
15013 }
15014
15015 /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto
15016 /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the
15017 /// shipped default, and the multiplier reaches the strength.
15018 #[test]
15019 fn the_per_level_delta_q_strength_indexes_the_levels_it_names() {
15020 let d = crate::speed::DQ_LEVEL_K;
15021 assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table");
15022 assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]);
15023 // Short and broken fields fall back per SLOT, not per spec.
15024 assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]);
15025 assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]);
15026 assert_eq!(super::DqLevel::TopArf as usize, 0);
15027 assert_eq!(super::DqLevel::MidArf as usize, 1);
15028 assert_eq!(super::DqLevel::Leaf as usize, 2);
15029 }
15030
15031 #[test]
15032 fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
15033 // Four 64x64 superblocks across: the shipped map forms its ratio per
15034 // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
15035 // only ever produce one ratio -- and one ratio, mean-normalised, is
15036 // the flat map, whatever the content underneath it.
15037 let (w, h) = (256usize, 64usize);
15038 let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
15039 let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
15040 let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
15041 assert_eq!(f.len(), 64, "16x4 cells of 16x16");
15042 for (i, &v) in f.iter().enumerate() {
15043 assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda");
15044 }
15045
15046 // Left half textured, right half constant: the window saves bits
15047 // predicting the left half and nothing at all on the right.
15048 let split: Vec<u8> = (0..w * h)
15049 .map(|i| if i % w < w / 2 { ((i * 37) % 251) as u8 } else { 128 })
15050 .collect();
15051 let frames: Vec<&[u8]> = vec![&split, &split, &split];
15052 let cells_x = w / 16;
15053 for k in [0.25f64, 0.5, 1.0, 2.0] {
15054 let (f, _) = super::tpl_lambda_factors(&frames, w, h, k);
15055 for r in 0..h / 16 {
15056 let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
15057 assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1");
15058 assert!(idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1");
15059 }
15060 }
15061 }
15062
15063 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
15064 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
15065 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
15066 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
15067 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
15068 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
15069 /// only a quarter of the 16x8 table and read the wrong byte for every
15070 /// block row but the first (silently wrong above-right/below-left
15071 /// availability -- wrong pixels, no error).
15072 #[test]
15073 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
15074 for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
15075 let (bw_log2, bh_log2) =
15076 ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize);
15077 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
15078 for (name, table) in
15079 [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)]
15080 {
15081 assert_eq!(
15082 table.len() * 8,
15083 rows * cols,
15084 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
15085 );
15086 let mut seen = vec![0u32; table.len() * 8];
15087 for blk_row in 0..rows {
15088 for blk_col in 0..cols {
15089 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
15090 assert!(
15091 idx < seen.len(),
15092 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
15093 );
15094 seen[idx] += 1;
15095 }
15096 }
15097 assert!(
15098 seen.iter().all(|&n| n == 1),
15099 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
15100 (row stride is not {cols})"
15101 );
15102 }
15103 }
15104 }
15105 use super::*;
15106 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
15107 use crate::probe::run_with_stdin;
15108 use std::process::{Command, Stdio};
15109
15110 /// Every rectangular shape this decoder codes, at every position a block
15111 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
15112 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
15113 /// (`reconintra.c`) answer, whose bodies are ported below.
15114 ///
15115 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
15116 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
15117 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
15118 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
15119 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
15120 /// oracle's own arrays, so a re-routed or truncated table fails here even
15121 /// where the two rows happen to agree.
15122 ///
15123 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
15124 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
15125 /// callers handle by predicting each transform unit as its own block.
15126 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
15127 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
15128 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
15129 /// (the horizontal shapes, which those partitions never produce).
15130 #[test]
15131 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
15132 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
15133 // it pins the 64 reach explicitly instead of following the process's
15134 // own superblock knob (`for_encoder`), which made it red under
15135 // `EC_AV1_SB128=1` for no defect of the code under test.
15136 let fctx = &crate::decode::FrameCtx::new();
15137 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
15138 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
15139 (4, 8, 64, 9280, 64, 550),
15140 (8, 4, 64, 3712, 64, 9630),
15141 (8, 16, 16, 2352, 16, 134),
15142 (16, 8, 16, 960, 16, 2400),
15143 (16, 32, 4, 620, 4, 32),
15144 (32, 16, 4, 32, 4, 184),
15145 (32, 64, 1, 127, 1, 0),
15146 (64, 32, 1, 19, 1, 34),
15147 (4, 16, 32, 5472, 32, 14),
15148 (16, 4, 32, 960, 32, 6464),
15149 (8, 32, 8, 1400, 8, 2),
15150 (32, 8, 8, 32, 8, 1136),
15151 (16, 64, 2, 382, 2, 0),
15152 (64, 16, 2, 4, 2, 84),
15153 ];
15154 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
15155 /// a block whose transform covers it whole (`row_off == col_off == 0`,
15156 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
15157 /// superblock (`sb_mi_size == 16`).
15158 fn libaom_reach(
15159 bw: usize,
15160 bh: usize,
15161 x: usize,
15162 y: usize,
15163 width: usize,
15164 height: usize, _fctx: &crate::decode::FrameCtx,
15165 ) -> (bool, bool) {
15166 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
15167 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
15168 let sb_mi_size = 16usize;
15169 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
15170 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
15171 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
15172 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
15173 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
15174 // has_top_right: top_available && right_available, then row_off == 0.
15175 let top_right = if y == 0 || x + bw >= width {
15176 false
15177 } else if blk_row_in_sb == 0 {
15178 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
15179 // `bw_unit < bw_unit`, false for a whole-block transform.)
15180 true
15181 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
15182 false
15183 } else {
15184 bit(tr_table)
15185 };
15186 // has_bottom_left: bottom_available && left_available, col_off == 0.
15187 let bottom_left = if x == 0 || y + bh >= height {
15188 false
15189 } else if blk_col_in_sb == 0 {
15190 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
15191 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
15192 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
15193 false
15194 } else {
15195 bit(bl_table)
15196 };
15197 (top_right, bottom_left)
15198 }
15199 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
15200 let (tr, bl) = rect_reach_tables(bw, bh);
15201 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
15202 assert_eq!(
15203 (tr.len(), sum(tr), bl.len(), sum(bl)),
15204 (tr_len, tr_sum, bl_len, bl_sum),
15205 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
15206 );
15207 // Two superblocks across and down, so the superblock-relative
15208 // position (and not the frame position) is what decides.
15209 for sb_y in [0usize, 64] {
15210 for sb_x in [0usize, 64] {
15211 for y in (sb_y..sb_y + 64).step_by(bh) {
15212 for x in (sb_x..sb_x + 64).step_by(bw) {
15213 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
15214 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
15215 assert_eq!(
15216 (got.above_right, got.below_left),
15217 want,
15218 "{bw}x{bh} at ({x}, {y})"
15219 );
15220 }
15221 }
15222 }
15223 }
15224 }
15225 }
15226
15227 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
15228 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
15229 /// aomenc gate decodes its stream through ffmpeg and is meaningless
15230 /// without it -- turns it into a hard failure. Without this the require
15231 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
15232 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
15233 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
15234 fn have_ffmpeg() -> bool {
15235 let present = Command::new("ffmpeg")
15236 .arg("-version")
15237 .stdout(Stdio::null())
15238 .stderr(Stdio::null())
15239 .status()
15240 .is_ok_and(|s| s.success());
15241 assert!(
15242 present
15243 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
15244 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
15245 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
15246 );
15247 present
15248 }
15249
15250 /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the
15251 /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).
15252 fn have_encoder(encoder: &str) -> bool {
15253 Command::new("ffmpeg")
15254 .args(["-hide_banner", "-encoders"])
15255 .stderr(Stdio::null())
15256 .output()
15257 .is_ok_and(|o| {
15258 String::from_utf8_lossy(&o.stdout)
15259 .lines()
15260 .any(|l| l.split_whitespace().nth(1) == Some(encoder))
15261 })
15262 }
15263
15264 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
15265 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
15266 let out = run_with_stdin(
15267 Command::new("ffmpeg").args([
15268 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
15269 ]),
15270 stream,
15271 );
15272 assert!(
15273 out.status.success(),
15274 "ffmpeg refused the stream: {}",
15275 String::from_utf8_lossy(&out.stderr)
15276 );
15277 let (luma, chroma) = (width * height, width * height / 4);
15278 assert_eq!(
15279 out.stdout.len(),
15280 luma + 2 * chroma,
15281 "expected one 4:2:0 frame"
15282 );
15283 Picture {
15284 width,
15285 height,
15286 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
15287 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
15288 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
15289 }
15290 }
15291
15292 /// A picture with something of everything in it: a gradient, an edge, a
15293 /// ripple and a block of flat colour, none of them aligned to the block
15294 /// grid.
15295 /// The in-loop filters actually FIRE and the stream still decodes to
15296 /// exactly what the encoder kept as its reconstruction
15297 /// (gate-blind-to-feature: a filter search that always answered "off"
15298 /// would leave every other test just as green, and the BD gate that
15299 /// would notice is `#[ignore]`d).
15300 ///
15301 /// Run:
15302 /// cargo test -p ec-av1 --release --lib -- \
15303 /// encode::tests::the_filter_search_picks_real_filters
15304 #[test]
15305 fn the_filter_search_picks_real_filters() {
15306 let _knobs = crate::speed::knob_read();
15307 let fctx = &crate::decode::FrameCtx::for_encoder();
15308 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
15309 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
15310 let fired = encoded
15311 .frames
15312 .iter()
15313 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
15314 .count();
15315 assert!(
15316 fired > 0,
15317 "no frame of this sequence chose any in-loop filtering: {:?}",
15318 encoded
15319 .frames
15320 .iter()
15321 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
15322 .collect::<Vec<_>>()
15323 );
15324 // The reconstruction the encoder predicts from is the FILTERED one,
15325 // and it is what a decoder of the stream produces -- byte for byte,
15326 // frame for frame.
15327 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
15328 assert_eq!(decoded.len(), encoded.frames.len());
15329 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
15330 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
15331 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
15332 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
15333 }
15334 }
15335
15336 fn test_card(width: usize, height: usize) -> Picture {
15337 let mut picture = Picture::grey(width, height);
15338 for y in 0..height {
15339 for x in 0..width {
15340 let gradient = x as f64 * 200.0 / width as f64;
15341 let ripple = 30.0
15342 * (x as f64 * std::f64::consts::PI / 23.0).sin()
15343 * (y as f64 * std::f64::consts::PI / 37.0).cos();
15344 let edge = if x > width * 3 / 7 && y > height / 3 {
15345 40.0
15346 } else {
15347 0.0
15348 };
15349 picture.y[y * width + x] =
15350 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
15351 }
15352 }
15353 for y in 0..height / 2 {
15354 for x in 0..width / 2 {
15355 let i = y * width / 2 + x;
15356 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
15357 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
15358 }
15359 }
15360 picture
15361 }
15362
15363 fn psnr(a: &[u16], b: &[u16]) -> f64 {
15364 let squared: f64 = a
15365 .iter()
15366 .zip(b)
15367 .map(|(&x, &y)| {
15368 let d = f64::from(x) - f64::from(y);
15369 d * d
15370 })
15371 .sum();
15372 if squared == 0.0 {
15373 return f64::INFINITY;
15374 }
15375 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
15376 }
15377
15378 /// lane-i64's witness: a smooth gradient is exactly the picture a whole
15379 /// 64x64 intra block predicts as well as four 32x32 ones, so the key
15380 /// frame's new root fires on most superblocks -- and what BOTH decoders
15381 /// produce is the encoder's own reconstruction, sample for sample.
15382 ///
15383 /// The fire count is the `gate-blind-to-feature` guard: without it every
15384 /// assert below passes on a stream that codes no whole superblock at all.
15385 #[test]
15386 fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
15387 let _knobs = crate::speed::knob_read();
15388 let fctx = &crate::decode::FrameCtx::for_encoder();
15389 // 4 x 3 superblocks, all of them wholly inside the frame.
15390 let (width, height) = (256usize, 192usize);
15391 let mut picture = Picture::grey(width, height);
15392 for y in 0..height {
15393 for x in 0..width {
15394 picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
15395 }
15396 }
15397 for y in 0..height / 2 {
15398 for x in 0..width / 2 {
15399 picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
15400 picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
15401 }
15402 }
15403 let _ = take_i64_root_hits();
15404 let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
15405 let [roots, _offered, _edge] = take_i64_root_hits();
15406 // The counters are process-global, so another test encoding in
15407 // parallel can only ADD to them -- the per-FRAME fact is the mode
15408 // list, which carries one entry per coded block and so exactly 12
15409 // when every superblock was coded as one 64x64 intra block.
15410 assert_eq!(
15411 encoded.modes.len(),
15412 12,
15413 "not every superblock was coded as one 64x64 intra block"
15414 );
15415 assert!(
15416 roots >= 8,
15417 "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
15418 );
15419 eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
15420
15421 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
15422 assert_eq!(ours.len(), 1, "our decoder's frames");
15423 assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
15424 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
15425 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
15426
15427 if !have_ffmpeg() {
15428 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15429 return;
15430 }
15431 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15432 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15433 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15434 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15435 }
15436
15437 /// The claim the whole encoder rests on: what a decoder produces is what
15438 /// the encoder said it would, sample for sample, on every plane.
15439 ///
15440 /// Prediction reads the reconstruction, so a single sample of drift
15441 /// anywhere would spread into every block below and to the right of it —
15442 /// which is why this is an equality and not a tolerance.
15443 #[test]
15444 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
15445 let _knobs = crate::speed::knob_read();
15446 let fctx = &crate::decode::FrameCtx::for_encoder();
15447 if !have_ffmpeg() {
15448 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
15449 return;
15450 }
15451 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48), (248, 152)] {
15452 let picture = test_card(width, height);
15453 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15454 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15455 assert_eq!(
15456 decoded.y, encoded.reconstruction.y,
15457 "{width}x{height}: luma"
15458 );
15459 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
15460 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
15461 }
15462 // One q index from each of the four coefficient-CDF contexts
15463 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
15464 let (width, height) = (64usize, 64usize);
15465 let picture = test_card(width, height);
15466 let _ = take_tx_depth_hits();
15467 for &q in &[15u8, 45, 100, 200] {
15468 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
15469 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15470 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
15471 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
15472 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
15473 }
15474 // lane-av1tx: the exactness above is only a claim about SPLIT
15475 // transforms if some block actually split one (`gate-blind-to-feature`
15476 // -- with `tx_depth` stuck at 0 every assert here passes on the
15477 // pre-lane stream). The test card's edges split at these four
15478 // quantizers; the counter is per-process (another test encoding in
15479 // parallel can only ADD to it, so this can be masked, never falsely
15480 // failed), so it is read once for the whole q ladder.
15481 let depths = take_tx_depth_hits();
15482 assert!(
15483 depths[1] + depths[2] > 0,
15484 "no block split its transform: depths {depths:?}"
15485 );
15486 }
15487
15488 /// A synthetic screen-content picture -- a few flat colours in a grid of
15489 /// boxes with hard edges and text-like bars, the shape a desktop capture
15490 /// has -- so the palette path is exercised on content it is for.
15491 #[cfg(test)]
15492 fn screen_card(width: usize, height: usize) -> Picture {
15493 const INK: [u16; 4] = [16, 90, 180, 235];
15494 let mut picture = Picture::grey(width, height);
15495 for y in 0..height {
15496 for x in 0..width {
15497 let cell = (x / 24 + y / 24) % 2;
15498 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
15499 picture.y[y * width + x] = INK[cell * 2 + bar];
15500 }
15501 }
15502 // Four chroma colours, not two: a two-colour chroma block only ever
15503 // codes a `PaletteSizeUV` of 2, which leaves
15504 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
15505 // deltas and the neighbour cache flags, exercised only when
15506 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
15507 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
15508 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
15509 for y in 0..height / 2 {
15510 for x in 0..width / 2 {
15511 let cell = (x / 12 + 2 * (y / 12)) % 4;
15512 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
15513 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
15514 }
15515 }
15516 picture
15517 }
15518
15519 /// The lane's own end-to-end check: on screen content the detector fires,
15520 /// blocks really take a palette (fire count, class
15521 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
15522 /// symbol this lane writes -- reconstructs exactly what the encoder did.
15523 /// The film-shaped `test_card` must NOT trip the detector, which is what
15524 /// keeps every non-screen stream byte-identical.
15525 #[test]
15526 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
15527 let _knobs = crate::speed::knob_read();
15528 let fctx = &crate::decode::FrameCtx::for_encoder();
15529 let (width, height) = (192usize, 96usize);
15530 let _ = crate::tile::take_palette_hits();
15531 let picture = screen_card(width, height);
15532 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15533 assert!(
15534 encoded.screen,
15535 "the detector did not fire on screen content -- no palette syntax was coded at all"
15536 );
15537 let hits = crate::tile::take_palette_hits();
15538 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
15539 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
15540 // The chroma half is a claim about the plane-1 syntax only if some
15541 // block really took a chroma palette (`gate-blind-to-feature`): every
15542 // exactness assert below passes on a stream that codes
15543 // `palette_uv_mode == 0` everywhere.
15544 let uv_hits = crate::tile::take_palette_uv_hits();
15545 assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
15546 let uv_cached = crate::tile::take_palette_uv_cache_hits();
15547 eprintln!(
15548 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
15549 uv_hits[0],
15550 &uv_hits[2..]
15551 );
15552 assert!(
15553 uv_cached > 0,
15554 "no chroma base colour came out of the neighbour cache -- \
15555 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
15556 );
15557 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
15558 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
15559 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
15560 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
15561 if !have_ffmpeg() {
15562 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15563 return;
15564 }
15565 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15566 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15567 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15568 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15569 // A whole GOP: the inter frames' own intra blocks carry the palette
15570 // syntax too (the three intra arms of the inter writers), which only
15571 // ffmpeg reading the frames back can prove.
15572 let moved: Vec<Picture> = (0..4)
15573 .map(|f| {
15574 let base = screen_card(width, height);
15575 let mut out = Picture::grey(width, height);
15576 for y in 0..height {
15577 for x in 0..width {
15578 let sx = (x + f * 7) % width;
15579 out.y[y * width + x] = base.y[y * width + sx];
15580 }
15581 }
15582 for y in 0..height / 2 {
15583 for x in 0..width / 2 {
15584 let sx = (x + f * 3) % (width / 2);
15585 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
15586 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
15587 }
15588 }
15589 out
15590 })
15591 .collect();
15592 let _ = crate::tile::take_palette_hits();
15593 let _ = crate::tile::take_palette_uv_hits();
15594 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
15595 let gop_hits = crate::tile::take_palette_hits();
15596 let gop_uv_hits = crate::tile::take_palette_uv_hits();
15597 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
15598 eprintln!(
15599 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
15600 {} chroma palette blocks",
15601 inter_screen, gop_hits[0], gop_uv_hits[0]
15602 );
15603 assert!(
15604 gop_uv_hits[0] > 0,
15605 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
15606 );
15607 assert!(
15608 inter_screen > 0,
15609 "no inter frame set allow_screen_content_tools"
15610 );
15611 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
15612 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
15613 assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
15614 }
15615 if have_ffmpeg() {
15616 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
15617 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
15618 assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
15619 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
15620 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
15621 }
15622 }
15623
15624 // The other half of the keep rule: film-shaped content leaves the
15625 // detector (and so the whole sequence header) alone.
15626 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
15627 assert!(!film.screen, "the detector fired on the film-shaped test card");
15628 }
15629
15630 /// The lane's keep-rule measurement: the gate's own screen capture, one
15631 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
15632 /// Setting the bit forces deblocking, CDEF and loop restoration off for
15633 /// that frame, so the table is exactly the filter loss against the bytes
15634 /// the copied blocks save.
15635 #[test]
15636 #[ignore = "needs the real-library manifest and ffmpeg"]
15637 fn probe_intrabc_key_frame() {
15638 let _knobs = crate::speed::knob_write();
15639 let fctx = &crate::decode::FrameCtx::for_encoder();
15640 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
15641 .join("../../fixtures");
15642 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
15643 eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest");
15644 return;
15645 };
15646 let Some(clip) = manifest
15647 .lines()
15648 .skip(1)
15649 .filter_map(|l| l.split('\t').next())
15650 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
15651 else {
15652 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
15653 return;
15654 };
15655 let (width, height) = (1280usize, 768usize);
15656 let picture = clip_frame(clip, "0", width, height);
15657 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
15658 for q in [5u8, 20, 35, 45] {
15659 for on in [false, true] {
15660 force_intrabc(Some(on));
15661 let _ = crate::tile::take_intrabc_hits();
15662 let _ = take_intrabc_search();
15663 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
15664 let hits = crate::tile::take_intrabc_hits();
15665 let search = take_intrabc_search();
15666 eprintln!(
15667 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
15668 if encoded.allow_intrabc { "on" } else { "off" },
15669 encoded.stream.len(),
15670 psnr_all(&encoded.reconstruction, &picture),
15671 hits[0],
15672 &hits[1..],
15673 search[0], search[1], search[2],
15674 );
15675 }
15676 }
15677 force_intrabc(None);
15678 }
15679
15680 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
15681 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
15682 /// take a block vector (fire count + DV histogram, class
15683 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
15684 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
15685 /// exactly what the encoder did.
15686 #[test]
15687 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
15688 let _knobs = crate::speed::knob_write();
15689 let fctx = &crate::decode::FrameCtx::for_encoder();
15690 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
15691 // superblocks of 64) and tall enough for a source superblock row
15692 // above the blocks that copy from it.
15693 let (width, height) = (512usize, 256usize);
15694 let picture = screen_card(width, height);
15695 let _ = crate::tile::take_intrabc_hits();
15696 // The default is OFF (it measured worse on the real screen capture --
15697 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
15698 // the arm on for its own encode and puts it back straight after.
15699 force_intrabc(Some(true));
15700 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15701 force_intrabc(None);
15702 assert!(
15703 encoded.allow_intrabc,
15704 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
15705 intrabc_source_share() * 100.0
15706 );
15707 let hits = crate::tile::take_intrabc_hits();
15708 eprintln!(
15709 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
15710 hits[0],
15711 &hits[1..],
15712 intrabc_source_share() * 100.0
15713 );
15714 let search = take_intrabc_search();
15715 eprintln!(
15716 "intrabc searches {} found-valid {} won-RD {}",
15717 search[0], search[1], search[2]
15718 );
15719 assert!(
15720 hits[0] > 0,
15721 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
15722 );
15723 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
15724 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
15725 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
15726 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
15727 if !have_ffmpeg() {
15728 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15729 return;
15730 }
15731 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15732 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15733 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15734 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15735 }
15736
15737 /// The minimal repro that isolated the inter-residual desync: a key frame
15738 /// followed by one inter frame whose single superblock carries one
15739 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
15740 /// coefficient, its three sibling blocks all `skip: true`. Before the
15741 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
15742 /// found when processing input") even though every symbol either block
15743 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
15744 /// same coefficient syntax decodes clean on every intra key-frame gate).
15745 #[test]
15746 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
15747 let _knobs = crate::speed::knob_write();
15748 let fctx = &crate::decode::FrameCtx::for_encoder();
15749 if !have_ffmpeg() {
15750 eprintln!(
15751 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
15752 );
15753 return;
15754 }
15755 let (width, height) = (64usize, 64usize);
15756 let picture = Picture::grey(width, height);
15757 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15758
15759 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
15760 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
15761
15762 let residual_block = BlockCoeffs {
15763 luma_tx_types: Vec::new(),
15764 angle_delta_y: 0,
15765 cfl_alphas: None,
15766 filter_intra: None,
15767 luma: vec![Coeff {
15768 row: 0,
15769 col: 0,
15770 level: 4,
15771 }],
15772 u: Vec::new(),
15773 v: Vec::new(),
15774 mode: 0,
15775 uv_mode: 0,
15776 skip: false,
15777 eight: None,
15778 dv: None,
15779 palette: None,
15780 palette_uv: None,
15781 tx_depth: 0,
15782 inter: Some(InterInfo {
15783 ref1: None,
15784 mv1: (0, 0),
15785 ref_frame: crate::mvstack::LAST_FRAME,
15786 mode: InterMode::NearestMv,
15787 mv: (0, 0),
15788 ref_mv_idx: 0,
15789 }),
15790 motion_mode: 0,
15791 };
15792 let skipped_block = BlockCoeffs {
15793 skip: true,
15794 inter: Some(InterInfo {
15795 ref1: None,
15796 mv1: (0, 0),
15797 ref_frame: crate::mvstack::LAST_FRAME,
15798 mode: InterMode::NearestMv,
15799 mv: (0, 0),
15800 ref_mv_idx: 0,
15801 }),
15802 ..BlockCoeffs::default()
15803 };
15804 let blocks = vec![
15805 Quadrant::Whole(residual_block),
15806 Quadrant::Whole(skipped_block.clone()),
15807 Quadrant::Whole(skipped_block.clone()),
15808 Quadrant::Whole(skipped_block),
15809 ];
15810 // lane-av1obmc: the header this tile is decoded under carries
15811 // `is_motion_mode_switchable`, so the writer must be armed with it
15812 // too or the decoder reads a `motion_mode` symbol nobody wrote.
15813 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
15814 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
15815 let tile =
15816 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
15817 .unwrap();
15818
15819 // `key.stream` is already a temporal delimiter, the sequence header
15820 // and the key frame's own OBU (`encode_key_frame` built it from the
15821 // same `key_frame_headers(width, height, 100)` this test calls), so
15822 // the inter frame's OBU is appended straight onto it rather than
15823 // re-deriving the key frame's tile bytes.
15824 let mut stream = key.stream.clone();
15825 stream.extend_from_slice(&temporal_delimiter());
15826 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
15827
15828 ffmpeg_decode_sequence(&stream, width, height, 2);
15829 }
15830
15831 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
15832 /// frame size an AV1 decoder allocates, not necessarily the render size
15833 /// (see [`a_frame_round_trips_at_its_own_size`]).
15834 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
15835 // Distinct per call, not per process: the test binary runs callers on
15836 // parallel threads, and a shared name lets one test's cleanup delete
15837 // the stream another test's ffprobe is still reading.
15838 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
15839 let path = std::env::temp_dir().join(format!(
15840 "ec-av1-probe-{}-{}.obu",
15841 std::process::id(),
15842 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
15843 ));
15844 let _ = std::fs::remove_file(&path);
15845 std::fs::write(&path, stream).expect("writing the probe stream");
15846 let out = Command::new("ffprobe")
15847 .args([
15848 "-v",
15849 "error",
15850 "-f",
15851 "obu",
15852 "-select_streams",
15853 "v:0",
15854 "-show_entries",
15855 "stream=width,height",
15856 "-of",
15857 "csv=p=0",
15858 ])
15859 .arg(&path)
15860 .output()
15861 .expect("ffprobe failed to run");
15862 let _ = std::fs::remove_file(&path);
15863 assert!(
15864 out.status.success(),
15865 "ffprobe refused the stream: {}",
15866 String::from_utf8_lossy(&out.stderr)
15867 );
15868 let text = String::from_utf8_lossy(&out.stdout);
15869 let mut fields = text.trim().split(',');
15870 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
15871 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
15872 (width, height)
15873 }
15874
15875 /// lane-av1cap: the final filter replay against the capture decode it
15876 /// replaced, at the block-padded and straddling sizes the whole-frame
15877 /// tests cover -- `set_verify_final_replay` makes
15878 /// [`pick_and_apply_filters`] run both on every frame and assert, per
15879 /// frame, that the spliced picture and the two filter stages the
15880 /// restoration search reads are bit-identical over the frame's own crop.
15881 #[test]
15882 fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() {
15883 let _knobs = crate::speed::knob_write();
15884 let fctx = &crate::decode::FrameCtx::for_encoder();
15885 crate::decode::set_verify_final_replay(true);
15886 for &(width, height) in
15887 &[(64usize, 56usize), (216, 96), (192, 120), (640, 352), (1280, 720)]
15888 {
15889 eprintln!("--- {width}x{height}");
15890 let picture = test_card(width, height);
15891 let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15892 }
15893 crate::decode::set_verify_final_replay(false);
15894 }
15895
15896 /// A key frame at an arbitrary even size round-trips through ffmpeg over
15897 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
15898 /// picture's own size, and what ffmpeg decodes over that same top-left
15899 /// region equals it sample for sample.
15900 ///
15901 /// This does not check that `ffprobe` reports the picture's own size,
15902 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
15903 /// (block-padded) frame size, the same one libaom itself would code for
15904 /// a non-block-aligned picture. `render_width`/`render_height` (which
15905 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
15906 /// decoder is required to crop pixels by, and ffmpeg's does not --
15907 /// checked empirically against ffprobe here and against a real libaom
15908 /// encode separately. So the coded size, not the render size, is what
15909 /// `ffprobe` is asserted to report below.
15910 #[test]
15911 fn a_frame_round_trips_at_its_own_size() {
15912 let _knobs = crate::speed::knob_read();
15913 let fctx = &crate::decode::FrameCtx::for_encoder();
15914 if !have_ffmpeg() {
15915 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
15916 return;
15917 }
15918 // 854x480 is covered separately by
15919 // `an_854x480_picture_round_trips_through_its_padding`, which its own
15920 // doc comment explains was worth keeping as its own test.
15921 for &(width, height) in &[
15922 (1920usize, 1080usize),
15923 (640, 352),
15924 (1280, 720),
15925 (64, 56),
15926 (854, 480),
15927 (216, 96),
15928 (192, 120),
15929 ] {
15930 let picture = test_card(width, height);
15931 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15932 assert_eq!(
15933 (encoded.reconstruction.width, encoded.reconstruction.height),
15934 (width, height),
15935 "{width}x{height}: reconstruction is cropped to the picture's own size"
15936 );
15937 assert_eq!(
15938 ffprobe_size(&encoded.stream),
15939 (width as u32, height as u32),
15940 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
15941 );
15942 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15943 assert_eq!(
15944 decoded.y, encoded.reconstruction.y,
15945 "{width}x{height}: luma"
15946 );
15947 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
15948 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
15949 }
15950 }
15951
15952 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
15953 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
15954 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
15955 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
15956 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
15957 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
15958 /// col`) -- different bits of an 8-byte table, one true, one false. The
15959 /// stride libaom indexes by is fixed at its compile-time maximum
15960 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
15961 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
15962 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
15963 /// row/col position within the (correctly 64-relative) superblock stayed
15964 /// right, only the table's own row stride was wrong. Fixed in
15965 /// `Reach::table_stride`; not an arithmetic-coder desync (an
15966 /// EC_RNG-per-symbol trace against the same debug decoder found the
15967 /// bitstream byte-for-byte identical to libaom's across all 51188
15968 /// symbols of this frame before this bug was found).
15969 ///
15970 /// Since the frame header started writing the true (unpadded) display
15971 /// size into `frame_width`/`frame_height` rather than the padded coded
15972 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
15973 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
15974 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
15975 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
15976 /// the header's own size before output).
15977 #[test]
15978 fn an_854x480_picture_round_trips_through_its_padding() {
15979 let _knobs = crate::speed::knob_read();
15980 let fctx = &crate::decode::FrameCtx::for_encoder();
15981 if !have_ffmpeg() {
15982 return;
15983 }
15984 let (width, height) = (854usize, 480usize);
15985 let picture = test_card(width, height);
15986 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15987 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15988 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
15989 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
15990 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
15991 }
15992
15993 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
15994 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
15995 /// superblock, both partition tables:
15996 ///
15997 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
15998 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
15999 /// wiring the TU sites onto it changes no existing stream;
16000 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
16001 /// NULL in libaom because that lookup never happens, and reading a
16002 /// 4x4 row out of the three-row vert tables is what crashed a real
16003 /// `--enable-tx-size-search=1` stream (r2);
16004 /// 3. and it must be the BLOCK's vert answer where the two tables
16005 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
16006 /// row 1, column 0 reads its above-right samples from the 8x8 to its
16007 /// upper right, which a vertical AB partition codes AFTER it
16008 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
16009 #[test]
16010 fn of_tu_follows_the_block_row_including_under_vert_ab() {
16011 let fctx = &crate::decode::FrameCtx::for_encoder();
16012 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
16013 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
16014 // above-right answer is the BLOCK's, which is the whole reason a unit
16015 // asks the block instead of looking itself up (the
16016 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
16017 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
16018 assert_eq!(
16019 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
16020 plain.above_right,
16021 "ordinary table: the top-right TX4 unit takes the block's row"
16022 );
16023 let guard = Reach::vert_ab_partition();
16024 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
16025 assert_eq!(
16026 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
16027 vert.above_right,
16028 "vert AB: the unit follows the vert row the block just picked"
16029 );
16030 assert_ne!(
16031 plain.above_right, vert.above_right,
16032 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
16033 );
16034 drop(guard);
16035 }
16036
16037 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
16038 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
16039 /// reconintra.c`), for every 16x16 and 32x32 block position across three
16040 /// superblocks square -- interior and every superblock edge (top row,
16041 /// left column, right column, bottom row) both sizes reach. Written to
16042 /// catch the class the `table_stride` bug was: an index stride silently
16043 /// wrong for one block size while looking plausible for the other.
16044 #[test]
16045 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
16046 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
16047 // it pins the 64 reach explicitly instead of following the process's
16048 // own superblock knob (`for_encoder`), which made it red under
16049 // `EC_AV1_SB128=1` for no defect of the code under test.
16050 let fctx = &crate::decode::FrameCtx::new();
16051 // Transcribed from has_top_right/has_bottom_left's row_off==0,
16052 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
16053 // 128px reference grid) pinned as libaom pins it, independent of the
16054 // 64px superblock this crate actually codes.
16055 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
16056 if y == 0 || x + side >= width {
16057 return false;
16058 }
16059 let (row, col, per_side) = (
16060 (y % SUPERBLOCK) / side,
16061 (x % SUPERBLOCK) / side,
16062 SUPERBLOCK / side,
16063 );
16064 if row == 0 {
16065 return true;
16066 }
16067 if col + 1 == per_side {
16068 return false;
16069 }
16070 let stride = 128 / side;
16071 let index = row * stride + col;
16072 let table = if side == BLOCK {
16073 [95u8, 87].to_vec()
16074 } else {
16075 vec![255, 85, 119, 85, 127, 85, 119, 85]
16076 };
16077 (table[index / 8] >> (index % 8)) & 1 != 0
16078 }
16079
16080 fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool {
16081 if x == 0 || y + side >= height {
16082 return false;
16083 }
16084 let (row, col, per_side) = (
16085 (y % SUPERBLOCK) / side,
16086 (x % SUPERBLOCK) / side,
16087 SUPERBLOCK / side,
16088 );
16089 if col == 0 {
16090 return row * side + side < SUPERBLOCK;
16091 }
16092 if row + 1 == per_side {
16093 return false;
16094 }
16095 let stride = 128 / side;
16096 let index = row * stride + col;
16097 let table = if side == BLOCK {
16098 [4u8, 4].to_vec()
16099 } else {
16100 vec![84, 16, 84, 0, 84, 16, 84, 0]
16101 };
16102 (table[index / 8] >> (index % 8)) & 1 != 0
16103 }
16104
16105 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
16106 for side in [16usize, BLOCK] {
16107 for y in (0..height).step_by(side) {
16108 for x in (0..width).step_by(side) {
16109 let reach = Reach::of(side, x, y, width, height, fctx);
16110 assert_eq!(
16111 reach.above_right,
16112 libaom_top_right(side, x, y, width, height),
16113 "side={side} x={x} y={y}: above_right"
16114 );
16115 assert_eq!(
16116 reach.below_left,
16117 libaom_bottom_left(side, x, y, height, fctx),
16118 "side={side} x={x} y={y}: below_left"
16119 );
16120 }
16121 }
16122 }
16123 }
16124
16125 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
16126 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
16127 /// column inside the superblock) may read the below-left samples the
16128 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
16129 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
16130 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
16131 /// stream that partitions that small first hits the still-refused
16132 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
16133 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
16134 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
16135 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
16136 /// pixels -- lane-palette2 r12: the square multi-TU path used the
16137 /// standalone-block tables instead of this rule and granted a 16x16
16138 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
16139 #[test]
16140 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
16141 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
16142 // *_count_unit = tx size / 4.
16143 fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
16144 let (plane_bw_unit, count) = (bw / 4, tx / 4);
16145 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
16146 let _ = bh;
16147 if row_off_u > 0 {
16148 col_off_u + count < plane_bw_unit
16149 } else if col_off_u + count < plane_bw_unit {
16150 true
16151 } else {
16152 blk
16153 }
16154 }
16155 fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
16156 let (plane_bh_unit, count) = (bh / 4, tx / 4);
16157 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
16158 let _ = bw;
16159 if col_off_u > 0 {
16160 false
16161 } else if row_off_u + count < plane_bh_unit {
16162 true
16163 } else {
16164 blk
16165 }
16166 }
16167 for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
16168 for &tx in &[4usize, 8, 16, 32] {
16169 if tx > bw.min(bh) {
16170 continue;
16171 }
16172 for row_off in (0..bh).step_by(tx) {
16173 for col_off in (0..bw).step_by(tx) {
16174 for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] {
16175 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
16176 assert_eq!(
16177 got.above_right,
16178 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
16179 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
16180 );
16181 assert_eq!(
16182 got.below_left,
16183 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
16184 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
16185 );
16186 }
16187 }
16188 }
16189 }
16190 }
16191 }
16192
16193 #[test]
16194 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
16195 let fctx = &crate::decode::FrameCtx::for_encoder();
16196 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
16197 // Interior superblock, so neither the frame edge nor the col == 0 /
16198 // last-row early returns answer instead of the table.
16199 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
16200 let mut flipped = 0;
16201 for row in 0..8 {
16202 for col in 1..8 {
16203 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
16204 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
16205 let vert = {
16206 let _guard = Reach::vert_ab_partition();
16207 Reach::of(8, x, y, width, height, fctx).below_left
16208 };
16209 // The TR square of a VERT_A/_B sits at an even row, odd
16210 // column; every other slot must be untouched by the guard.
16211 if row % 2 == 0 && col % 2 == 1 {
16212 assert!(!raster, "raster below_left at row={row} col={col}");
16213 assert!(vert, "vert below_left at row={row} col={col}");
16214 flipped += 1;
16215 } else {
16216 assert_eq!(raster, vert, "guard moved row={row} col={col}");
16217 }
16218 }
16219 }
16220 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
16221 // The guard is scoped: it must not leak past its own block.
16222 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
16223 }
16224
16225 /// An odd width or height is refused by name, not by however the padder
16226 /// or the block coder would happen to fail on it.
16227 #[test]
16228 fn odd_dimensions_are_refused() {
16229 let _knobs = crate::speed::knob_read();
16230 let fctx = &crate::decode::FrameCtx::for_encoder();
16231 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
16232 let picture = Picture::grey(width, height);
16233 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
16234 .expect_err(&format!("{width}x{height} is odd and must be refused"));
16235 assert!(
16236 err.to_string().contains("even"),
16237 "{width}x{height}: error was {err}"
16238 );
16239 }
16240 }
16241
16242 /// A sequence at a size that is not a multiple of the block grid decodes
16243 /// to the right frame count and the right size for every frame,
16244 /// including the inter frames whose reference is the previous frame's
16245 /// own (padded) reconstruction.
16246 #[test]
16247 fn sequence_round_trips_at_a_non_multiple_size() {
16248 let _knobs = crate::speed::knob_read();
16249 let fctx = &crate::decode::FrameCtx::for_encoder();
16250 if !have_ffmpeg() {
16251 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
16252 return;
16253 }
16254 let (width, height) = (160usize, 96usize);
16255 let pictures: Vec<Picture> = (0..3)
16256 .map(|i| panned_test_card(width, height, i * 3))
16257 .collect();
16258 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16259 assert_eq!(encoded.frames.len(), 3);
16260 for (i, frame) in encoded.frames.iter().enumerate() {
16261 assert_eq!(
16262 (frame.reconstruction.width, frame.reconstruction.height),
16263 (width, height),
16264 "frame {i}: reconstruction size"
16265 );
16266 }
16267 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
16268 // true (display) size a sequence's frames share, not the padded one.
16269 assert_eq!(
16270 ffprobe_size(&encoded.stream),
16271 (width as u32, height as u32),
16272 "sequence: ffprobe reports the true (display) size"
16273 );
16274 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
16275 assert_eq!(decoded.len(), 3, "decoded frame count");
16276 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16277 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16278 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16279 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16280 }
16281 }
16282
16283 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
16284 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
16285 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
16286 /// `pos + side_mi / 2 < bound` boundary), which is the case
16287 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
16288 /// refusing. A key frame alone already covered this size; this proves the
16289 /// inter tile writer's parity with it across a real multi-frame export.
16290 #[test]
16291 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
16292 let _knobs = crate::speed::knob_read();
16293 let fctx = &crate::decode::FrameCtx::for_encoder();
16294 if !have_ffmpeg() {
16295 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
16296 return;
16297 }
16298 let (width, height) = (1280usize, 720usize);
16299 let pictures: Vec<Picture> = (0..3)
16300 .map(|i| panned_test_card(width, height, i * 3))
16301 .collect();
16302 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16303 assert_eq!(encoded.frames.len(), 3);
16304 for (i, frame) in encoded.frames.iter().enumerate() {
16305 assert_eq!(
16306 (frame.reconstruction.width, frame.reconstruction.height),
16307 (width, height),
16308 "frame {i}: reconstruction size"
16309 );
16310 }
16311 assert_eq!(
16312 ffprobe_size(&encoded.stream),
16313 (width as u32, height as u32),
16314 "ffprobe reports the true (display) 1280x720 size"
16315 );
16316 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
16317 assert_eq!(decoded.len(), 3, "decoded frame count");
16318 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16319 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16320 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16321 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16322 }
16323 }
16324
16325 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
16326 /// leaf's own half (`has_half` at the SUB level) itself straddles the
16327 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
16328 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
16329 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
16330 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
16331 /// straddling-16x16 branch), so an inter frame no longer refuses this
16332 /// size either. This only proves the encoder does not error out -- see
16333 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
16334 /// decoder-clean proof (a 3-frame sequence, so the inter path is
16335 /// actually exercised).
16336 #[test]
16337 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
16338 let _knobs = crate::speed::knob_read();
16339 let fctx = &crate::decode::FrameCtx::for_encoder();
16340 let (width, height) = (640usize, 360usize);
16341 let picture = Picture::grey(width, height);
16342 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
16343
16344 // `encode_sequence`'s second frame is the inter path: same size, now
16345 // wired the same way.
16346 let pictures = vec![picture.clone(), picture];
16347 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
16348 .expect("inter frame now codes the mod-32==8 straddle too");
16349 }
16350
16351 /// The r15 fix at production size: three 640x360 key frames (inter is
16352 /// still refused at this size, per the test above, so this stands in for
16353 /// the charter's "3-frame sequence" using three independent key frames of
16354 /// shifted content), each proven decoder-clean through ffmpeg rather than
16355 /// only encoder-clean.
16356 #[test]
16357 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
16358 let _knobs = crate::speed::knob_read();
16359 let fctx = &crate::decode::FrameCtx::for_encoder();
16360 if !have_ffmpeg() {
16361 eprintln!(
16362 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
16363 no ffmpeg"
16364 );
16365 return;
16366 }
16367 let (width, height) = (640usize, 360usize);
16368 for shift in [0i64, 7, 19] {
16369 let picture = panned_test_card(width, height, shift);
16370 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16371 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16372 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
16373 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
16374 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
16375 }
16376 }
16377
16378 /// The 640x360 straddle class, but through the inter path an actual
16379 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
16380 /// proves the leaf-8 inter stream this round wires up is not just
16381 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
16382 #[test]
16383 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
16384 let _knobs = crate::speed::knob_read();
16385 let fctx = &crate::decode::FrameCtx::for_encoder();
16386 if !have_ffmpeg() {
16387 eprintln!(
16388 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
16389 );
16390 return;
16391 }
16392 let (width, height) = (640usize, 360usize);
16393 let pictures: Vec<Picture> = (0..4)
16394 .map(|i| panned_test_card(width, height, i * 3))
16395 .collect();
16396 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16397 assert_eq!(encoded.frames.len(), 4);
16398 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
16399 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
16400 }
16401 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
16402 assert_eq!(decoded.len(), 4, "decoded frame count");
16403 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16404 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16405 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16406 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16407 }
16408 }
16409
16410 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
16411 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
16412 let out = Command::new("ffmpeg")
16413 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
16414 .args(["-vf", &format!("scale={width}:{height}")])
16415 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
16416 .output()
16417 .expect("ffmpeg failed to run");
16418 assert!(
16419 out.status.success(),
16420 "ffmpeg: {}",
16421 String::from_utf8_lossy(&out.stderr)
16422 );
16423 let (luma, chroma) = (width * height, width * height / 4);
16424 assert_eq!(
16425 out.stdout.len(),
16426 luma + 2 * chroma,
16427 "expected one 4:2:0 frame"
16428 );
16429 Picture {
16430 width,
16431 height,
16432 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
16433 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
16434 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
16435 }
16436 }
16437
16438 /// Prints what the mode search saves over DC prediction alone, for the
16439 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
16440 /// weight the search puts on rate can be swept.
16441 #[test]
16442 #[ignore = "a sweep, not a gate"]
16443 fn probe_lambda() {
16444 let _knobs = crate::speed::knob_read();
16445 let fctx = &crate::decode::FrameCtx::for_encoder();
16446 let mut pictures = vec![
16447 ("test card".to_string(), test_card(160, 96)),
16448 ("stripes".to_string(), stripes(160, 96, true)),
16449 ];
16450 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
16451 for entry in clips.split(':').filter(|e| !e.is_empty()) {
16452 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
16453 let name = path.rsplit('/').next().unwrap_or(path).to_string();
16454 pictures.push((name, clip_frame(path, skip, 640, 352)));
16455 }
16456 }
16457 for (name, picture) in pictures {
16458 let dc = ladder(&picture, &[DC_PRED], fctx);
16459 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
16460 println!(
16461 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
16462 bd_rate(&dc, &searched) * 100.0,
16463 10f64.powf(searched[1].1),
16464 searched[1].0,
16465 10f64.powf(dc[1].1),
16466 dc[1].0,
16467 );
16468 }
16469 }
16470
16471 /// Prints the whole mode-search ladder, so two builds of the search can be
16472 /// compared against each other rather than each against its own baseline.
16473 #[test]
16474 #[ignore = "a sweep, not a gate"]
16475 fn probe_ladder() {
16476 let _knobs = crate::speed::knob_read();
16477 let fctx = &crate::decode::FrameCtx::for_encoder();
16478 for (name, picture) in sweep_pictures() {
16479 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
16480 let points = all
16481 .iter()
16482 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
16483 .collect::<Vec<_>>()
16484 .join(" ");
16485 println!("ladder {name}: {points}");
16486 }
16487 }
16488
16489 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
16490 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
16491 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
16492 #[test]
16493 #[ignore = "a sweep, not a gate"]
16494 fn probe_split() {
16495 let _knobs = crate::speed::knob_read();
16496 let fctx = &crate::decode::FrameCtx::for_encoder();
16497 for (name, picture) in sweep_pictures() {
16498 let ladder = |split: bool| {
16499 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
16500 .iter()
16501 .map(|&q| {
16502 let encoded = encode_key_frame_inner(
16503 &picture,
16504 q,
16505 0.5,
16506 &KEY_FRAME_MODES,
16507 split,
16508 (picture.width, picture.height),
16509 unspecified_color_config(), fctx,
16510 )
16511 .unwrap();
16512 (
16513 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
16514 (encoded.stream.len() as f64).log10(),
16515 )
16516 })
16517 .collect();
16518 points.sort_by(|a, b| a.0.total_cmp(&b.0));
16519 points
16520 };
16521 let (whole, split) = (ladder(false), ladder(true));
16522 let blocks = encode_key_frame_inner(
16523 &picture,
16524 90,
16525 0.5,
16526 &KEY_FRAME_MODES,
16527 true,
16528 (picture.width, picture.height),
16529 unspecified_color_config(), fctx,
16530 )
16531 .unwrap()
16532 .modes
16533 .len();
16534 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
16535 println!(
16536 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
16537 bd_rate(&whole, &split) * 100.0
16538 );
16539 }
16540 }
16541
16542 /// A striped picture, running one way or the other. The stripes are what
16543 /// separates a vertical predictor from a horizontal one: a mode search
16544 /// reading a transposed edge would pick the wrong one of the pair, which no
16545 /// symmetric picture would show.
16546 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
16547 let mut picture = Picture::grey(width, height);
16548 for y in 0..height {
16549 for x in 0..width {
16550 let along = if vertical { x } else { y };
16551 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
16552 }
16553 }
16554 picture
16555 }
16556
16557 /// Where two planes first disagree, and by how much: a mismatch reported as
16558 /// a position says which block and which sample of it went wrong, which a
16559 /// pair of thousand-sample arrays does not.
16560 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
16561 let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
16562 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
16563 Some(format!(
16564 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
16565 i % width,
16566 i / width,
16567 ours[i],
16568 theirs[i]
16569 ))
16570 }
16571
16572 /// Every mode the encoder offers has to predict what the decoder predicts,
16573 /// not just the ones a particular picture happens to choose: each is forced
16574 /// over a whole picture and the reconstruction gated against ffmpeg.
16575 #[test]
16576 fn every_mode_decodes_to_what_the_encoder_predicted() {
16577 let _knobs = crate::speed::knob_write();
16578 let fctx = &crate::decode::FrameCtx::for_encoder();
16579 if !have_ffmpeg() {
16580 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
16581 return;
16582 }
16583 // A mode ablation measures the MODE search: a filter-intra block is
16584 // coded `DC_PRED` whatever mode the arm forces, so it would fail the
16585 // "the encoder coded something else" check for a reason that is not
16586 // about the mode search at all.
16587 force_filter_intra(Some(false));
16588 // 128 wide is a whole number of superblocks and 160 is not: the last
16589 // superblock of a 160-wide row is half a one, whose blocks have no
16590 // above-right samples inside the frame at all.
16591 for (width, height) in [(128, 96), (160, 96)] {
16592 let picture = test_card(width, height);
16593 for mode in KEY_FRAME_MODES {
16594 let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap();
16595 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16596 for (plane, ours, theirs, stride) in [
16597 ("luma", &encoded.reconstruction.y, &decoded.y, width),
16598 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
16599 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
16600 ] {
16601 assert!(
16602 first_difference(ours, theirs, stride).is_none(),
16603 "{width}x{height} mode {mode}, {plane}: {}",
16604 first_difference(ours, theirs, stride).unwrap()
16605 );
16606 }
16607 assert!(
16608 encoded.modes.iter().all(|&m| m == mode),
16609 "mode {mode}: the encoder coded something else"
16610 );
16611 }
16612 }
16613 }
16614
16615 /// The search has to follow the picture: vertical stripes are cheapest
16616 /// predicted from the row above, horizontal ones from the column to the
16617 /// left. Reading the edges the other way round would swap the two answers
16618 /// while leaving every fidelity gate intact.
16619 #[test]
16620 fn the_search_picks_the_direction_the_picture_runs() {
16621 let _knobs = crate::speed::knob_write();
16622 let fctx = &crate::decode::FrameCtx::for_encoder();
16623 // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]:
16624 // a filter-intra block is coded `DC_PRED` whatever mode the arm
16625 // offers, and these stripes are SCREEN content, where the filter arm
16626 // now searches its own transform depth (lane-fitu) and wins outright
16627 // -- which says nothing about the mode search this gate measures.
16628 force_filter_intra(Some(false));
16629 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
16630 let picture = stripes(128, 96, vertical);
16631 // Only the pair, because on stripes a third mode predicts exactly
16632 // what the right one of the pair does -- PAETH reads the corner and
16633 // the left column, which a striped picture makes equal -- and the
16634 // tie then goes to whichever is cheaper to name, which is not what
16635 // this gate is about.
16636 let encoded =
16637 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
16638 // The first block of the picture has neither neighbour, so it
16639 // cannot tell the modes apart; every other one can.
16640 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
16641 assert!(
16642 picked * 2 > encoded.modes.len() - 1,
16643 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
16644 encoded.modes.len() - 1,
16645 encoded.modes
16646 );
16647 }
16648 }
16649
16650 /// What the search is for: the same picture, at the same quantizer, coded
16651 /// smaller and more faithfully than DC alone can manage.
16652 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
16653 /// between the two rate-distortion curves in log-rate against PSNR, as a
16654 /// fraction of the reference's rate. Negative means the second curve costs
16655 /// less for the same picture.
16656 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
16657 let low = reference[0].0.max(other[0].0);
16658 let high = reference[reference.len() - 1]
16659 .0
16660 .min(other[other.len() - 1].0);
16661 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
16662 // the non-directional one on the synthetic diagonals -- every point
16663 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
16664 // to integrate over any more. A curve that dominates that way has
16665 // saved everything the measure can express (the
16666 // `instrument-at-bound` class: the answer is at the instrument's own
16667 // edge, not undefined), so name it rather than panicking; anything
16668 // less clean than strict dominance still is.
16669 if high <= low {
16670 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
16671 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
16672 let dominates = other[0].0 > reference[reference.len() - 1].0
16673 && other_hi_rate <= ref_lo_rate;
16674 assert!(
16675 dominates,
16676 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
16677 );
16678 return -1.0;
16679 }
16680 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
16681 let i = curve
16682 .windows(2)
16683 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
16684 .unwrap_or(0);
16685 let (x0, y0) = curve[i];
16686 let (x1, y1) = curve[i + 1];
16687 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
16688 };
16689 let steps = 64;
16690 let mut area = 0.0;
16691 for step in 0..steps {
16692 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
16693 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
16694 }
16695 10f64.powf(area / f64::from(steps)) - 1.0
16696 }
16697
16698 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
16699 /// fidelity.
16700 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
16701 // A mode ablation measures the MODE search: the palette would code
16702 // these synthetic two-colour pictures losslessly under every arm and
16703 // leave nothing to compare (see [`force_screen`]).
16704 force_screen(Some(false));
16705 // Same reason, for the filter-intra candidate: it wins blocks under
16706 // BOTH arms of a mode ablation and so cancels the difference the
16707 // ablation measures (class `gate-recipe-confound`).
16708 force_filter_intra(Some(false));
16709 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
16710 .iter()
16711 .map(|&q| {
16712 let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
16713 (
16714 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
16715 (encoded.stream.len() as f64).log10(),
16716 )
16717 })
16718 .collect();
16719 points.sort_by(|a, b| a.0.total_cmp(&b.0));
16720 points
16721 }
16722
16723 /// What the search is for: the same pictures cost less to code at the same
16724 /// fidelity than DC prediction alone can manage. A picture that runs one
16725 /// way saves far more than a busy one, which is the shape a working
16726 /// directional pair has.
16727 #[test]
16728 fn the_search_beats_dc_alone() {
16729 let _knobs = crate::speed::knob_read();
16730 let fctx = &crate::decode::FrameCtx::for_encoder();
16731 for (name, picture, want) in [
16732 ("test card", test_card(160, 96), -0.05),
16733 ("stripes", stripes(160, 96, true), -0.40),
16734 ] {
16735 let saved = bd_rate(
16736 &ladder(&picture, &[DC_PRED], fctx),
16737 &ladder(&picture, &NON_DIRECTIONAL, fctx),
16738 );
16739 assert!(
16740 saved < want,
16741 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
16742 saved * 100.0,
16743 -want * 100.0
16744 );
16745 }
16746 }
16747
16748 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
16749 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
16750 fn sweep_pictures() -> Vec<(String, Picture)> {
16751 let mut pictures = vec![
16752 ("test card".to_string(), test_card(160, 96)),
16753 ("stripes".to_string(), stripes(160, 96, true)),
16754 ("diagonal".to_string(), diagonal(160, 96, true)),
16755 ];
16756 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
16757 for entry in clips.split(':').filter(|e| !e.is_empty()) {
16758 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
16759 let name = path.rsplit('/').next().unwrap_or(path).to_string();
16760 pictures.push((name, clip_frame(path, skip, 640, 352)));
16761 }
16762 }
16763 pictures
16764 }
16765
16766 /// What the six directional modes are worth, per picture, at whatever
16767 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
16768 /// no further, and how often the search picks one.
16769 #[test]
16770 #[ignore = "a sweep, not a gate"]
16771 fn probe_directional() {
16772 let _knobs = crate::speed::knob_write();
16773 let fctx = &crate::decode::FrameCtx::for_encoder();
16774 for (name, picture) in sweep_pictures() {
16775 let dc = ladder(&picture, &[DC_PRED], fctx);
16776 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
16777 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
16778 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
16779 let directional = encoded
16780 .modes
16781 .iter()
16782 .filter(|&&m| (3..=8).contains(&m))
16783 .count();
16784 // A picture whose ladders sit at different fidelities altogether
16785 // has no BD-rate to report -- see the flat-sample-window class.
16786 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
16787 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
16788 };
16789 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
16790 if overlap(a, b) {
16791 format!("{:+.2}%", bd_rate(a, b) * 100.0)
16792 } else {
16793 "no overlap".to_string()
16794 }
16795 };
16796 println!(
16797 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
16798 against(&flat, &all),
16799 against(&dc, &all),
16800 encoded.modes.len(),
16801 );
16802 }
16803 }
16804
16805 /// A picture whose stripes run along a diagonal, one way or the other.
16806 /// This is to the directional modes what [`stripes`] is to the vertical and
16807 /// horizontal pair: a predictor that walked the edge in the wrong direction
16808 /// would answer the two pictures the same way round.
16809 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
16810 let mut picture = Picture::grey(width, height);
16811 for y in 0..height {
16812 for x in 0..width {
16813 let along = if down_right { x + height - y } else { x + y };
16814 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
16815 }
16816 }
16817 picture
16818 }
16819
16820 /// The mode picked by the most blocks of a picture, ignoring the first
16821 /// block, which has no neighbours to tell the modes apart with.
16822 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
16823 // A mode ablation measures the MODE search: the palette would code
16824 // these synthetic two-colour pictures losslessly under every arm and
16825 // leave nothing to compare (see [`force_screen`]).
16826 force_screen(Some(false));
16827 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
16828 let blocks = &encoded.modes[1..];
16829 let mut counts = [0usize; 13];
16830 for &mode in blocks {
16831 counts[usize::from(mode)] += 1;
16832 }
16833 let (mode, count) = counts
16834 .iter()
16835 .enumerate()
16836 .max_by_key(|&(_, count)| *count)
16837 .expect("thirteen modes");
16838 (mode as u8, *count, blocks.len())
16839 }
16840
16841 /// The search has to follow a diagonal the way it runs: stripes down and to
16842 /// the right are cheapest predicted at 135 degrees, stripes down and to the
16843 /// left at 45. A walk that stepped the wrong way along the edge, or read
16844 /// the above row where it should read the left column, would swap these.
16845 #[test]
16846 fn the_search_picks_the_diagonal_the_picture_runs() {
16847 let _knobs = crate::speed::knob_write();
16848 let fctx = &crate::decode::FrameCtx::for_encoder();
16849 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
16850 let picture = diagonal(160, 96, down_right);
16851 let (mode, count, blocks) = favourite_mode(&picture, fctx);
16852 assert_eq!(
16853 mode, want,
16854 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
16855 );
16856 }
16857 }
16858
16859 /// What the directional modes are for: a picture that runs along a diagonal
16860 /// costs far less to code with them than the seven that read only their own
16861 /// edges can manage, and a picture that runs no particular way costs no
16862 /// more. The second half is the one that bites: a mode set the search
16863 /// cannot price is a mode set that loses rate on content that does not want
16864 /// it, which is what costing the mode symbol is for.
16865 #[test]
16866 fn the_diagonals_beat_the_modes_that_read_no_further() {
16867 let _knobs = crate::speed::knob_read();
16868 let fctx = &crate::decode::FrameCtx::for_encoder();
16869 for (name, picture, want) in [
16870 ("down-right", diagonal(160, 96, true), -0.20),
16871 ("down-left", diagonal(160, 96, false), -0.20),
16872 ("test card", test_card(160, 96), 0.01),
16873 ] {
16874 let saved = bd_rate(
16875 &ladder(&picture, &NON_DIRECTIONAL, fctx),
16876 &ladder(&picture, &KEY_FRAME_MODES, fctx),
16877 );
16878 assert!(
16879 saved < want,
16880 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
16881 saved * 100.0,
16882 -want * 100.0
16883 );
16884 }
16885 }
16886
16887 /// A mode the encoder cannot predict must be refused rather than coded as
16888 /// something else, and a search with nothing to choose from likewise.
16889 #[test]
16890 fn a_mode_the_encoder_cannot_predict_is_refused() {
16891 let _knobs = crate::speed::knob_read();
16892 let fctx = &crate::decode::FrameCtx::for_encoder();
16893 let picture = test_card(64, 64);
16894 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
16895 .unwrap_err()
16896 .to_string();
16897 assert!(
16898 message.contains("intra mode 13"),
16899 "the refusal must name the mode, got {message}"
16900 );
16901 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
16902 }
16903
16904 /// The picture that comes back is the picture that went in, to within the
16905 /// quantizer. A prediction that read the wrong neighbours, or a block
16906 /// written into the wrong place, would still decode to what the encoder
16907 /// reconstructed — it is this gate that says the reconstruction is of the
16908 /// right picture.
16909 #[test]
16910 fn the_encoded_picture_is_the_one_that_went_in() {
16911 let _knobs = crate::speed::knob_read();
16912 let fctx = &crate::decode::FrameCtx::for_encoder();
16913 let picture = test_card(160, 96);
16914 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16915 let luma = psnr(&encoded.reconstruction.y, &picture.y);
16916 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
16917 for (plane, (got, want)) in [
16918 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
16919 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
16920 ]
16921 .iter()
16922 .enumerate()
16923 {
16924 let chroma = psnr(got, want);
16925 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
16926 }
16927 }
16928
16929 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
16930 /// does the opposite. Both are monotone, which is what a rate-distortion
16931 /// loop above this will assume.
16932 #[test]
16933 fn fidelity_and_rate_move_with_the_quantizer() {
16934 let _knobs = crate::speed::knob_read();
16935 let fctx = &crate::decode::FrameCtx::for_encoder();
16936 let picture = test_card(128, 128);
16937 let mut previous: Option<(usize, f64)> = None;
16938 for &q in &[70u8, 90, 110] {
16939 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
16940 let quality = psnr(&encoded.reconstruction.y, &picture.y);
16941 if let Some((bytes, better)) = previous {
16942 assert!(
16943 encoded.stream.len() < bytes,
16944 "q {q}: {} bytes",
16945 encoded.stream.len()
16946 );
16947 assert!(quality < better, "q {q}: PSNR {quality}");
16948 }
16949 previous = Some((encoded.stream.len(), quality));
16950 }
16951
16952 // The deadzone half of this claim lives in
16953 // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now:
16954 // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding
16955 // every zeroing, the deadzone no longer moves a coded stream
16956 // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against
16957 // fewer at 0.5 on this 128x128 card), and that is the pass doing its
16958 // job, not a quantiser defect.
16959
16960 // Bytes must not jump up across a q-context boundary: a wrong CDF
16961 // table for the far side would show up as a rate discontinuity here,
16962 // even though a coarser quantizer always codes no more than a finer
16963 // one on the same picture.
16964 //
16965 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
16966 // chroma searches its own mode, a coarser quantizer can pick a
16967 // *different* uv_mode on a block whose modes now cost nearly the
16968 // same, and the search prices that symbol against the static default
16969 // CDF while the writer codes it against an adapted one -- 311 -> 319
16970 // bytes at q 120->121 on this picture. The table this gate is really
16971 // watching would move the rate by far more than the mode churn does.
16972 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
16973 // same block can also change transform DEPTH between two neighbouring
16974 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
16975 // symbol is priced off the static CDF row 0 for the same reason the
16976 // uv_mode one is.
16977 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
16978 // path is pricing through the adapting CDF state (what
16979 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
16980 // drift of), after which the exact bound comes back.
16981 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
16982 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
16983 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
16984 assert!(
16985 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
16986 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
16987 );
16988 }
16989 }
16990
16991 /// A flat picture is a flat stream: every block predicts its neighbours'
16992 /// average, which is the picture's own value, and codes nothing.
16993 #[test]
16994 fn a_flat_picture_costs_almost_nothing() {
16995 let _knobs = crate::speed::knob_read();
16996 let fctx = &crate::decode::FrameCtx::for_encoder();
16997 let mut picture = Picture::grey(128, 128);
16998 picture.y.fill(97);
16999 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17000 // The first block has no neighbour and predicts 128, so it carries a
17001 // DC; every block after it predicts 97 and carries nothing.
17002 assert!(
17003 encoded.stream.len() < 100,
17004 "{} bytes for a flat picture",
17005 encoded.stream.len()
17006 );
17007 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
17008 assert_eq!(s, 97, "sample {i} of a flat picture");
17009 }
17010 }
17011
17012 /// The sizes the encoder refuses, refused for a reason rather than by
17013 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
17014 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
17015 /// lands past the halfway point of whichever block it falls in, so
17016 /// `PARTITION_NONE` or a single gathered split flag still says everything
17017 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
17018 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
17019 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
17020 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
17021 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
17022 /// refusal here claimed otherwise and was wrong; see
17023 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
17024 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
17025 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
17026 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
17027 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
17028 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
17029 /// still refused is a malformed picture.
17030 #[test]
17031 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
17032 let _knobs = crate::speed::knob_read();
17033 let fctx = &crate::decode::FrameCtx::for_encoder();
17034 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
17035 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
17036 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
17037 .expect("36 luma columns still round up to an even MiCols");
17038
17039 let mut short = Picture::grey(64, 64);
17040 short.u.truncate(10);
17041 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
17042 }
17043
17044 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
17045 /// column half only (`has_half` false on cols, true on rows) -- exactly
17046 /// the single-axis straddle lane-av1-rect r7 wires through
17047 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
17048 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
17049 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
17050 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
17051 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
17052 /// `partition_context_lookup` entry this writer ever produces (no 4x4
17053 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
17054 /// leaf regardless of neighbour state -- our writer already agreed with
17055 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
17056 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
17057 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
17058 /// it does not regress the gate. r11 tell-for-tell traced two further,
17059 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
17060 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
17061 /// leaves, when the second leaf's true above (or left) neighbour is the
17062 /// first leaf itself -- fixed by threading the first leaf's mode into the
17063 /// second leaf's context, mi-precise, like `record_mi` already does for
17064 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
17065 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
17066 /// `reduced_tx_set` is false), but this crate's key frames set
17067 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
17068 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
17069 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
17070 /// symbol bits to desync everything after it. Fixed with a new
17071 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
17072 /// eset/size slot). Both fixes are provably correct against libaom
17073 /// source and each closed part of the gap (leaf0's `eob` went from a
17074 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
17075 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
17076 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
17077 /// (do not reuse r11's committed logs, which predate its own fixes) and
17078 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
17079 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
17080 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
17081 /// every other `write_block` caller at 16x16 and up already passes
17082 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
17083 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
17084 /// different amount of arithmetic range and derailed everything after
17085 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
17086 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
17087 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
17088 /// never updating those coarse arrays itself -- so a *second* straddling
17089 /// 16x16 quadrant stacked above or left of the first (never covered by
17090 /// r11's same-call `prev_leaf` override, which only threads state
17091 /// between the two leaves of one shared quadrant) read whatever stale
17092 /// mode sat in that slot before either leaf ran. Fixed by writing the
17093 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
17094 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
17095 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
17096 /// offset of a single unit; fixing (3)+(4) together still leaves a
17097 /// residual divergence one leaf further in -- the decoder now reads
17098 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
17099 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
17100 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
17101 /// desyncs the stream by exactly the width of one earlier symbol -- not
17102 /// yet isolated to a single named symbol. r15 found the last bug: the
17103 /// header fix from r14 explained the rng skew fully, and the remaining
17104 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
17105 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
17106 /// loop, once per leaf, so the first leaf's write clobbered the true
17107 /// external neighbour mode the second leaf of the *same* straddling
17108 /// quadrant still needed for its non-adjacency axis (a column-straddle
17109 /// case: two leaves share one `outer_at` column index, so leaf 1's
17110 /// write to `left_mode[r]` overwrote the real western neighbour before
17111 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
17112 /// doing it once, after the whole leaf loop, from the last (bottom/
17113 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
17114 #[test]
17115 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
17116 let _knobs = crate::speed::knob_read();
17117 let fctx = &crate::decode::FrameCtx::for_encoder();
17118 if !have_ffmpeg() {
17119 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
17120 return;
17121 }
17122 let (width, height) = (40usize, 32usize);
17123 let picture = test_card(width, height);
17124 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17125 assert_eq!(
17126 (encoded.reconstruction.width, encoded.reconstruction.height),
17127 (width, height)
17128 );
17129 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
17130 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
17131 }
17132 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17133 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
17134 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
17135 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
17136 }
17137
17138 /// A frame of real video, rather than a picture built to be easy.
17139 ///
17140 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
17141 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
17142 /// encoder's reconstruction has to survive the same equality gate as the
17143 /// synthetic pictures — real video reaches contexts a test card does not.
17144 #[test]
17145 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
17146 let _knobs = crate::speed::knob_read();
17147 let fctx = &crate::decode::FrameCtx::for_encoder();
17148 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
17149 eprintln!(
17150 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
17151 set EC_AV1_CLIP to a clip"
17152 );
17153 return;
17154 };
17155 if !have_ffmpeg() {
17156 eprintln!(
17157 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
17158 );
17159 return;
17160 }
17161 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
17162 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
17163 // test quick while still spanning many superblocks.
17164 let (width, height) = (640usize, 352usize);
17165 let picture = clip_frame(&clip, &skip, width, height);
17166
17167 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17168 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17169 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
17170 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
17171 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
17172 eprintln!(
17173 "{} bytes, luma PSNR {:.2} dB",
17174 encoded.stream.len(),
17175 psnr(&decoded.y, &picture.y)
17176 );
17177 }
17178
17179 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
17180 /// sequence of these is a translation a motion search can actually find
17181 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
17182 /// inter frame's rate against the key frame's is measuring the same
17183 /// picture moving, not two different pictures.
17184 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
17185 let mut picture = Picture::grey(width, height);
17186 for y in 0..height {
17187 for x in 0..width {
17188 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
17189 let gradient = sx * 200.0 / width as f64;
17190 let ripple = 30.0
17191 * (sx * std::f64::consts::PI / 23.0).sin()
17192 * (y as f64 * std::f64::consts::PI / 37.0).cos();
17193 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
17194 40.0
17195 } else {
17196 0.0
17197 };
17198 picture.y[y * width + x] =
17199 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
17200 }
17201 }
17202 for y in 0..height / 2 {
17203 for x in 0..width / 2 {
17204 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
17205 let i = y * width / 2 + x;
17206 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
17207 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
17208 }
17209 }
17210 picture
17211 }
17212
17213 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
17214 fn ffmpeg_decode_sequence(
17215 stream: &[u8],
17216 width: usize,
17217 height: usize,
17218 frames: usize,
17219 ) -> Vec<Picture> {
17220 let out = run_with_stdin(
17221 Command::new("ffmpeg").args([
17222 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
17223 ]),
17224 stream,
17225 );
17226 assert!(
17227 out.status.success(),
17228 "ffmpeg refused the stream: {}",
17229 String::from_utf8_lossy(&out.stderr)
17230 );
17231 let (luma, chroma) = (width * height, width * height / 4);
17232 let frame_bytes = luma + 2 * chroma;
17233 assert_eq!(
17234 out.stdout.len(),
17235 frame_bytes * frames,
17236 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
17237 String::from_utf8_lossy(&out.stderr)
17238 );
17239 (0..frames)
17240 .map(|i| {
17241 let base = i * frame_bytes;
17242 Picture {
17243 width,
17244 height,
17245 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
17246 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
17247 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
17248 }
17249 })
17250 .collect()
17251 }
17252
17253 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
17254 /// makes for a key frame, extended down the reference chain: each inter
17255 /// frame's reconstruction predicts from the previous frame's own decoded
17256 /// reconstruction, so a single sample of drift anywhere would propagate
17257 /// into every frame after it -- which is why every frame is checked, not
17258 /// just the last one, and why this is an equality and not a tolerance.
17259 #[test]
17260 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
17261 let _knobs = crate::speed::knob_read();
17262 let fctx = &crate::decode::FrameCtx::for_encoder();
17263 if !have_ffmpeg() {
17264 eprintln!(
17265 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
17266 );
17267 return;
17268 }
17269 let (width, height) = (128usize, 64usize);
17270 let pictures: Vec<Picture> = (0..5)
17271 .map(|i| panned_test_card(width, height, i * 3))
17272 .collect();
17273 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17274 assert_eq!(encoded.frames.len(), 5);
17275
17276 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
17277 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17278 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
17279 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
17280 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
17281 }
17282
17283 eprintln!("frame bytes luma PSNR (dB) inter share");
17284 for (i, frame) in encoded.frames.iter().enumerate() {
17285 eprintln!(
17286 "{i:5} {:5} {:14.2} {:11.2}",
17287 frame.stream.len(),
17288 psnr(&frame.reconstruction.y, &pictures[i].y),
17289 frame.inter_block_share
17290 );
17291 }
17292 }
17293
17294 /// The same sequence through OUR OWN decoder, sample-exact against the
17295 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
17296 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
17297 /// divergence point at all, while our decoder can be traced symbol by
17298 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
17299 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
17300 /// names the first differing frame, plane and position.
17301 /// lane-sb128b: the writer used to price a `NEWMV` residual against
17302 /// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the
17303 /// write-time stack could not carry, while the drl symbols signalled the
17304 /// clamped index -- so the decoder derived a DIFFERENT motion vector with
17305 /// the entropy stream still in sync, and the drift only surfaced frames
17306 /// later as a drl desync (on film B, as the encoder's own trial decode
17307 /// refusing a reference slot).
17308 ///
17309 /// The clamp needs a stack that shrinks between search and write, which
17310 /// is what a 128x128 superblock's visit order does; the counter is the
17311 /// point (class `gate-blind-to-feature`): a green round trip on a clip
17312 /// that never clamps proves nothing.
17313 ///
17314 /// `#[ignore]`: [`force_sb128`] moves a process-global.
17315 ///
17316 /// cargo test -p ec-av1 --release --lib -- --ignored \
17317 /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture
17318 /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode
17319 /// and one motion vector where the four 64x64 roots below spend four of
17320 /// each (cen3's L1). The counter is the gate on the fixture (class
17321 /// `gate-blind-to-feature`): a green round trip on a clip that never
17322 /// codes a 128x128 block proves nothing. RED before the search existed
17323 /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every
17324 /// root by construction).
17325 ///
17326 /// Both readers: our own decoder sample-exact against the encoder's
17327 /// reconstruction (a writer/reader desync surfaces as a pixel miss or a
17328 /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle.
17329 ///
17330 /// `#[ignore]`: [`force_sb128`] moves a process-global.
17331 ///
17332 /// cargo test -p ec-av1 --release --lib -- --ignored \
17333 /// a_128_superblock_clip_whose_root_search --nocapture
17334 #[test]
17335 #[ignore = "sets the process-global superblock size: run it alone"]
17336 fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {
17337 let _knobs = crate::speed::knob_write();
17338 if !have_ffmpeg() {
17339 eprintln!("SKIP: no ffmpeg");
17340 return;
17341 }
17342 force_sb128(true);
17343 let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));
17344 std::fs::create_dir_all(&dir).unwrap();
17345 let clip = dir.join("smpte-1280x768.y4m");
17346 // A slow horizontal pan over a still pattern: whole 128x128 regions
17347 // share one motion vector, which is exactly what a 128 root can code
17348 // as one block and four 64 roots cannot.
17349 let ok = Command::new("ffmpeg")
17350 .args(["-v", "error", "-y", "-f", "lavfi"])
17351 .args(["-i", "smptebars=size=1600x768:rate=24"])
17352 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17353 .args(["-pix_fmt", "yuv420p"])
17354 .arg(&clip)
17355 .status()
17356 .expect("ffmpeg failed to run")
17357 .success();
17358 assert!(ok, "ffmpeg could not write the synthetic clip");
17359 let (width, height) = (1280usize, 768usize);
17360 let pictures =
17361 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17362 let _ = take_b128_none_hits();
17363 let _ = crate::tile::take_sb128_none_hits();
17364 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17365 let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits());
17366 eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}");
17367 assert!(
17368 coded > 0,
17369 "no 128x128 block was coded on this clip, so it cannot witness the root search",
17370 );
17371 assert_eq!(won, coded, "every 128x128 root the search took must be coded as one");
17372 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17373 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17374 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17375 let recon = &frame.reconstruction;
17376 for (plane, got, want) in [
17377 ("luma", &dec.y, &recon.y),
17378 ("U", &dec.u, &recon.u),
17379 ("V", &dec.v, &recon.v),
17380 ] {
17381 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17382 assert_eq!(
17383 differ, 0,
17384 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17385 own reconstruction",
17386 got.len()
17387 );
17388 }
17389 }
17390 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17391 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17392 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17393 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17394 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17395 }
17396 }
17397
17398 /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma
17399 /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The
17400 /// same pan the skip-only witness above uses, with the arm FORCED
17401 /// ([`force_b128_residual`]): on synthetic bars the RD picks the residual
17402 /// about once per frame, which witnesses the shape but not every context
17403 /// it reads, and forcing codes all 420 roots of the clip through it. RED
17404 /// before this lane by construction (`write_inter_block_128` refused
17405 /// every non-skip 128 block, so no such block existed to decode), and RED
17406 /// again on the first draft of the writer, whose neighbour band recorded
17407 /// `skip = true` for a block that carries a residual -- the next root's
17408 /// `skip` symbol then took CDF row 1 where the reader takes row 0.
17409 ///
17410 /// lane-b128res: the fixture's q moved 150 -> 60. The forced arm replaces
17411 /// the skip arm's cost unconditionally (that is what makes the writer see
17412 /// the residual), and the cost model moved under it since lane-b128r --
17413 /// lane-rectdq made every non-skipped root pay its delta_q group and the
17414 /// pyramid re-prices the leaves -- so at q=150, then q=90, the NONE root
17415 /// lost its partition at ALL 420 roots and the writer coded none. q=60
17416 /// puts 52 written blocks back on this clip; the `coded > 0` assert below
17417 /// is the guard that catches the next such drift.
17418 ///
17419 /// cargo test -p ec-av1 --release --lib -- --ignored \
17420 /// a_128_root_block_with_a_real_residual --nocapture
17421 #[test]
17422 #[ignore = "sets the process-global superblock size: run it alone"]
17423 fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {
17424 let _knobs = crate::speed::knob_write();
17425 if !have_ffmpeg() {
17426 eprintln!("SKIP: no ffmpeg");
17427 return;
17428 }
17429 force_sb128(true);
17430 let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));
17431 std::fs::create_dir_all(&dir).unwrap();
17432 let clip = dir.join("smpte-pan-1280x768.y4m");
17433 let ok = Command::new("ffmpeg")
17434 .args(["-v", "error", "-y", "-f", "lavfi"])
17435 .args(["-i", "smptebars=size=1600x768:rate=24"])
17436 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17437 .args(["-pix_fmt", "yuv420p"])
17438 .arg(&clip)
17439 .status()
17440 .expect("ffmpeg failed to run")
17441 .success();
17442 assert!(ok, "ffmpeg could not write the synthetic clip");
17443 let (width, height) = (1280usize, 768usize);
17444 let pictures =
17445 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17446 let _ = take_b128_residual_hits();
17447 let _ = crate::tile::take_sb128_residual_hits();
17448 force_b128_residual(true);
17449 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17450 let (won, coded) =
17451 (take_b128_residual_hits(), crate::tile::take_sb128_residual_hits());
17452 eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}");
17453 assert!(
17454 coded > 0,
17455 "no 128x128 block carried a residual on this clip, so it cannot witness the arm",
17456 );
17457 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17458 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17459 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17460 let recon = &frame.reconstruction;
17461 for (plane, got, want) in [
17462 ("luma", &dec.y, &recon.y),
17463 ("U", &dec.u, &recon.u),
17464 ("V", &dec.v, &recon.v),
17465 ] {
17466 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17467 assert_eq!(
17468 differ, 0,
17469 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17470 own reconstruction",
17471 got.len()
17472 );
17473 }
17474 }
17475 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17476 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17477 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17478 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17479 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17480 }
17481 }
17482
17483 /// lane-edge128: a 128x128 root block WITH a residual on a clip whose
17484 /// CDEF search codes a per-64x64 `cdef_idx` list. `read_cdef` (spec
17485 /// 5.11.56) codes ONE literal for the block that first reaches a unit and
17486 /// copies it over every unit the block SPANS, so the four units of a 128
17487 /// root share one index -- while the encoder's CDEF search prices a
17488 /// preset per unit and its filter replay applied all four. Only the first
17489 /// reached the stream, so every decoder filtered the other three with the
17490 /// origin's strengths and the encoder's reconstruction (the picture the
17491 /// next frame predicts from) was a filter apart from what a decoder
17492 /// produces. RED before this lane on the native BD gate's bars 2160p row
17493 /// (`EC_AV1_B128RES=1`, q=90, frame 11: 8 luma and 702 chroma samples,
17494 /// the rows above the 128 superblock's own edge); the stream itself was
17495 /// always right -- ffmpeg and our own decoder agreed with each other and
17496 /// disagreed with the encoder.
17497 ///
17498 /// `take_cdef_covered_units` is the gate on the fixture (class
17499 /// `gate-blind-to-feature`): a clip whose CDEF picks one strength pair
17500 /// for the whole frame codes no literal at all and witnesses nothing.
17501 ///
17502 /// cargo test -p ec-av1 --release --lib -- --ignored \
17503 /// a_128_root_residual_block_under_a_per_unit_cdef --nocapture
17504 #[test]
17505 #[ignore = "sets the process-global superblock size: run it alone"]
17506 fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() {
17507 let _knobs = crate::speed::knob_write();
17508 if !have_ffmpeg() {
17509 eprintln!("SKIP: no ffmpeg");
17510 return;
17511 }
17512 force_sb128(true);
17513 let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id()));
17514 std::fs::create_dir_all(&dir).unwrap();
17515 let clip = dir.join("testsrc2-1280x768.y4m");
17516 // Detailed synthetic content: its CDEF search spends more than one
17517 // strength pair, which is what puts a `cdef_idx` literal in the tile.
17518 let ok = Command::new("ffmpeg")
17519 .args(["-v", "error", "-y", "-f", "lavfi"])
17520 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17521 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17522 .arg(&clip)
17523 .status()
17524 .expect("ffmpeg failed to run")
17525 .success();
17526 assert!(ok, "ffmpeg could not write the synthetic clip");
17527 let (width, height) = (1280usize, 768usize);
17528 let pictures =
17529 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17530 force_b128_root(true);
17531 force_b128_residual(true);
17532 let _ = crate::tile::take_sb128_residual_hits();
17533 let _ = crate::filter_search::take_cdef_covered_units();
17534 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
17535 let coded = crate::tile::take_sb128_residual_hits();
17536 let covered = crate::filter_search::take_cdef_covered_units();
17537 eprintln!(
17538 "128x128 blocks WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
17539 another unit's literal: {covered}"
17540 );
17541 assert!(coded > 0, "no 128x128 block carried a residual on this clip");
17542 assert!(
17543 covered > 0,
17544 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
17545 cannot witness the rule",
17546 );
17547 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17548 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17549 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17550 for (plane, got, want) in [
17551 ("luma", &dec.y, &frame.reconstruction.y),
17552 ("U", &dec.u, &frame.reconstruction.u),
17553 ("V", &dec.v, &frame.reconstruction.v),
17554 ] {
17555 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17556 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17557 }
17558 }
17559 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17560 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17561 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17562 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17563 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17564 }
17565 }
17566
17567 /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves
17568 /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a
17569 /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now
17570 /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own
17571 /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the
17572 /// rect partition with [`force_b128_rect`]) so every inter root of the
17573 /// clip goes through it; the `coded > 0` assert is the guard that catches
17574 /// the next fixture drift (the whole-128 twin of this witness went RED
17575 /// twice that way).
17576 ///
17577 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17578 /// encode::tests::a_rect128_half_with_a_real_residual --nocapture
17579 #[test]
17580 #[ignore = "sets the process-global superblock size: run it alone"]
17581 fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
17582 let _knobs = crate::speed::knob_write();
17583 if !have_ffmpeg() {
17584 eprintln!("SKIP: no ffmpeg");
17585 return;
17586 }
17587 force_sb128(true);
17588 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
17589 std::fs::create_dir_all(&dir).unwrap();
17590 let clip = dir.join("smpte-pan-1280x768.y4m");
17591 let ok = Command::new("ffmpeg")
17592 .args(["-v", "error", "-y", "-f", "lavfi"])
17593 .args(["-i", "smptebars=size=1600x768:rate=24"])
17594 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17595 .args(["-pix_fmt", "yuv420p"])
17596 .arg(&clip)
17597 .status()
17598 .expect("ffmpeg failed to run")
17599 .success();
17600 assert!(ok, "ffmpeg could not write the synthetic clip");
17601 let (width, height) = (1280usize, 768usize);
17602 let pictures =
17603 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17604 force_b128_rect(1);
17605 force_b128_rectres(true);
17606 let _ = take_b128_rectres_hits();
17607 let _ = crate::tile::take_sb128_rectres_hits();
17608 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17609 let (won, coded) =
17610 (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17611 eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}");
17612 assert!(
17613 coded > 0,
17614 "no 128x64 half carried a residual on this clip, so it cannot witness the arm",
17615 );
17616 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17617 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17618 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17619 let recon = &frame.reconstruction;
17620 for (plane, got, want) in [
17621 ("luma", &dec.y, &recon.y),
17622 ("U", &dec.u, &recon.u),
17623 ("V", &dec.v, &recon.v),
17624 ] {
17625 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17626 assert_eq!(
17627 differ, 0,
17628 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17629 own reconstruction",
17630 got.len()
17631 );
17632 }
17633 }
17634 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17635 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17636 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17637 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17638 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17639 }
17640 }
17641
17642 /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE
17643 /// pieces carry residuals -- the 128x64 half through the two-chunk arm,
17644 /// the two 64x64 squares through the one-chunk arm (the shape libaom's
17645 /// own AB partitions earn their keep with). testsrc2 at 12 frames, the
17646 /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose
17647 /// reference picture the GOP has not produced yet, which refuses before
17648 /// any AB root is coded.
17649 ///
17650 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17651 /// encode::tests::an_ab128_piece_with_a_real_residual --nocapture
17652 #[test]
17653 #[ignore = "sets the process-global superblock size: run it alone"]
17654 fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
17655 let _knobs = crate::speed::knob_write();
17656 if !have_ffmpeg() {
17657 eprintln!("SKIP: no ffmpeg");
17658 return;
17659 }
17660 force_sb128(true);
17661 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
17662 std::fs::create_dir_all(&dir).unwrap();
17663 let clip = dir.join("testsrc2-1280x768.y4m");
17664 let ok = Command::new("ffmpeg")
17665 .args(["-v", "error", "-y", "-f", "lavfi"])
17666 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17667 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17668 .arg(&clip)
17669 .status()
17670 .expect("ffmpeg failed to run")
17671 .success();
17672 assert!(ok, "ffmpeg could not write the synthetic clip");
17673 let (width, height) = (1280usize, 768usize);
17674 let pictures =
17675 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17676 force_b128_ab(4);
17677 force_b128_rectres(true);
17678 let _ = take_b128_rectres_hits();
17679 let _ = crate::tile::take_sb128_rectres_hits();
17680 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17681 let (won, coded) =
17682 (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17683 eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}");
17684 assert!(
17685 coded > 0,
17686 "no AB piece carried a residual on this clip, so it cannot witness the arm",
17687 );
17688 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17689 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17690 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17691 let recon = &frame.reconstruction;
17692 for (plane, got, want) in [
17693 ("luma", &dec.y, &recon.y),
17694 ("U", &dec.u, &recon.u),
17695 ("V", &dec.v, &recon.v),
17696 ] {
17697 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17698 assert_eq!(
17699 differ, 0,
17700 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17701 own reconstruction",
17702 got.len()
17703 );
17704 }
17705 }
17706 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17707 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17708 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17709 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17710 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17711 }
17712 }
17713
17714 /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ
17715 /// half WITH a residual under a clip whose CDEF search codes a
17716 /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin
17717 /// and the decoder stamps BOTH units it spans with it, so the owner map
17718 /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to
17719 /// collapse the pair -- exactly the bug class that broke bars 2160p at
17720 /// the whole-128 root. RED before this lane by construction: no rect
17721 /// piece could carry a residual, so no such literal existed.
17722 ///
17723 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17724 /// encode::tests::a_rect128_residual_half_under_a_per_unit_cdef --nocapture
17725 #[test]
17726 #[ignore = "sets the process-global superblock size: run it alone"]
17727 fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
17728 let _knobs = crate::speed::knob_write();
17729 if !have_ffmpeg() {
17730 eprintln!("SKIP: no ffmpeg");
17731 return;
17732 }
17733 force_sb128(true);
17734 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
17735 std::fs::create_dir_all(&dir).unwrap();
17736 let clip = dir.join("testsrc2-1280x768.y4m");
17737 // Detailed synthetic content: its CDEF search spends more than one
17738 // strength pair, which is what puts a `cdef_idx` literal in the tile.
17739 let ok = Command::new("ffmpeg")
17740 .args(["-v", "error", "-y", "-f", "lavfi"])
17741 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17742 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17743 .arg(&clip)
17744 .status()
17745 .expect("ffmpeg failed to run")
17746 .success();
17747 assert!(ok, "ffmpeg could not write the synthetic clip");
17748 let (width, height) = (1280usize, 768usize);
17749 let pictures =
17750 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17751 force_b128_rect(1);
17752 force_b128_rectres(true);
17753 let _ = crate::tile::take_sb128_rectres_hits();
17754 let _ = crate::filter_search::take_cdef_covered_units();
17755 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
17756 let coded = crate::tile::take_sb128_rectres_hits();
17757 let covered = crate::filter_search::take_cdef_covered_units();
17758 eprintln!(
17759 "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
17760 another unit's literal: {covered}"
17761 );
17762 assert!(coded > 0, "no 128x64 half carried a residual on this clip");
17763 assert!(
17764 covered > 0,
17765 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
17766 cannot witness the rule",
17767 );
17768 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17769 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17770 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17771 for (plane, got, want) in [
17772 ("luma", &dec.y, &frame.reconstruction.y),
17773 ("U", &dec.u, &frame.reconstruction.u),
17774 ("V", &dec.v, &frame.reconstruction.v),
17775 ] {
17776 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17777 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17778 }
17779 }
17780 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17781 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17782 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17783 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17784 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17785 }
17786 }
17787
17788 /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
17789 /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
17790 /// `write_compound_block` chain every smaller compound block takes, at a
17791 /// window it had never been exercised at. RED before this lane: the
17792 /// search passed an empty compound list at the 128 root, so the count was
17793 /// 0 and no such block existed to decode.
17794 ///
17795 /// cargo test -p ec-av1 --release --lib -- --ignored \
17796 /// a_128_root_compound_block --nocapture
17797 #[test]
17798 #[ignore = "sets the process-global superblock size: run it alone"]
17799 fn a_128_root_compound_block_decodes_exact_through_both_decoders() {
17800 let _knobs = crate::speed::knob_write();
17801 if !have_ffmpeg() {
17802 eprintln!("SKIP: no ffmpeg");
17803 return;
17804 }
17805 force_sb128(true);
17806 let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id()));
17807 std::fs::create_dir_all(&dir).unwrap();
17808 let clip = dir.join("testsrc2-1280x768.y4m");
17809 // Moving objects that occlude each other: a pan is coded by one
17810 // reference outright, and a compound pair only pays where the two
17811 // references disagree.
17812 let ok = Command::new("ffmpeg")
17813 .args(["-v", "error", "-y", "-f", "lavfi"])
17814 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17815 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17816 .arg(&clip)
17817 .status()
17818 .expect("ffmpeg failed to run")
17819 .success();
17820 assert!(ok, "ffmpeg could not write the synthetic clip");
17821 let (width, height) = (1280usize, 768usize);
17822 let pictures =
17823 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17824 // The compound candidate wins the 128 block's own search on this pan
17825 // but the root then loses to its four cells, so the root is forced
17826 // (the residual arm is left at its default, off).
17827 force_b128_root(true);
17828 let _ = take_b128_compound_hits();
17829 let _ = crate::tile::take_sb128_compound_hits();
17830 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17831 let (won, coded) =
17832 (take_b128_compound_hits(), crate::tile::take_sb128_compound_hits());
17833 eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}");
17834 assert!(coded > 0, "no compound 128x128 block was coded on this clip");
17835 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17836 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17837 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17838 for (plane, got, want) in [
17839 ("luma", &dec.y, &frame.reconstruction.y),
17840 ("U", &dec.u, &frame.reconstruction.u),
17841 ("V", &dec.v, &frame.reconstruction.v),
17842 ] {
17843 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17844 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17845 }
17846 }
17847 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17848 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17849 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17850 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17851 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17852 }
17853 }
17854
17855 /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT`
17856 /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one
17857 /// square. Three passes over one `testsrc2` clip:
17858 ///
17859 /// * HORZ forced at every root ([`force_b128_rect`]), so every context
17860 /// the 128x64 shape reads is exercised rather than the handful the RD
17861 /// would pick;
17862 /// * VERT forced the same way;
17863 /// * UNFORCED, which is the count the gate rows are read against -- the
17864 /// same clip with the RD free to choose among NONE / HORZ / VERT /
17865 /// four superblocks.
17866 ///
17867 /// Each pass is sample-exact against the encoder's own reconstruction
17868 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
17869 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
17870 /// before this lane by construction: `write_sb128_root` could only name
17871 /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three.
17872 ///
17873 /// cargo test -p ec-av1 --release --lib -- --ignored \
17874 /// a_128_root_horz_and_vert --nocapture
17875 #[test]
17876 #[ignore = "sets the process-global superblock size: run it alone"]
17877 fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {
17878 let _knobs = crate::speed::knob_write();
17879 if !have_ffmpeg() {
17880 eprintln!("SKIP: no ffmpeg");
17881 return;
17882 }
17883 force_sb128(true);
17884 let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));
17885 std::fs::create_dir_all(&dir).unwrap();
17886 let clip = dir.join("testsrc2-1280x768.y4m");
17887 let ok = Command::new("ffmpeg")
17888 .args(["-v", "error", "-y", "-f", "lavfi"])
17889 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17890 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17891 .arg(&clip)
17892 .status()
17893 .expect("ffmpeg failed to run")
17894 .success();
17895 assert!(ok, "ffmpeg could not write the synthetic clip");
17896 let (width, height) = (1280usize, 768usize);
17897 let pictures =
17898 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17899 let mut unforced = (0usize, 0usize);
17900 for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] {
17901 force_b128_rect(force);
17902 let _ = take_b128_horz_hits();
17903 let _ = take_b128_vert_hits();
17904 let _ = crate::tile::take_sb128_horz_hits();
17905 let _ = crate::tile::take_sb128_vert_hits();
17906 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17907 let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits());
17908 let (coded_h, coded_v) = (
17909 crate::tile::take_sb128_horz_hits(),
17910 crate::tile::take_sb128_vert_hits(),
17911 );
17912 eprintln!(
17913 "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \
17914 {coded_h} 128x64 + {coded_v} 64x128 halves"
17915 );
17916 match force {
17917 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"),
17918 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"),
17919 // The unforced count is REPORTED, not asserted: it is the
17920 // number the gate is read against, and a zero here would be
17921 // an RD result, not a defect (the forced passes already prove
17922 // the writer and the reader agree on the shape).
17923 _ => unforced = (won_h, won_v),
17924 }
17925 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17926 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
17927 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17928 for (plane, got, want) in [
17929 ("luma", &dec.y, &frame.reconstruction.y),
17930 ("U", &dec.u, &frame.reconstruction.u),
17931 ("V", &dec.v, &frame.reconstruction.v),
17932 ] {
17933 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17934 assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ");
17935 }
17936 }
17937 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17938 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17939 assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma");
17940 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
17941 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
17942 }
17943 }
17944 force_b128_rect(0);
17945 eprintln!(
17946 "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames",
17947 unforced.0, unforced.1
17948 );
17949 }
17950
17951 /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
17952 /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.
17953 /// Five passes over the same `testsrc2` clip
17954 /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
17955 /// uses: each shape forced at every root ([`force_b128_ab`]), so every
17956 /// context and every visit order the shape reads is exercised rather than
17957 /// the handful the RD would pick, and then an UNFORCED pass whose
17958 /// per-shape count is REPORTED (it is the number the gate rows are read
17959 /// against).
17960 ///
17961 /// Each pass is sample-exact against the encoder's own reconstruction
17962 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
17963 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
17964 /// before this lane by construction: `write_sb128_root` could only name
17965 /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.
17966 ///
17967 /// cargo test -p ec-av1 --release --lib -- --ignored \
17968 /// a_128_root_ab_shapes --nocapture
17969 #[test]
17970 #[ignore = "sets the process-global superblock size: run it alone"]
17971 fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
17972 let _knobs = crate::speed::knob_write();
17973 if !have_ffmpeg() {
17974 eprintln!("SKIP: no ffmpeg");
17975 return;
17976 }
17977 force_sb128(true);
17978 let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
17979 std::fs::create_dir_all(&dir).unwrap();
17980 let clip = dir.join("testsrc2-1280x768.y4m");
17981 let ok = Command::new("ffmpeg")
17982 .args(["-v", "error", "-y", "-f", "lavfi"])
17983 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17984 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17985 .arg(&clip)
17986 .status()
17987 .expect("ffmpeg failed to run")
17988 .success();
17989 assert!(ok, "ffmpeg could not write the synthetic clip");
17990 let (width, height) = (1280usize, 768usize);
17991 let pictures =
17992 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17993 let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"];
17994 let mut unforced = [0usize; 4];
17995 for force in [4u8, 5, 6, 7, 0] {
17996 force_b128_ab(force);
17997 let label = if force == 0 { "unforced" } else { names[usize::from(force) - 4] };
17998 let _ = take_b128_ab_hits();
17999 let _ = crate::tile::take_sb128_ab_hits();
18000 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
18001 let won = take_b128_ab_hits();
18002 let coded = crate::tile::take_sb128_ab_hits();
18003 eprintln!(
18004 "{label}: search won {won:?} AB roots, writer coded {coded:?} \
18005 (HORZ_A/HORZ_B/VERT_A/VERT_B)"
18006 );
18007 if force == 0 {
18008 // The unforced counts are REPORTED, not asserted: a zero here
18009 // would be an RD result, not a defect (the four forced passes
18010 // already prove the writer and the reader agree on the shape).
18011 unforced = won;
18012 } else {
18013 let i = usize::from(force) - 4;
18014 assert!(coded[i] > 0, "no {label} root was coded with {label} forced");
18015 }
18016 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18017 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
18018 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18019 for (plane, got, want) in [
18020 ("luma", &dec.y, &frame.reconstruction.y),
18021 ("U", &dec.u, &frame.reconstruction.u),
18022 ("V", &dec.v, &frame.reconstruction.v),
18023 ] {
18024 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
18025 assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ");
18026 }
18027 }
18028 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
18029 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
18030 assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma");
18031 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
18032 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
18033 }
18034 }
18035 force_b128_ab(0);
18036 eprintln!(
18037 "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B",
18038 unforced[0], unforced[1], unforced[2], unforced[3],
18039 );
18040 }
18041
18042 #[test]
18043 #[ignore = "sets the process-global superblock size: run it alone"]
18044 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
18045 let _knobs = crate::speed::knob_write();
18046 if !have_ffmpeg() {
18047 eprintln!("SKIP: no ffmpeg");
18048 return;
18049 }
18050 force_sb128(true);
18051 let dir = std::env::temp_dir().join(format!("ec-av1-sb128b-{}", std::process::id()));
18052 std::fs::create_dir_all(&dir).unwrap();
18053 let clip = dir.join("mandelbrot-1280x768.y4m");
18054 let ok = Command::new("ffmpeg")
18055 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "mandelbrot=size=1280x768:rate=24"])
18056 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
18057 .arg(&clip)
18058 .status()
18059 .expect("ffmpeg failed to run")
18060 .success();
18061 assert!(ok, "ffmpeg could not write the synthetic clip");
18062 let path = clip.to_str().unwrap();
18063 let (width, height) = (1280usize, 768usize);
18064 let pictures = crate::probe::source(path, "0", "null", width, height, 12);
18065
18066 let _ = crate::tile::take_drl_clamp_hits();
18067 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
18068 let clamps = crate::tile::take_drl_clamp_hits();
18069 assert!(
18070 clamps > 0,
18071 "this clip never asked for a drl index the write-time stack could not carry, \
18072 so it cannot witness the defect"
18073 );
18074 eprintln!("clamped drl indices: {clamps}");
18075
18076 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18077 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18078 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18079 let recon = &frame.reconstruction;
18080 for (plane, got, want) in [
18081 ("luma", &dec.y, &recon.y),
18082 ("U", &dec.u, &recon.u),
18083 ("V", &dec.v, &recon.v),
18084 ] {
18085 let differ = got.iter().zip(want).filter(|(a, b)| a != b).count();
18086 assert_eq!(
18087 differ, 0,
18088 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
18089 own reconstruction",
18090 got.len()
18091 );
18092 }
18093 }
18094 }
18095
18096 #[test]
18097 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
18098 let _knobs = crate::speed::knob_read();
18099 let fctx = &crate::decode::FrameCtx::for_encoder();
18100 // 256x128, not the 128x64 this started at: once a leaf could search
18101 // its second reference (lane-av1comp4) the small card's every
18102 // eligible block went to a compound winner, which commits its flat
18103 // transform, and the split below stopped firing on content that
18104 // still splits at every larger size ([[gate-blind-to-feature]] --
18105 // the guard is right, the fixture had shrunk under it).
18106 let (width, height) = (256usize, 128usize);
18107 let pictures: Vec<Picture> =
18108 (0..5).map(|i| panned_test_card(width, height, i * 3)).collect();
18109 let _ = take_inter_tx_split_hits();
18110 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18111 let raw = take_inter_tx_split_hits();
18112 // Summed over the four block classes the census keys on (leaf/32x32 x
18113 // single/compound): this assert is about the split firing at all.
18114 let split = [
18115 raw.iter().step_by(2).sum::<usize>(),
18116 raw.iter().skip(1).step_by(2).sum::<usize>(),
18117 ];
18118 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
18119 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
18120 // content splits -- a green round trip in which the split never fires
18121 // would prove only the flat path.
18122 if tx_select() && tx_select_inter() {
18123 assert!(split[1] > 0, "the inter var-tx split never fired");
18124 }
18125 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18126 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18127 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18128 let recon = &frame.reconstruction;
18129 for (plane, got, want, stride) in [
18130 ("luma", &dec.y, &recon.y, width),
18131 ("U", &dec.u, &recon.u, width / 2),
18132 ("V", &dec.v, &recon.v, width / 2),
18133 ] {
18134 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
18135 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
18136 panic!(
18137 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
18138 reconstruction {} ({} of {} samples differ)",
18139 at % stride,
18140 at / stride,
18141 got[at],
18142 want[at],
18143 got.iter().zip(want).filter(|(a, b)| a != b).count(),
18144 got.len(),
18145 );
18146 }
18147 }
18148 }
18149 }
18150
18151 /// The rate term the mode search ranks every decision by has to be the
18152 /// rate the writer then spends. The search prices a block's coefficients
18153 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
18154 /// against the default CDFs a tile starts from and the contexts of a
18155 /// block whose neighbours coded nothing -- while the tile writer codes
18156 /// them against a state that has been adapting all frame (the
18157 /// price-the-narrowing class). This measures that drift: the sum of what
18158 /// the search paid for the coefficients it kept, against the bytes the
18159 /// writer actually emitted for the whole tile (which also carries the
18160 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
18161 /// expected to be the larger of the two).
18162 #[test]
18163 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
18164 let _knobs = crate::speed::knob_read();
18165 let fctx = &crate::decode::FrameCtx::for_encoder();
18166 let (width, height) = (256usize, 128usize);
18167 let pictures: Vec<Picture> = (0..5)
18168 .map(|i| panned_test_card(width, height, i * 2))
18169 .collect();
18170 let _ = take_predicted_bits();
18171 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18172 let predicted = take_predicted_bits();
18173 assert_eq!(predicted.len(), encoded.frames.len());
18174
18175 eprintln!("frame predicted bits written bits drift");
18176 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
18177 // defect this gate exists to catch), a positive one is the written
18178 // side carrying syntax the coefficient sum leaves out -- and since
18179 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
18180 // on that side, so the two directions no longer share a bound.
18181 let mut worst_over: f64 = 0.0;
18182 let mut worst_under: f64 = 0.0;
18183 // The census is per CODED frame, so it is zipped in coding order --
18184 // which is not display order under a pyramid.
18185 let coded: Vec<&Encoded> =
18186 encoded.coding_order.iter().map(|&i| &encoded.frames[i]).collect();
18187 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
18188 let written = frame.tile.len() as f64 * 8.0;
18189 let drift = (written - bits) / written;
18190 worst_over = worst_over.max(-drift);
18191 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
18192 // all (150-250 bits of tile, nearly all of it partition/mode/mv
18193 // syntax the coefficient sum never counts), so its ratio measures
18194 // that floor rather than any drift. Frames under 512 written bits
18195 // are left out of the under-price bound for that reason; the
18196 // over-price bound -- the defect direction, where the search pays
18197 // MORE than the writer -- still covers every frame.
18198 if written >= 512.0 {
18199 worst_under = worst_under.max(drift);
18200 }
18201 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
18202 }
18203 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
18204 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
18205 // over-prices every frame but the last (its sum EXCLUDES the
18206 // partition/mode/skip/mv syntax the written side carries, so the true
18207 // coefficient over-price is larger still): the writer's CDFs adapt to
18208 // the content while the search's stay at the defaults. The bound is
18209 // set just above the worst measured point -- a widening drift is the
18210 // thing this gate exists to catch.
18211 assert!(
18212 worst_over <= 0.16,
18213 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
18214 worst_over * 100.0
18215 );
18216 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
18217 // the worst inter frame, where nearly every block now codes an MV
18218 // residual and a reference the coefficient sum never counts. Re-measured
18219 // at +29.6% once the encoder's grid published compound blocks properly
18220 // (compound share 8.8% -> 11.5%): a compound block carries a second
18221 // reference tree, a compound mode symbol and -- for the half-new modes
18222 // -- an MV residual, none of which the coefficient sum counts.
18223 // lane-av1txbits: pricing against the tables the frame's writer really
18224 // starts from collapses the over-price above to nothing, so the whole
18225 // remaining gap is the syntax the coefficient sum leaves out. That is
18226 // the default on a non-screen frame since lane-av1price2 (this
18227 // fixture is one), and it reads +32.6% here.
18228 // lane-av1obmc: every eligible single-reference inter block now also
18229 // carries a `motion_mode` symbol the coefficient sum never counts,
18230 // and an OBMC block carries the more expensive of the two values --
18231 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
18232 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
18233 // decisions, so this bound and the byte pins above FAIL BY DESIGN
18234 // under it; the default path (no motion_mode syntax at all) is the
18235 // one they are measured on.
18236 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
18237 // coding pyramid now, so the five frames are a key frame, a hidden
18238 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
18239 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
18240 // near-empty leaves below it. Both bounds stand where they were.
18241 // lane-av1rejudge: local warp is ON by default now, so every eligible
18242 // single-reference block carries that same `motion_mode` symbol (a
18243 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
18244 // +34.9% here, one point past the OBMC reading above. The bound moves
18245 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
18246 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
18247 // symbol and one or two magnitude symbols, none of which the
18248 // coefficient sum counts either -- +36.9% here against the same
18249 // fixture's +34.9% with `EC_AV1_CFL=0`.
18250 // ... and a directional block whose `angle_delta_y` is no longer
18251 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
18252 assert!(
18253 worst_under <= 0.40,
18254 "the writer spent {:.2}% more than the search priced -- more than \
18255 the mode/mv syntax outside the coefficient sum explains",
18256 worst_under * 100.0
18257 );
18258 }
18259
18260 /// The census behind step (1) of the pricer lane: for every transform
18261 /// block the writer really codes, what the search priced those levels at
18262 /// against what the writer spent on them, split by table set and non-zero
18263 /// count. One average hides the interesting part -- the classes the
18264 /// estimate is systematically wrong about (all-zero blocks, the
18265 /// one-coefficient blocks the inter search lives on) -- so the split is
18266 /// printed and only the total is asserted on.
18267 #[test]
18268 fn pricer_error_census_by_block_class() {
18269 let _knobs = crate::speed::knob_read();
18270 let fctx = &crate::decode::FrameCtx::for_encoder();
18271 let (width, height) = (256usize, 128usize);
18272 let pictures: Vec<Picture> = (0..5)
18273 .map(|i| panned_test_card(width, height, i * 2))
18274 .collect();
18275 crate::tile::pricer_census_on();
18276 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18277 let rows = crate::tile::take_pricer_census();
18278 assert!(!rows.is_empty(), "the census saw no transform block");
18279
18280 println!("| set | nz | blocks | priced bits | written bits | error |");
18281 println!("|---|---|---|---|---|---|");
18282 let (mut priced_all, mut written_all) = (0.0, 0.0);
18283 for ((set, bucket), (blocks, priced, written)) in &rows {
18284 priced_all += priced;
18285 written_all += written;
18286 println!(
18287 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
18288 crate::tile::census_bucket_label(*bucket),
18289 if *written > 0.0 {
18290 (priced - written) / written * 100.0
18291 } else {
18292 0.0
18293 }
18294 );
18295 }
18296 println!(
18297 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
18298 rows.values().map(|r| r.0).sum::<u64>(),
18299 (priced_all - written_all) / written_all * 100.0
18300 );
18301 assert!(written_all > 0.0);
18302 }
18303
18304 /// Step (2) of the pricer lane: the same census, but on the REAL clips
18305 /// the BD gate scores -- one film clip and the screen capture -- so the
18306 /// question the film/screen split raises can be answered from data. Real
18307 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
18308 /// the screen capture larger, and the census says why: on a screen
18309 /// capture the frame's own starting tables are the tables of a frame that
18310 /// coded PALETTE and long runs of zero blocks, so they are far from the
18311 /// tables the writer ends the frame with; the pricer error does not fall
18312 /// the way it does on film.
18313 ///
18314 /// Not a gate -- it prints. Run it once per mode:
18315 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
18316 /// --ignored pricer_error_census_on_clips --nocapture
18317 #[test]
18318 #[ignore = "reads the real library, needs ffmpeg"]
18319 fn pricer_error_census_on_clips() {
18320 let _knobs = crate::speed::knob_write();
18321 if !have_ffmpeg() {
18322 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
18323 return;
18324 }
18325 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
18326 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
18327 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
18328 if film.exists() {
18329 clips.push(("film 1080p".to_string(), film));
18330 }
18331 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
18332 && let Some(p) = manifest
18333 .lines()
18334 .skip(1)
18335 .filter_map(|l| l.split('\t').next())
18336 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
18337 {
18338 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
18339 }
18340 assert!(!clips.is_empty(), "no source clip available");
18341 let (width, height, frames) = (640usize, 384usize, 6usize);
18342 for (name, path) in &clips {
18343 let fctx = &crate::decode::FrameCtx::for_encoder();
18344 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
18345 SCREEN_FRAMES.iter().for_each(|c| {
18346 c.store(0, std::sync::atomic::Ordering::Relaxed);
18347 });
18348 let _ = crate::tile::take_pricing_hits();
18349 crate::tile::pricer_census_on();
18350 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18351 let rows = crate::tile::take_pricer_census();
18352 let (price_default, price_real) = crate::tile::take_pricing_hits();
18353 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
18354 println!(
18355 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
18356 {screen_on}, pricer armings default={price_default} real={price_real}"
18357 );
18358 println!("| set | nz | blocks | priced bits | written bits | error |");
18359 println!("|---|---|---|---|---|---|");
18360 let (mut priced_all, mut written_all) = (0.0, 0.0);
18361 for ((set, bucket), (blocks, priced, written)) in &rows {
18362 priced_all += priced;
18363 written_all += written;
18364 println!(
18365 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
18366 crate::tile::census_bucket_label(*bucket),
18367 if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 }
18368 );
18369 }
18370 println!(
18371 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
18372 rows.values().map(|r| r.0).sum::<u64>(),
18373 (priced_all - written_all) / written_all * 100.0
18374 );
18375 assert!(written_all > 0.0, "{name}: the census saw no transform block");
18376 }
18377 }
18378
18379 /// Low motion has to actually buy something: at least one inter frame of
18380 /// a panning sequence has to cost fewer bytes than the key frame that
18381 /// starts it, and the inter-block share it prints has to be non-zero --
18382 /// a search that never picks an inter mode would still pass a rate gate
18383 /// on a picture with no motion in it (the class this repo calls
18384 /// gate-blind-to-feature), so the share is printed even though it is not
18385 /// asserted on beyond being reachable at all.
18386 #[test]
18387 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
18388 let _knobs = crate::speed::knob_read();
18389 let fctx = &crate::decode::FrameCtx::for_encoder();
18390 let (width, height) = (256usize, 128usize);
18391 let pictures: Vec<Picture> = (0..5)
18392 .map(|i| panned_test_card(width, height, i * 2))
18393 .collect();
18394 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18395
18396 let key_bytes = encoded.frames[0].stream.len();
18397 eprintln!("frame bytes inter share");
18398 for (i, frame) in encoded.frames.iter().enumerate() {
18399 eprintln!(
18400 "{i:5} {:5} {:11.2}",
18401 frame.stream.len(),
18402 frame.inter_block_share
18403 );
18404 }
18405 assert!(
18406 encoded.frames[1..]
18407 .iter()
18408 .any(|f| f.stream.len() < key_bytes),
18409 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
18410 );
18411 assert!(
18412 encoded.frames[1..]
18413 .iter()
18414 .any(|f| f.inter_block_share > 0.0),
18415 "no inter frame coded a single inter block -- the search never fired"
18416 );
18417 }
18418
18419 /// A manual perf probe, not a gate: prints where a key frame's and an
18420 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
18421 /// measures before it optimizes rather than guessing. Run with
18422 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
18423 #[test]
18424 #[ignore = "a perf probe, not a gate"]
18425 fn stage_timing_breakdown() {
18426 let _knobs = crate::speed::knob_read();
18427 let fctx = &crate::decode::FrameCtx::for_encoder();
18428 use std::time::Instant;
18429
18430 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
18431 let picture = test_card(width, height);
18432
18433 let t = Instant::now();
18434 let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
18435 let dc_only_t = t.elapsed();
18436
18437 let t = Instant::now();
18438 let non_directional =
18439 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
18440 let non_directional_t = t.elapsed();
18441
18442 let t = Instant::now();
18443 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18444 let all_modes_t = t.elapsed();
18445
18446 eprintln!(
18447 "\n=== key frame {width}x{height} ===\n\
18448 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
18449 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
18450 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
18451 dc_only.stream.len(),
18452 non_directional.stream.len(),
18453 all_modes.stream.len(),
18454 );
18455
18456 // One inter frame predicting off the key frame's own
18457 // reconstruction, the (256, 256)-padded surface encode_sequence
18458 // itself would hand encode_inter_frame.
18459 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
18460 let padded_pic = picture.padded_to(SUPERBLOCK);
18461 let t = Instant::now();
18462 let inter =
18463 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();
18464 let inter_t = t.elapsed();
18465 eprintln!(
18466 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
18467 {:.2})",
18468 inter.stream.len(),
18469 inter.inter_block_share
18470 );
18471 }
18472
18473 // Isolated per-call cost of the trial pipeline's own stages, at both
18474 // transform sizes the search runs, averaged over enough calls to
18475 // rise above `Instant::now`'s own noise.
18476 for side in [16usize, 32] {
18477 const N: u32 = 20_000;
18478 let residual: Vec<i32> = (0..side * side)
18479 .map(|i| ((i * 37 % 61) as i32) - 30)
18480 .collect();
18481
18482 let t = Instant::now();
18483 let mut levels = Vec::new();
18484 for _ in 0..N {
18485 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
18486 }
18487 let forward_t = t.elapsed() / N;
18488
18489 let t = Instant::now();
18490 for _ in 0..N {
18491 std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
18492 }
18493 let inverse_t = t.elapsed() / N;
18494
18495 let set = if side == 32 {
18496 crate::cdf_state::TxbSet::Luma32
18497 } else {
18498 crate::cdf_state::TxbSet::Luma16
18499 };
18500 let t = Instant::now();
18501 for _ in 0..N {
18502 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
18503 }
18504 let entropy_t = t.elapsed() / N;
18505
18506 let above = vec![128u8; side * 2];
18507 let left = vec![128u8; side * 2];
18508 let mut prediction = vec![0u8; side * side];
18509 let t = Instant::now();
18510 for _ in 0..N {
18511 intra_predict_u8(
18512 D45_PRED,
18513 0,
18514 Some(&above),
18515 Some(&left),
18516 Some(128),
18517 side,
18518 side,
18519 false,
18520 false,
18521 &mut prediction, fctx,
18522 );
18523 }
18524 let predict_t = t.elapsed() / N;
18525
18526 eprintln!(
18527 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
18528 predict (1 directional mode): {predict_t:>9.2?}\n\
18529 forward_and_quantize: {forward_t:>9.2?}\n\
18530 dequant_and_inverse: {inverse_t:>9.2?}\n\
18531 coeff_bits: {entropy_t:>9.2?}"
18532 );
18533 }
18534 }
18535
18536 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
18537 /// (motion search, [`crate::mc::predict`], transform+quantize,
18538 /// `coeff_bits`), plus what is left over once those are subtracted --
18539 /// the thirteen-mode intra-candidate loop `search_inter_block` still
18540 /// runs on every inter block (its own transform/quant/entropy calls are
18541 /// already inside buckets 2/3, so "left over" here is everything NOT
18542 /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
18543 /// symbol-cost lookups outside `coeff_bits`).
18544 ///
18545 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
18546 #[test]
18547 #[ignore = "a perf probe, not a gate"]
18548 fn stage_timing_breakdown_inter() {
18549 let _knobs = crate::speed::knob_read();
18550 let fctx = &crate::decode::FrameCtx::for_encoder();
18551 use std::time::Instant;
18552
18553 let (width, height) = (1280usize, 720);
18554 let picture = test_card(width, height);
18555 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18556 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
18557 let padded_pic = picture.padded_to(SUPERBLOCK);
18558
18559 stage_reset();
18560 let t = Instant::now();
18561 let inter =
18562 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();
18563 let total_t = t.elapsed();
18564 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
18565 let accounted = motion_search + transform_quant + entropy;
18566 // motion_search already contains interpolation's own time (every
18567 // candidate the search costs calls crate::mc::predict), so it is not
18568 // added again here -- interpolation is reported alongside as "of
18569 // which interpolation", not as a fifth additive bucket.
18570 let other = total_t.saturating_sub(accounted);
18571
18572 eprintln!(
18573 "\n=== inter frame {width}x{height}, one frame ===\n\
18574 total: {total_t:>9.2?} ({} bytes)\n\
18575 motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
18576 {interpolation:>9.2?})\n\
18577 transform + quantize: {transform_quant:>9.2?}\n\
18578 coeff_bits (entropy pricing): {entropy:>9.2?}\n\
18579 everything else (13-mode intra {other:>9.2?}\n\
18580 candidate loop's own predict/bookkeeping, NEARESTMV's own \
18581 predict, RD glue):",
18582 inter.stream.len(),
18583 );
18584 }
18585
18586 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
18587 /// frames (a dark/flat one, a detailed one, a normal film one) at two
18588 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
18589 /// None`, the baseline this same build produces without
18590 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
18591 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
18592 /// go in the lane report, which is where "ship as default" is decided --
18593 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
18594 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
18595 #[test]
18596 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
18597 fn prune_k_quality_sweep() {
18598 let _knobs = crate::speed::knob_read();
18599 let fctx = &crate::decode::FrameCtx::for_encoder();
18600 if !have_ffmpeg() {
18601 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
18602 return;
18603 }
18604 let (width, height) = (640usize, 352usize);
18605 let frames: &[(&str, &str, &str)] = &[
18606 // (label, clip, seek) -- a near-black scene, a busy one, and an
18607 // ordinary film frame, each from a different real file.
18608 (
18609 "dark/flat",
18610 "/home/user/Videos/reela.mp4",
18611 "3",
18612 ),
18613 (
18614 "detailed",
18615 "/home/user/Downloads/reelb.mkv",
18616 "1200",
18617 ),
18618 (
18619 "film",
18620 "/home/user/Videos/Films/reelc.mkv",
18621 "600",
18622 ),
18623 ];
18624 for &(label, clip, skip) in frames {
18625 if !std::path::Path::new(clip).exists() {
18626 eprintln!("SKIP {label}: {clip} not present on this machine");
18627 continue;
18628 }
18629 let picture = clip_frame(clip, skip, width, height);
18630 for &q in &[60u8, 150] {
18631 // SAFETY (not literally unsafe, just process-global): this is
18632 // a single-threaded #[ignore] probe, run by hand, never
18633 // alongside other tests that read Search::top_k.
18634 set_test_top_k_override(None);
18635 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
18636 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
18637 eprint!(
18638 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
18639 baseline.stream.len(),
18640 baseline_psnr
18641 );
18642 for &k in &[3usize, 4, 6] {
18643 set_test_top_k_override(Some(k));
18644 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
18645 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
18646 eprint!(
18647 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
18648 pruned.stream.len(),
18649 pruned_psnr,
18650 pruned_psnr - baseline_psnr
18651 );
18652 }
18653 eprintln!();
18654 }
18655 }
18656 set_test_top_k_override(None);
18657 }
18658
18659 /// Two consecutive decoded frames from one clip, for an inter-frame
18660 /// sweep -- [`clip_frame`] alone only ever gives one.
18661 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
18662 let out = Command::new("ffmpeg")
18663 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
18664 .args(["-vf", &format!("scale={width}:{height}")])
18665 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
18666 .output()
18667 .expect("ffmpeg failed to run");
18668 assert!(
18669 out.status.success(),
18670 "ffmpeg: {}",
18671 String::from_utf8_lossy(&out.stderr)
18672 );
18673 let (luma, chroma) = (width * height, width * height / 4);
18674 let frame_len = luma + 2 * chroma;
18675 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
18676 std::array::from_fn(|i| {
18677 let bytes = &out.stdout[i * frame_len..][..frame_len];
18678 Picture {
18679 width,
18680 height,
18681 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
18682 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
18683 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
18684 }
18685 })
18686 }
18687
18688 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
18689 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
18690 /// then one inter frame off it (`search_inter_block`'s own intra
18691 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
18692 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
18693 /// padding step complicates the comparison. Prints bytes and luma PSNR
18694 /// for the inter frame alone, unpruned vs each `K`.
18695 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
18696 #[test]
18697 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
18698 fn prune_k_quality_sweep_inter() {
18699 let _knobs = crate::speed::knob_read();
18700 let fctx = &crate::decode::FrameCtx::for_encoder();
18701 if !have_ffmpeg() {
18702 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
18703 return;
18704 }
18705 let (width, height) = (1280usize, 704usize);
18706 let frames: &[(&str, &str, &str)] = &[
18707 (
18708 "dark/flat",
18709 "/home/user/Videos/reela.mp4",
18710 "3",
18711 ),
18712 (
18713 "detailed",
18714 "/home/user/Downloads/reelb.mkv",
18715 "1200",
18716 ),
18717 (
18718 "film",
18719 "/home/user/Videos/Films/reelc.mkv",
18720 "600",
18721 ),
18722 ];
18723 for &(label, clip, skip) in frames {
18724 if !std::path::Path::new(clip).exists() {
18725 eprintln!("SKIP {label}: {clip} not present on this machine");
18726 continue;
18727 }
18728 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
18729 for &q in &[60u8, 150] {
18730 // SAFETY (not literally unsafe, just process-global): a
18731 // single-threaded #[ignore] probe, run by hand, never
18732 // alongside other tests that read Search::top_k.
18733 set_test_top_k_override_inter(None);
18734 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
18735 let baseline = encode_inter_frame(
18736 &inter_source,
18737 &key.reconstruction,
18738 q,
18739 0.5,
18740 1,
18741 flat_order_hints(1, 0, false),
18742 (width, height), None, None, None, None, fctx, None, &[],
18743 )
18744 .unwrap();
18745 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
18746 eprint!(
18747 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
18748 baseline.stream.len(),
18749 baseline_psnr
18750 );
18751 for &k in &[3usize, 4, 6] {
18752 set_test_top_k_override_inter(Some(k));
18753 let pruned = encode_inter_frame(
18754 &inter_source,
18755 &key.reconstruction,
18756 q,
18757 0.5,
18758 1,
18759 flat_order_hints(1, 0, false),
18760 (width, height), None, None, None, None, fctx, None, &[],
18761 )
18762 .unwrap();
18763 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
18764 eprint!(
18765 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
18766 pruned.stream.len(),
18767 pruned_psnr,
18768 pruned_psnr - baseline_psnr
18769 );
18770 }
18771 eprintln!();
18772 }
18773 }
18774 set_test_top_k_override_inter(None);
18775 }
18776
18777 /// `frames` consecutive pictures out of a real clip, scaled to a whole
18778 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
18779 /// to an arbitrary count for the fixture regression gate below.
18780 fn clip_frames(
18781 clip: &str,
18782 skip: &str,
18783 width: usize,
18784 height: usize,
18785 frames: usize,
18786 ) -> Vec<Picture> {
18787 clip_frames_vf(clip, skip, &format!("scale={width}:{height}"), width, height, frames)
18788 }
18789
18790 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
18791 /// for a native-resolution CROP instead of a downscale (the downscale is
18792 /// what destroys a screen capture's exact repeats -- class
18793 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
18794 fn clip_frames_vf(
18795 clip: &str,
18796 skip: &str,
18797 vf: &str,
18798 width: usize,
18799 height: usize,
18800 frames: usize,
18801 ) -> Vec<Picture> {
18802 // ONE definition of the gate's loader recipe, shared with
18803 // `examples/enc_probe` so the instrument cannot arm a different source
18804 // than the gate it reports on (class `instrument disagrees with the
18805 // gate`; lane-probe).
18806 crate::probe::source(clip, skip, vf, width, height, frames)
18807 }
18808
18809 /// The standing regression gate on real content: 12 frames of a real
18810 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
18811 /// this crate's own input regardless of its own source codec), encoded
18812 /// as an AV1 GOP and checked against three numeric floors so a
18813 /// compatibility or quality regression fails the suite instead of
18814 /// waiting for a downstream repo's gate to catch it (as happened for a
18815 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
18816 /// refusal, both caught only that way).
18817 ///
18818 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
18819 /// that geometry is already covered elsewhere), chosen only so encode
18820 /// time and gate numbers are not muddied by an edge-block class this
18821 /// test is not about.
18822 ///
18823 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
18824 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
18825 /// below carry a margin off those measured numbers (PSNR floor =
18826 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
18827 #[test]
18828 fn real_clip_encodes_within_its_quality_and_size_budget() {
18829 let _knobs = crate::speed::knob_read();
18830 let fctx = &crate::decode::FrameCtx::for_encoder();
18831 if !have_ffmpeg() {
18832 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
18833 return;
18834 }
18835 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18836 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
18837 if !clip.exists() {
18838 eprintln!(
18839 "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing",
18840 clip.display()
18841 );
18842 return;
18843 }
18844 let (width, height, frame_count) = (640usize, 384usize, 12usize);
18845 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
18846 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18847 assert_eq!(encoded.frames.len(), frame_count);
18848
18849 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
18850 // stream and hands back every frame -- a stream a downstream
18851 // decoder refuses is the exact class of regression this gate
18852 // exists for.
18853 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
18854 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
18855
18856 // Gate 2: quality vs the source did not silently collapse.
18857 let mean_psnr: f64 = decoded
18858 .iter()
18859 .zip(&source)
18860 .map(|(d, s)| psnr(&d.y, &s.y))
18861 .sum::<f64>()
18862 / frame_count as f64;
18863 assert!(
18864 mean_psnr >= 44.91,
18865 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
18866 );
18867
18868 // Gate 3: the stream did not silently bloat.
18869 assert!(
18870 encoded.stream.len() <= 80_340,
18871 "stream grew to {} bytes, over the 80340-byte ceiling",
18872 encoded.stream.len()
18873 );
18874 }
18875
18876 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
18877 /// straddle size: 640x384 is exact on both axes (32-aligned), so
18878 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
18879 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
18880 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
18881 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
18882 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
18883 /// card; this one is the real-clip gate, same three floors.
18884 ///
18885 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
18886 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
18887 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
18888 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
18889 #[test]
18890 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
18891 let _knobs = crate::speed::knob_read();
18892 let fctx = &crate::decode::FrameCtx::for_encoder();
18893 if !have_ffmpeg() {
18894 eprintln!(
18895 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
18896 no ffmpeg"
18897 );
18898 return;
18899 }
18900 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18901 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
18902 if !clip.exists() {
18903 eprintln!(
18904 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
18905 {} missing",
18906 clip.display()
18907 );
18908 return;
18909 }
18910 let (width, height, frame_count) = (704usize, 400usize, 8usize);
18911 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
18912 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18913 assert_eq!(encoded.frames.len(), frame_count);
18914
18915 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
18916 // stream and hands back every frame.
18917 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
18918 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
18919
18920 // Gate 2: quality vs the source did not silently collapse.
18921 let mean_psnr: f64 = decoded
18922 .iter()
18923 .zip(&source)
18924 .map(|(d, s)| psnr(&d.y, &s.y))
18925 .sum::<f64>()
18926 / frame_count as f64;
18927 assert!(
18928 mean_psnr >= 44.98,
18929 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
18930 );
18931
18932 // Gate 3: the stream did not silently bloat.
18933 assert!(
18934 encoded.stream.len() <= 62_703,
18935 "stream grew to {} bytes, over the 62703-byte ceiling",
18936 encoded.stream.len()
18937 );
18938 }
18939
18940 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
18941 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
18942 /// facade -- timed end to end, so the edith export-time projection is a
18943 /// real number rather than a guess from the isolated key/inter numbers
18944 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
18945 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
18946 #[test]
18947 #[ignore = "a perf probe, not a gate"]
18948 fn sequence_bench_sanity() {
18949 let _knobs = crate::speed::knob_read();
18950 let fctx = &crate::decode::FrameCtx::for_encoder();
18951 use std::time::Instant;
18952 let (width, height) = (1280usize, 720usize);
18953 let pictures: Vec<Picture> = (0..24)
18954 .map(|i| panned_test_card(width, height, i * 3))
18955 .collect();
18956 let t = Instant::now();
18957 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18958 let elapsed = t.elapsed();
18959 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
18960 eprintln!(
18961 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
18962 elapsed / 24
18963 );
18964 }
18965
18966 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
18967 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
18968 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
18969 /// -- --ignored --nocapture`.
18970 #[test]
18971 #[ignore = "a calibration probe, not a gate"]
18972 fn calibration_sweep_base_q_idx() {
18973 let _knobs = crate::speed::knob_read();
18974 let fctx = &crate::decode::FrameCtx::for_encoder();
18975 if !have_ffmpeg() {
18976 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
18977 return;
18978 }
18979 let (width, height, frames) = (640usize, 384usize, 12usize);
18980 for clip in [
18981 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
18982 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
18983 ] {
18984 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18985 .join("../../fixtures/video")
18986 .join(clip);
18987 if !path.exists() {
18988 eprintln!("SKIP {clip}: fixture missing");
18989 continue;
18990 }
18991 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
18992 eprintln!("--- {clip} ---");
18993 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
18994 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
18995 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
18996 let mean_psnr: f64 = decoded
18997 .iter()
18998 .zip(&source)
18999 .map(|(d, s)| psnr(&d.y, &s.y))
19000 .sum::<f64>()
19001 / frames as f64;
19002 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
19003 eprintln!(
19004 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
19005 encoded.stream.len()
19006 );
19007 }
19008 }
19009 }
19010
19011 // -----------------------------------------------------------------------
19012 // The encoder's standing BD-rate baseline against libaom and rav1e.
19013 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
19014 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
19015 // agreeing with our encoder proves nothing about the bitstream.
19016 // -----------------------------------------------------------------------
19017
19018 /// All-plane PSNR of a decoded picture against its source, on the same
19019 /// 8-bit scale [`psnr`] uses.
19020 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
19021 let cat = |p: &Picture| {
19022 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
19023 v.extend_from_slice(&p.y);
19024 v.extend_from_slice(&p.u);
19025 v.extend_from_slice(&p.v);
19026 v
19027 };
19028 psnr(&cat(decoded), &cat(source))
19029 }
19030
19031 /// The pictures back as the planar 8-bit bytes an encoder reads.
19032 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
19033 let mut raw = Vec::new();
19034 for p in source {
19035 for plane in [&p.y, &p.u, &p.v] {
19036 raw.extend(plane.iter().map(|&s| s as u8));
19037 }
19038 }
19039 raw
19040 }
19041
19042 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
19043 /// through ffmpeg: one point per entry of `points`, each a quality flag
19044 /// set. Returns the ladder ordered by fidelity and the total encode wall
19045 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
19046 /// so both curves are measured by the same decoder.
19047 fn external_ladder(
19048 source: &[Picture],
19049 width: usize,
19050 height: usize,
19051 encoder: &str,
19052 points: &[Vec<String>],
19053 ) -> (Vec<(f64, f64)>, f64) {
19054 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
19055 let dir = std::env::temp_dir();
19056 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
19057 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
19058 let mut ladder = Vec::new();
19059 let mut wall = 0.0;
19060 for (i, params) in points.iter().enumerate() {
19061 let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id()));
19062 let start = std::time::Instant::now();
19063 let out = Command::new("ffmpeg")
19064 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
19065 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
19066 .arg(&raw_path)
19067 .args(["-an", "-threads", "1"])
19068 .args(["-g", &source.len().to_string(), "-c:v", encoder])
19069 .args(params)
19070 .args(["-f", "obu"])
19071 .arg(&obu)
19072 .output()
19073 .expect("ffmpeg failed to run");
19074 wall += start.elapsed().as_secs_f64();
19075 assert!(
19076 out.status.success(),
19077 "{encoder} {params:?}: {}",
19078 String::from_utf8_lossy(&out.stderr)
19079 );
19080 let stream = std::fs::read(&obu).expect("reference stream");
19081 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
19082 // lane-dkey: every reference point must also decode through OUR
19083 // decoder, sample-exact against ffmpeg's decode of the same bytes.
19084 // A BD table computed off streams we cannot read is a table about
19085 // an encoder we cannot check; this is the assertion that would
19086 // have caught the `force_integer_mv` defect (its stream decoded to
19087 // 25 dB garbage while this gate stayed green) and the crf-5 key
19088 // frame desync. A failure names the encoder, the point's flags and
19089 // the first differing frame/plane/sample.
19090 // lane-dpm1: a failing reference point is COLLECTED, not panicked
19091 // on, so one run still prints the whole BD table and names every
19092 // bad point instead of stopping at the first. The collection is
19093 // asserted empty by [`assert_ladder_decodes`] at the end of each
19094 // gate.
19095 match crate::stream::decode_stream(&stream) {
19096 Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
19097 "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
19098 ours.len(),
19099 decoded.len(),
19100 )),
19101 Ok(ours) => {
19102 for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
19103 if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
19104 note_ladder_failure(format!(
19105 "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
19106 decoder decoded {got}, ffmpeg {want}"
19107 ));
19108 break;
19109 }
19110 }
19111 }
19112 Err(e) => note_ladder_failure(format!(
19113 "{encoder} {params:?}: our decoder refused the stream ({e})"
19114 )),
19115 }
19116 let mean: f64 = decoded
19117 .iter()
19118 .zip(source)
19119 .map(|(d, s)| psnr_all(d, s))
19120 .sum::<f64>()
19121 / source.len() as f64;
19122 ladder.push((mean, (stream.len() as f64).log10()));
19123 let _ = std::fs::remove_file(&obu);
19124 }
19125 let _ = std::fs::remove_file(&raw_path);
19126 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19127 (ladder, wall)
19128 }
19129
19130 /// Every reference ladder point that did not decode sample-exactly
19131 /// through our own decoder, collected across a whole gate run so the BD
19132 /// table still prints and EVERY bad point is named
19133 /// (`encoder params frame plane sample`) instead of only the first.
19134 static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
19135
19136 fn note_ladder_failure(msg: String) {
19137 eprintln!("LADDER DECODE FAILURE: {msg}");
19138 LADDER_FAILURES.lock().expect("ladder failures").push(msg);
19139 }
19140
19141 /// Fail the gate at its END on everything [`external_ladder`] collected.
19142 fn assert_ladder_decodes() {
19143 let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
19144 assert!(
19145 failures.is_empty(),
19146 "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
19147 failures.len(),
19148 failures.join("\n"),
19149 );
19150 }
19151
19152 /// First differing sample between two pictures, as
19153 /// `(plane, index, left, right)` -- so a gate failure names the plane and
19154 /// the sample instead of just "differs". A length difference counts as a
19155 /// mismatch of that plane at the first index past the shorter one.
19156 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
19157 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
19158 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
19159 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
19160 }
19161 if l.len() != r.len() {
19162 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
19163 }
19164 }
19165 None
19166 }
19167
19168 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
19169 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
19170 /// stream is decoded twice -- by ffmpeg and by our own
19171 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
19172 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
19173 /// in Y, U and V over every shown frame in display order. That is itself
19174 /// a gate: it proves the bitstream says what the encoder thinks, in the
19175 /// only two decoders that read it.
19176 fn our_ladder(
19177 name: &str,
19178 source: &[Picture],
19179 width: usize,
19180 height: usize,
19181 fctx: &crate::decode::FrameCtx,
19182 ) -> (Vec<(f64, f64)>, f64) {
19183 let mut ladder = Vec::new();
19184 let mut wall = 0.0;
19185 for &q in &[150u8, 120, 90, 60] {
19186 let start = std::time::Instant::now();
19187 // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
19188 // the gate has to be able to re-sweep it. 0.5 is the shipped one
19189 // (`crate::encoder::DEADZONE`).
19190 let deadzone = std::env::var("EC_AV1_DEADZONE")
19191 .ok()
19192 .and_then(|v| v.parse().ok())
19193 .unwrap_or(0.5);
19194 let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
19195 wall += start.elapsed().as_secs_f64();
19196 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
19197 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19198 assert_eq!(
19199 ours.len(),
19200 source.len(),
19201 "{name} q={q}: our decoder's display-order frame count"
19202 );
19203 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
19204 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
19205 panic!(
19206 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
19207 {got}, the encoder reconstructed {want}"
19208 );
19209 }
19210 }
19211 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
19212 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
19213 panic!(
19214 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
19215 {got}, the encoder reconstructed {want}"
19216 );
19217 }
19218 }
19219 let per_frame: Vec<f64> = decoded.iter().zip(source).map(|(d, s)| psnr_all(d, s)).collect();
19220 // lane-txrd: does a tool's loss start at the FIRST inter frame
19221 // (a local mispricing) or grow down the GOP (propagation into
19222 // the reference chain)? One line per q point answers it.
19223 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
19224 let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect();
19225 eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" "));
19226 // lane-txrd: per PLANE, because an all-plane mean hides a
19227 // collapse in one of them (class `metric blind to a plane`).
19228 let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String {
19229 let v: Vec<String> = decoded
19230 .iter()
19231 .zip(source)
19232 .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s))))
19233 .collect();
19234 v.join(" ")
19235 };
19236 eprintln!("{name}: q={q} Y {}", plane(|p| &p.y));
19237 eprintln!("{name}: q={q} U {}", plane(|p| &p.u));
19238 eprintln!("{name}: q={q} V {}", plane(|p| &p.v));
19239 }
19240 let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64;
19241 ladder.push((mean, (encoded.stream.len() as f64).log10()));
19242 }
19243 // What this clip asked for and what the content gate left it coding
19244 // under: a screen clip requests a pyramid and codes flat, and that
19245 // difference is what keeps its row identical to the flat baseline
19246 // (class `gate-blind-to-feature`).
19247 eprintln!(
19248 "{name}: sequence, pyramid requested {:?} effective {:?}",
19249 crate::encoder::Pyramid::from_env(),
19250 last_sequence_pyramid(),
19251 );
19252 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19253 (ladder, wall)
19254 }
19255
19256 /// [`our_ladder`] through the streaming facade — the surface the editor's
19257 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
19258 /// each stream is also reordered (hidden `ALTREF` first,
19259 /// `show_existing_frame` last per group) and each level is coded at its
19260 /// own quantizer offset; without one it is the flat ladder, which
19261 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
19262 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
19263 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
19264 /// the whole ladder how many frames and how many bytes it spent, and the
19265 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
19266 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
19267 /// flat path, so a requested pyramid can come back `None` here.
19268 fn our_ladder_facade(
19269 name: &str,
19270 source: &[Picture],
19271 width: usize,
19272 height: usize,
19273 pyramid: Option<crate::encoder::Pyramid>,
19274 ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4], Option<crate::encoder::Pyramid>) {
19275 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
19276 let slot = |l: Level| match l {
19277 Level::Key => 0,
19278 Level::Arf => 1,
19279 Level::Leaf => 2,
19280 Level::ShowExisting => 3,
19281 };
19282 let mut ladder = Vec::new();
19283 let mut wall = 0.0;
19284 let mut effective = None;
19285 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
19286 for &q in &[150u8, 120, 90, 60] {
19287 let config = EncoderConfig {
19288 width,
19289 height,
19290 base_q_idx: q,
19291 gop: source.len(),
19292 colour: Colour::Unspecified,
19293 tile_cols_log2: 0,
19294 tile_rows_log2: 0,
19295 };
19296 let start = std::time::Instant::now();
19297 let mut enc = match pyramid {
19298 None => Av1Encoder::new(config).unwrap(),
19299 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
19300 };
19301 let mut packets = Vec::new();
19302 for picture in source {
19303 packets.extend(enc.encode_frames(picture).unwrap());
19304 }
19305 packets.extend(enc.flush().unwrap());
19306 wall += start.elapsed().as_secs_f64();
19307 effective = enc.pyramid();
19308 let mut stream = Vec::new();
19309 for p in &packets {
19310 counts[slot(p.level)] += 1;
19311 bytes[slot(p.level)] += p.data.len();
19312 stream.extend_from_slice(&p.data);
19313 }
19314 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
19315 // correct if the DISPLAY-order output still has one frame per
19316 // source picture, in the right order -- checked against our own
19317 // decoder as well as ffmpeg's, both below.
19318 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
19319 assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count");
19320 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
19321 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
19322 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
19323 panic!(
19324 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
19325 decoded {got}, our decoder decoded {want}"
19326 );
19327 }
19328 }
19329 let mean: f64 = decoded
19330 .iter()
19331 .zip(source)
19332 .map(|(d, s)| psnr_all(d, s))
19333 .sum::<f64>()
19334 / source.len() as f64;
19335 ladder.push((mean, (stream.len() as f64).log10()));
19336 }
19337 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19338 (ladder, wall, counts, bytes, effective)
19339 }
19340
19341 /// Byte-exactness gate for encoder work that is meant to change only
19342 /// how long the encoder takes.
19343 ///
19344 /// The BD gate above measures quality, which a speed lane can move by a
19345 /// hair without failing anything; this pins the streams themselves.
19346 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
19347 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
19348 /// in the tile) and again on lane-av1mv's merge of it: an extra
19349 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
19350 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
19351 /// prices coefficients against the tables the frame's writer really
19352 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
19353 /// decision change the BD gate judges. Re-pinned again on
19354 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
19355 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
19356 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
19357 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
19358 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
19359 /// by default ([`warp_on`], a sequence/frame header bit and a new
19360 /// motion_mode symbol on eligible blocks) and
19361 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
19362 /// every inter frame's superblocks now code at their own lambda
19363 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
19364 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
19365 /// and the two var-tx depth searches ([`tx32_depth_search`],
19366 /// [`compound_var_tx`]) are on by default, all three re-judged on the
19367 /// native gate's real film rows.
19368 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
19369 /// every block whose chroma takes it codes a different mode symbol, two
19370 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
19371 /// restores the previous streams. Re-pinned again in the same lane once
19372 /// directional luma winners searched their `angle_delta_y`
19373 /// (`EC_AV1_ANGLE=0` restores that half).
19374 #[test]
19375 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
19376 // These are DEFAULT-PRESET pins: a speed preset switches search levers
19377 // off, so it legitimately moves every byte. Encode at speed 0 whatever
19378 // `EC_AV1_SPEED` says (write guard: the preset is process-global).
19379 let _knobs = crate::speed::knob_write();
19380 let was = crate::speed::speed();
19381 crate::speed::set_speed(0);
19382 if !have_ffmpeg() {
19383 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
19384 return;
19385 }
19386 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19387 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
19388 if !clip.exists() {
19389 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip");
19390 return;
19391 }
19392 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
19393 // FNV-1a over the stream: a witness that every coded bit is where it
19394 // was, which a byte count alone is not.
19395 let fnv = |b: &[u8]| {
19396 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
19397 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
19398 })
19399 };
19400 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
19401 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
19402 // of 4, its leaves at q+8 and a `show_existing_frame` header per
19403 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
19404 // four frames; four pictures is one short mini-GOP, which is the
19405 // shape that pays least (the ARF's own quality has no later group to
19406 // carry it), so this is not the BD gate's number.
19407 // Re-taken again on lane-av1cfl: the chroma search offers
19408 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
19409 // so every block taking either codes different syntax and different
19410 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
19411 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
19412 // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
19413 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
19414 // so these four pictures code as one truncated group -- a hidden
19415 // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
19416 // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
19417 // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
19418 // Re-taken on lane-fintra: the sequence header sets
19419 // `enable_filter_intra`, so every DC_PRED intra block of at most
19420 // 32x32 without a luma palette carries a `use_filter_intra` flag and
19421 // the blocks that take one code a filter-intra mode, a different
19422 // prediction and different coefficients -- 7321 -> 7373 at q=150 and
19423 // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
19424 // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
19425 // (default pyramid `8:-32:16`, one truncated group of 8 with its
19426 // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
19427 // root can code a REAL residual now (one TX_64X64 luma transform and
19428 // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
19429 // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
19430 // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
19431 // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
19432 // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
19433 // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
19434 // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
19435 // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
19436 // -> 9835 at q=150 and 35450 -> 35798 at q=60.
19437 // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
19438 // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
19439 // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
19440 // these four pictures -- offers every superblock a 64x64 intra root
19441 // now. `EC_AV1_I64=0` restores 8557 / 33345.
19442 // Re-taken on lane-pricer: the inter RD search prices a single
19443 // reference through the tree and the neighbour contexts the writer
19444 // really codes it with, so every inter picture's reference decisions
19445 // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
19446 // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
19447 // for `skip`/`is_inter` and for the whole compound reference tree, so
19448 // every inter block's cost -- and with it the skip and reference
19449 // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
19450 // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
19451 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
19452 // single and compound are priced against the same syntax -- 8311 ->
19453 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
19454 // Re-taken on lane-newmv: the motion search charges its own rate term
19455 // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
19456 // and each subpel stage re-runs from its own winner
19457 // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
19458 // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
19459 // and 33014 -> 33090 at q=60.
19460 // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
19461 // from libaom's objective tpl mapping, so every inter picture's
19462 // quantizer grid -- and every decision priced against it -- moved
19463 // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
19464 // at the merge of both lanes.
19465 // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its
19466 // per-superblock `delta_qindex` at 1.5x the preset's strength
19467 // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
19468 // grids -- and every decision priced against them -- moved:
19469 // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
19470 // Re-taken on lane-arfpred: the top ARF is coded from a temporally
19471 // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
19472 // pixels -- and the leaves that predict from them -- moved:
19473 // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
19474 // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
19475 // the shipped stream did not move.
19476 // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
19477 // picture is coded in 128x128 superblocks now, the inter ones
19478 // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
19479 // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
19480 // Re-taken at the merge of lane-b128m onto main (128 superblocks on
19481 // by default, on top of the ARF temporal filter).
19482 // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
19483 // candidates the 64 root already did ([`b128_compound`]), so every
19484 // inter frame that carries `reference_select` codes different blocks
19485 // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
19486 // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
19487 // Re-taken on lane-arftf: that filter's strength swept on the deciding
19488 // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered
19489 // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and
19490 // 33017 at q=60 (the same LENGTH, different bytes).
19491 // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
19492 // lane-rlclamp onto the 128 compound default.
19493 // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
19494 // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
19495 // so every inter frame whose RD takes one codes a different partition
19496 // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
19497 // quantizer the rect cut never wins its own comparison on this clip.
19498 // `EC_AV1_B128HV=0` restores 8290 exactly.
19499 let pins: [(u8, usize, u64); 2] = [(150, 8291, 0x1f00bb0eb099a27f), (60, 33227, 0x57ee6b1f8eacd881)];
19500 let coded: Vec<(u8, usize, u64)> = pins
19501 .iter()
19502 .map(|&(q, _, _)| {
19503 let e = encode_sequence(&source, q, 0.5).unwrap();
19504 (q, e.stream.len(), fnv(&e.stream))
19505 })
19506 .collect();
19507 crate::speed::set_speed(was);
19508 for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
19509 assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
19510 }
19511 }
19512
19513 /// A ladder is only a ladder if both axes rise together.
19514 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
19515 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
19516 for w in ladder.windows(2) {
19517 assert!(
19518 w[1].0 > w[0].0 && w[1].1 > w[0].1,
19519 "{name}: not monotone, {ladder:?}"
19520 );
19521 }
19522 }
19523
19524 /// The sweep behind [`screen_content`]'s constants
19525 /// (`unswept-decision-constants`), on the SAME five clips
19526 /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
19527 /// same native crop: for each colour bound N the share of 16x16 luma
19528 /// blocks with 2..=N distinct colours, and the share of those whose
19529 /// per-pixel variance also clears a floor V -- libaom's
19530 /// `av1_set_screen_content_options` counts the variance-cleared blocks
19531 /// too (its `counts_2`, which gates intrabc), and without that term a
19532 /// smooth dark film frame reads as screen content.
19533 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
19534 #[test]
19535 #[ignore = "reads the real library"]
19536 fn probe_screen_detect() {
19537 let _knobs = crate::speed::knob_read();
19538 if !have_ffmpeg() {
19539 eprintln!("SKIP probe_screen_detect: no ffmpeg");
19540 return;
19541 }
19542 let limits = [4usize, 8, 16, 32, 64, 128];
19543 let floors = [0u64, 4, 16, 64, 256];
19544 // The census of one clip at one size: mean share, over the frames, of
19545 // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
19546 let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
19547 let mut acc = [[0f64; 5]; 6];
19548 for picture in frames {
19549 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
19550 let mut hit = [[0usize; 5]; 6];
19551 let mut blocks = 0usize;
19552 for by in (0..ch).step_by(16) {
19553 for bx in (0..cw).step_by(16) {
19554 let mut seen = [false; 256];
19555 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
19556 for row in 0..16 {
19557 for col in 0..16 {
19558 let v = y[(by + row) * cw + bx + col];
19559 sum += u64::from(v);
19560 sq += u64::from(v) * u64::from(v);
19561 if !seen[usize::from(v)] {
19562 seen[usize::from(v)] = true;
19563 colors += 1;
19564 }
19565 }
19566 }
19567 let var = (sq - sum * sum / 256) / 256;
19568 blocks += 1;
19569 for (li, &limit) in limits.iter().enumerate() {
19570 if colors > 1 && colors <= limit {
19571 for (fi, &floor) in floors.iter().enumerate() {
19572 hit[li][fi] += usize::from(var > floor);
19573 }
19574 }
19575 }
19576 }
19577 }
19578 for li in 0..6 {
19579 for fi in 0..5 {
19580 acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
19581 }
19582 }
19583 }
19584 let n = frames.len().max(1) as f64;
19585 eprintln!("{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:", frames.len());
19586 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{f:>8}")).collect::<String>());
19587 for (li, &limit) in limits.iter().enumerate() {
19588 eprintln!(
19589 " {limit:>5} |{}",
19590 (0..5).map(|fi| format!("{:>7.1}%", acc[li][fi] / n)).collect::<String>()
19591 );
19592 }
19593 };
19594 for (name, path, seek) in native_gate_clips() {
19595 let Some((nw, nh)) = probe_dims(&path) else {
19596 eprintln!("SKIP {name}: ffprobe gave no size");
19597 continue;
19598 };
19599 let cw = nw.min(1920) / 128 * 128;
19600 let ch = nh.min(1024) / 128 * 128;
19601 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
19602 let frames = clip_frames_vf(&path, &seek, &format!("crop={cw}:{ch}:{x}:{y0}"), cw, ch, 12);
19603 census(&name, &frames, cw, ch);
19604 // The 640x384 gate scales instead of cropping, and the scaling
19605 // changes the census (bars smooth out): the constants have to
19606 // separate at BOTH sizes.
19607 let small = clip_frames(&path, &seek, 640, 384, 12);
19608 census(&name, &small, 640, 384);
19609 }
19610 }
19611
19612 /// The detector against the WHOLE real library (class
19613 /// `unswept-decision-constants`, user rule "his data is the gate"):
19614 /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
19615 /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
19616 /// duration, four frames each, 8-bit 4:2:0, at native size or a
19617 /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
19618 /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
19619 /// Prints per file and offset the share of qualifying 16x16 blocks, the
19620 /// [`screen_content`] verdict and a content hint (mean luma, luma
19621 /// standard deviation, inter MAD), then sweeps the colour bound against
19622 /// the variance floor over the whole library: for each (N, V) the worst
19623 /// (highest) share among the camera/film rows against the best (lowest)
19624 /// among the screen-recording rows, so the rule with the widest gap can
19625 /// be read off. Rows carry the manifest index, codec and size only --
19626 /// no titles, no home paths.
19627 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
19628 #[test]
19629 #[ignore = "reads the real library"]
19630 fn probe_screen_library() {
19631 let _knobs = crate::speed::knob_read();
19632 if !have_ffmpeg() {
19633 eprintln!("SKIP probe_screen_library: no ffmpeg");
19634 return;
19635 }
19636 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
19637 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
19638 eprintln!("SKIP probe_screen_library: no real-library manifest");
19639 return;
19640 };
19641 let limits = [4usize, 8, 16, 32, 64];
19642 let floors = [0u64, 4, 8, 16, 32, 64, 128];
19643 // Whatever ffmpeg gave us, without the exact-count assertion the
19644 // gate loaders make: a seek near the end of a clip returns fewer
19645 // frames, and that is a row to print, not a panic.
19646 let decode = |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
19647 let out = Command::new("ffmpeg")
19648 .args(["-v", "error", "-ss", seek, "-i", clip])
19649 .args(["-frames:v", &n.to_string()])
19650 .args(["-vf", vf])
19651 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
19652 .output();
19653 let Ok(out) = out else { return Vec::new() };
19654 if !out.status.success() {
19655 return Vec::new();
19656 }
19657 let (luma, chroma) = (w * h, w * h / 4);
19658 let frame_len = luma + 2 * chroma;
19659 (0..out.stdout.len() / frame_len)
19660 .map(|i| {
19661 let b = &out.stdout[i * frame_len..][..frame_len];
19662 Picture {
19663 width: w,
19664 height: h,
19665 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
19666 u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
19667 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
19668 }
19669 })
19670 .collect()
19671 };
19672 // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
19673 // variance > V, for every (N, V) of the sweep grid, over one frame.
19674 let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
19675 let mut hit = [[0usize; 7]; 5];
19676 let mut blocks = 0usize;
19677 for by in (0..h).step_by(16) {
19678 for bx in (0..w).step_by(16) {
19679 let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
19680 let mut seen = [false; 256];
19681 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
19682 for row in 0..bh {
19683 for col in 0..bw {
19684 let v = y[(by + row) * w + bx + col];
19685 sum += u64::from(v);
19686 sq += u64::from(v) * u64::from(v);
19687 if !seen[usize::from(v)] {
19688 seen[usize::from(v)] = true;
19689 colors += 1;
19690 }
19691 }
19692 }
19693 let n = (bh * bw) as u64;
19694 let var = (sq - sum * sum / n) / n;
19695 blocks += 1;
19696 for (li, &limit) in limits.iter().enumerate() {
19697 if colors > 1 && colors <= limit {
19698 for (fi, &floor) in floors.iter().enumerate() {
19699 hit[li][fi] += usize::from(var > floor);
19700 }
19701 }
19702 }
19703 }
19704 }
19705 let mut out = [[0f64; 7]; 5];
19706 for li in 0..5 {
19707 for fi in 0..7 {
19708 out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
19709 }
19710 }
19711 out
19712 };
19713 // (index, label, path, duration, screen-by-its-own-content). The
19714 // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
19715 // are desktop recordings; everything else in this library is camera
19716 // or film material.
19717 let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
19718 for (label, file) in [("bars 1080p", "h264-1080p-23.976-8bit.mp4"), ("bars 2160p", "h264-2160p-23.976-8bit.mp4")] {
19719 let path = fixtures.join("video").join(file);
19720 if path.exists() {
19721 rows.push(("fx".into(), label.into(), path.to_str().unwrap().into(), 10.0, false));
19722 }
19723 }
19724 for (i, line) in manifest.lines().skip(1).enumerate() {
19725 let f: Vec<&str> = line.split('\t').collect();
19726 if f.len() < 10 {
19727 continue;
19728 }
19729 let (path, codec) = (f[0], f[2]);
19730 if codec == "-" || codec.is_empty() {
19731 continue;
19732 }
19733 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
19734 eprintln!("SKIP {}: manifest carries no coded size", i + 1);
19735 continue;
19736 };
19737 if !std::path::Path::new(path).exists() {
19738 eprintln!("SKIP {}: file is gone", i + 1);
19739 continue;
19740 }
19741 let name = path.rsplit('/').next().unwrap_or(path);
19742 let is_capture = path.contains("/OBS/")
19743 || (name.len() > 19
19744 && name.as_bytes()[4] == b'-'
19745 && name.as_bytes()[7] == b'-'
19746 && name.as_bytes()[10] == b' '
19747 && name.as_bytes()[13] == b'-');
19748 rows.push((
19749 format!("{}", i + 1),
19750 format!("{codec} {w}x{h}"),
19751 path.to_string(),
19752 f[8].parse::<f64>().unwrap_or(0.0),
19753 is_capture,
19754 ));
19755 }
19756 // Per (N, V): the worst camera/film row and the best screen row, so
19757 // the separation of the whole library is one subtraction.
19758 let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
19759 eprintln!("| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |");
19760 for (idx, label, path, dur, is_capture) in &rows {
19761 let Some((nw, nh)) = probe_dims(path) else {
19762 eprintln!("SKIP {idx}: ffprobe gave no size");
19763 continue;
19764 };
19765 let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
19766 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
19767 let vf = format!("crop={cw}:{ch}:{x}:{y0}");
19768 let mut file_grid = [[0f64; 7]; 5];
19769 let mut file_frames = 0usize;
19770 for pct in [10u32, 50, 90] {
19771 let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
19772 let frames = decode(path, &seek, &vf, cw, ch, 4);
19773 if frames.is_empty() {
19774 eprintln!("| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |", if *is_capture { "screen" } else { "camera" });
19775 continue;
19776 }
19777 let (mut share, mut yes, mut mean, mut sd, mut mad) = (0f64, 0usize, 0f64, 0f64, 0f64);
19778 let mut prev: Option<Vec<u8>> = None;
19779 for picture in &frames {
19780 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
19781 let grid = census(&y, cw, ch);
19782 for li in 0..5 {
19783 for fi in 0..7 {
19784 file_grid[li][fi] += grid[li][fi];
19785 }
19786 }
19787 file_frames += 1;
19788 // The shipped rule is (16 colours, var > 16): grid row 2,
19789 // floor 16 is column 3.
19790 share += grid[2][3];
19791 yes += usize::from(screen_content(&y, cw, cw, ch));
19792 let n = y.len() as f64;
19793 let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
19794 let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
19795 mean += sum / n;
19796 sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
19797 if let Some(p) = &prev {
19798 mad += p.iter().zip(&y).map(|(&a, &b)| f64::from(a.abs_diff(b))).sum::<f64>() / n;
19799 }
19800 prev = Some(y);
19801 }
19802 let f = frames.len() as f64;
19803 eprintln!(
19804 "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
19805 if *is_capture { "screen" } else { "camera" },
19806 share / f,
19807 if yes * 2 > frames.len() { "SCREEN" } else { "camera" },
19808 frames.len(),
19809 mean / f,
19810 sd / f,
19811 mad / (f - 1.0).max(1.0),
19812 );
19813 }
19814 if file_frames == 0 {
19815 continue;
19816 }
19817 for li in 0..5 {
19818 for fi in 0..7 {
19819 let s = file_grid[li][fi] / file_frames as f64;
19820 match is_capture {
19821 true => scr_min[li][fi] = scr_min[li][fi].min(s),
19822 false => cam_max[li][fi] = cam_max[li][fi].max(s),
19823 }
19824 }
19825 }
19826 }
19827 eprintln!("sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):");
19828 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{:>18}", format!("V>{f}"))).collect::<String>());
19829 let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
19830 for (li, &limit) in limits.iter().enumerate() {
19831 let mut row = String::new();
19832 for fi in 0..7 {
19833 let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
19834 row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
19835 if s - c > best {
19836 best = s - c;
19837 best_rule = (limit, floors[fi]);
19838 }
19839 }
19840 eprintln!(" {limit:>5} |{row}");
19841 }
19842 // The threshold sits at the midpoint of the widest gap; the shipped
19843 // constant is its reciprocal in whole parts of the frame.
19844 let (li, fi) = (
19845 limits.iter().position(|&l| l == best_rule.0).unwrap(),
19846 floors.iter().position(|&f| f == best_rule.1).unwrap(),
19847 );
19848 let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
19849 eprintln!(
19850 "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
19851 best_rule.0,
19852 best_rule.1,
19853 best,
19854 cam_max[li][fi],
19855 scr_min[li][fi],
19856 mid,
19857 (100.0 / mid.max(0.1)).round() as usize,
19858 );
19859 }
19860
19861 /// The missing instrument: what this encoder costs against libaom and
19862 /// rav1e at matched fidelity, and how long it takes to get there.
19863 ///
19864 /// Recipe, identical on all three sides: 12 consecutive frames of each
19865 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
19866 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
19867 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
19868 /// it by default), 4:2:0 8-bit in and out. Reference points:
19869 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
19870 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
19871 /// tile_cols=1:tile_rows=1:threads=1`
19872 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
19873 /// ffmpeg-decoded frames of each encoder's own stream.
19874 ///
19875 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
19876 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
19877 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
19878 /// four encodes of that ladder together):
19879 ///
19880 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
19881 /// |---|---|---|---|---|
19882 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
19883 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
19884 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
19885 ///
19886 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
19887 /// the encoder takes -- every stream it writes is byte-identical, so the
19888 /// BD columns are this box's own re-run of the same recipe rather than a
19889 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
19890 /// rav1e). What moved is the wall of the four encodes:
19891 ///
19892 /// | clip | wall ours before | after | instructions:u before -> after |
19893 /// |---|---|---|---|
19894 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
19895 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
19896 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
19897 ///
19898 /// Three exact steps, none of which touches a coded bit: the coefficient
19899 /// rate pricer stopped rebuilding every CDF table per candidate
19900 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
19901 /// tile once per candidate (`decode::FilterReplay`), and the forward
19902 /// transform stopped transforming the all-zero residual that 70% of its
19903 /// calls carry.
19904 ///
19905 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
19906 ///
19907 /// | step | 1080p | 2160p | screen |
19908 /// |---|---|---|---|
19909 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
19910 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
19911 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
19912 ///
19913 /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
19914 /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
19915 /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
19916 /// -- all three decided on the REAL film rows of
19917 /// [`bd_rate_screen_native`], which this downscaled recipe does not
19918 /// carry:
19919 ///
19920 /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
19921 /// |---|---|---|---|
19922 /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
19923 /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
19924 /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
19925 ///
19926 /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
19927 /// DEFAULT of the sequence path this gate codes through -- the bars are
19928 /// non-screen so they take it, the capture is gated flat:
19929 ///
19930 /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
19931 /// |---|---|---|---|---|
19932 /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
19933 /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
19934 /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
19935 ///
19936 /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
19937 /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
19938 /// facade arm -- which is what "one mini-GOP driver, two entry points"
19939 /// means here. This downscaled recipe HATES the pyramid (as it hates
19940 /// every knob the real film rows of `bd_rate_screen_native` keep, which
19941 /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
19942 /// above. The capture's row is the flat row to the byte in both runs --
19943 /// that equality IS the content gate.
19944 ///
19945 /// Loop restoration is NOT in yet: it is the one filter whose parameters
19946 /// are per restoration UNIT inside the tile payload, so it needs both
19947 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
19948 /// buffer to solve against -- neither of which this frame-header-level
19949 /// search reaches.
19950 ///
19951 /// The baseline it replaced, before an inter frame's blocks chose their
19952 /// own partition, was +501.4/+504.4/+440.9 against libaom and
19953 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
19954 ///
19955 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
19956 /// fidelity, while spending far more time than either (the partition
19957 /// search's own cost, uncut: see the two intra-pruning variants measured
19958 /// and rejected in the lane report). No
19959 /// threshold is asserted yet -- this run sets the baseline; the gate
19960 /// asserts four monotone points per ladder, and at EVERY ladder point of
19961 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
19962 /// `crate::stream::decode_stream` -- and asserts the encoder's
19963 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
19964 /// and V over every shown frame in display order. A failure names the
19965 /// clip, the q, the frame, the plane and the first differing sample.
19966 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
19967 /// which exposes no per-packet reconstruction, so that path asserts the
19968 /// two decoders against each other on all three planes.)
19969 ///
19970 /// Run:
19971 /// cargo test -p ec-av1 --release --lib -- --ignored \
19972 /// bd_rate_vs_libaom_and_rav1e --nocapture
19973 #[test]
19974 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
19975 fn bd_rate_vs_libaom_and_rav1e() {
19976 let _knobs = crate::speed::knob_write();
19977 if !have_ffmpeg() {
19978 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
19979 return;
19980 }
19981 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
19982 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
19983 // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
19984 // rows for real content (the real rows live in the native gate).
19985 for (label, name) in [
19986 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
19987 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
19988 ] {
19989 let path = fixtures.join("video").join(name);
19990 if path.exists() {
19991 clips.push((label.to_string(), path));
19992 } else {
19993 eprintln!("SKIP clip {name}: missing");
19994 }
19995 }
19996 // Screen capture: the repo carries no screen-capture fixture, so take
19997 // the first OBS recording the real-library manifest names.
19998 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
19999 Ok(manifest) => {
20000 let screen = manifest
20001 .lines()
20002 .skip(1)
20003 .filter_map(|l| l.split('\t').next())
20004 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists());
20005 match screen {
20006 Some(p) => clips.push((
20007 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
20008 std::path::PathBuf::from(p),
20009 )),
20010 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
20011 }
20012 }
20013 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
20014 }
20015 assert!(!clips.is_empty(), "no source clip available");
20016
20017 let (width, height, frames) = (640usize, 384usize, 12usize);
20018 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
20019 .iter()
20020 .map(|q| {
20021 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
20022 .map(String::from)
20023 .to_vec()
20024 })
20025 .collect();
20026 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
20027 .iter()
20028 .map(|q| {
20029 vec![
20030 "-rav1e-params".to_string(),
20031 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
20032 ]
20033 })
20034 .collect();
20035 println!(
20036 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
20037 );
20038 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |");
20039 println!("|---|---|---|---|---|");
20040 for (name, path) in &clips {
20041 let fctx = &crate::decode::FrameCtx::for_encoder();
20042 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
20043 let _ = take_partition_hits();
20044 let _ = crate::tile::take_palette_hits();
20045 SCREEN_FRAMES.iter().for_each(|c| {
20046 c.store(0, std::sync::atomic::Ordering::Relaxed);
20047 });
20048 let _ = take_uv_mode_hits();
20049 let _ = crate::tile::take_inter_mode_hits();
20050 let _ = crate::tile::take_drl_hits();
20051 let _ = crate::tile::take_ref_hits();
20052 let _ = crate::tile::take_compound_mode_hits();
20053 let _ = crate::tile::take_compound_pair_hits();
20054 let _ = crate::tile::take_compound_size_hits();
20055 let _ = crate::tile::take_compound_leaf_mode_hits();
20056 let _ = take_b64_root_hits();
20057 let _ = take_b64_residual_hits();
20058 let _ = take_b64_compound_hits();
20059 let _ = crate::motion::take_census();
20060 // The entry-surface arm: run the SAME ladder through the
20061 // streaming facade the editor's export calls, which must print
20062 // the same BD numbers as the sequence path -- byte for byte the
20063 // same stream now that both drive one mini-GOP driver
20064 // (lane-av1pyrdef).
20065 let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
20066 let (ours, ours_wall) = match facade {
20067 false => our_ladder(name, &source, width, height, fctx),
20068 true => {
20069 let pyramid = crate::encoder::Pyramid::from_env();
20070 let (ladder, wall, counts, bytes, effective) =
20071 our_ladder_facade(name, &source, width, height, pyramid);
20072 eprintln!(
20073 "{name}: facade, pyramid requested {pyramid:?} effective \
20074 {effective:?} -- frames key {} arf {} leaf {} \
20075 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
20076 counts[0], counts[1], counts[2], counts[3],
20077 bytes[0], bytes[1], bytes[2], bytes[3],
20078 );
20079 (ladder, wall)
20080 }
20081 };
20082 // How often the inter split actually fired over this clip's four
20083 // encodes, against the whole 32x32 that was the only outcome
20084 // before (gate-blind-to-feature).
20085 let [whole32, split32, whole16, split16] = take_partition_hits();
20086 // Which inter modes actually fired over this clip's four encodes,
20087 // and at which DRL index -- a mode nobody picks is a mode the BD
20088 // number cannot be crediting (gate-blind-to-feature).
20089 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
20090 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
20091 let refs = crate::tile::take_ref_hits();
20092 let modes_total = (nearest + near + global + new).max(1);
20093 eprintln!(
20094 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
20095 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
20096 {drl0}/{drl1}/{drl2}/{drl3}",
20097 100.0 * nearest as f64 / modes_total as f64,
20098 100.0 * near as f64 / modes_total as f64,
20099 100.0 * global as f64 / modes_total as f64,
20100 100.0 * new as f64 / modes_total as f64,
20101 );
20102 // The compound census: what share of the coded inter blocks took
20103 // a compound reference at all, which compound mode they took, and
20104 // which pair (gate-blind-to-feature -- a compound mode nobody
20105 // picks cannot be what a BD number credits).
20106 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
20107 // superblocks were left whole at all, and how many of those coded
20108 // a residual or took a compound reference.
20109 let (roots, root_res, root_comp) = (
20110 take_b64_root_hits(),
20111 take_b64_residual_hits(),
20112 take_b64_compound_hits(),
20113 );
20114 eprintln!(
20115 "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})"
20116 );
20117 let comp_modes = crate::tile::take_compound_mode_hits();
20118 let comp_pairs = crate::tile::take_compound_pair_hits();
20119 let comp_sizes = crate::tile::take_compound_size_hits();
20120 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
20121 let comp_total: usize = comp_modes.iter().sum();
20122 eprintln!(
20123 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
20124 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
20125 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
20126 modes_total + comp_total,
20127 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
20128 comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3],
20129 comp_modes[6], comp_modes[7],
20130 comp_pairs[3], comp_pairs[6],
20131 );
20132 eprintln!(
20133 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
20134 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
20135 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6],
20136 comp_leaf[7],
20137 );
20138 eprintln!(
20139 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
20140 comp_sizes[1], comp_sizes[2], comp_sizes[3],
20141 );
20142 // Where the wall-owning stage actually goes: how many candidate
20143 // evaluations (one `mc::predict` + SAD each) a search spends, how
20144 // many of them are subpel, and how often the winner is the seed
20145 // it started from -- the census the seeded search is judged by.
20146 let [calls, evals, subpel, rounds, near_pred, unmoved, widest, widest_moves] =
20147 crate::motion::take_census();
20148 let per = |n: u64| n as f64 / calls.max(1) as f64;
20149 eprintln!(
20150 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
20151 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
20152 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
20153 per(evals),
20154 100.0 * subpel as f64 / evals.max(1) as f64,
20155 per(rounds),
20156 100.0 * near_pred as f64 / calls.max(1) as f64,
20157 100.0 * unmoved as f64 / calls.max(1) as f64,
20158 );
20159 // lane-newmv, class `instrument at bound`: how often the winner
20160 // was walked to at the log stage's own WIDEST step -- a high
20161 // share means the search stops where its step lets it, not where
20162 // the content is.
20163 eprintln!(
20164 "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
20165 100.0 * widest as f64 / calls.max(1) as f64,
20166 per(widest_moves),
20167 );
20168 eprintln!(
20169 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
20170 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
20171 );
20172 eprintln!(
20173 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
20174 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
20175 whole32 + split32,
20176 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
20177 whole16 + split16,
20178 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
20179 );
20180 // The deblocking level each of this clip's frames chose
20181 // (lane-av1filt): 0 everywhere would mean the filter never fires.
20182 let levels = crate::filter_search::take_chosen_levels();
20183 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
20184 let mean = |f: fn(&Chosen) -> u8| {
20185 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
20186 };
20187 eprintln!(
20188 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
20189 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
20190 levels.len(),
20191 mean(|l| l.0.0),
20192 mean(|l| l.0.1),
20193 mean(|l| l.1.0),
20194 mean(|l| l.1.1),
20195 mean(|l| l.2.0),
20196 mean(|l| l.2.1),
20197 );
20198 // How many strength presets each frame's CDEF list carried and
20199 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
20200 // everywhere would mean the per-unit choice never fires.
20201 let presets = crate::filter_search::take_cdef_presets();
20202 let mut by_bits = [0usize; 4];
20203 for (b, _) in &presets {
20204 by_bits[usize::from(*b)] += 1;
20205 }
20206 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
20207 let on_extra: usize = presets
20208 .iter()
20209 .flat_map(|(_, c)| c.iter().skip(1))
20210 .sum();
20211 eprintln!(
20212 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
20213 on a non-default preset ({:.1}%)",
20214 by_bits[0],
20215 by_bits[1],
20216 by_bits[2],
20217 by_bits[3],
20218 on_extra,
20219 units,
20220 100.0 * on_extra as f64 / units.max(1) as f64
20221 );
20222 // How the 64x64 luma restoration units split between
20223 // RESTORE_NONE and Wiener (lane-av1lr).
20224 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
20225 eprintln!(
20226 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
20227 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
20228 );
20229 // Which chroma modes the search actually wins with, against the
20230 // unconditional DC_PRED that was the only outcome before
20231 // (gate-blind-to-feature).
20232 // Screen-content detection and the palette it turns on
20233 // (gate-blind-to-feature): how many frames set
20234 // `allow_screen_content_tools`, how many blocks took a palette,
20235 // and of what size. A film clip must print `screen frames on=0`.
20236 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
20237 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
20238 // Which tables the SEARCH priced against, per frame arming
20239 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
20240 // real starting ones. A film clip must show every inter arming on
20241 // the real side, a screen clip none of them.
20242 let (price_default, price_real) = crate::tile::take_pricing_hits();
20243 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
20244 let palette = crate::tile::take_palette_hits();
20245 eprintln!(
20246 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
20247 palette[0],
20248 (2..=8)
20249 .filter(|&n| palette[n] > 0)
20250 .map(|n| format!("{n}={}", palette[n]))
20251 .collect::<Vec<_>>()
20252 .join(" ")
20253 );
20254 // The CfL alpha histogram (lane-av1cfl): one entry per chroma
20255 // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
20256 // only ever fires at one magnitude is a search that never left
20257 // its first candidate (gate-blind-to-feature).
20258 // The luma angle-delta histogram (lane-av1cfl): how many
20259 // directional blocks won at each delta. All-zero would mean the
20260 // refinement never beat the base angle.
20261 let deltas = take_angle_delta_hits();
20262 if deltas.iter().sum::<usize>() > 0 {
20263 eprintln!(
20264 "{name}: angle_delta_y {}",
20265 deltas
20266 .iter()
20267 .enumerate()
20268 .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
20269 .collect::<Vec<_>>()
20270 .join(" ")
20271 );
20272 }
20273 let alphas = take_cfl_alpha_hits();
20274 if alphas.iter().sum::<usize>() > 0 {
20275 eprintln!(
20276 "{name}: cfl |alpha| {}",
20277 alphas
20278 .iter()
20279 .enumerate()
20280 .filter(|&(_, &n)| n > 0)
20281 .map(|(a, &n)| format!("{a}={n}"))
20282 .collect::<Vec<_>>()
20283 .join(" ")
20284 );
20285 }
20286 let palette_uv = crate::tile::take_palette_uv_hits();
20287 eprintln!(
20288 "{name}: chroma palette blocks {} sizes {}",
20289 palette_uv[0],
20290 (2..=8)
20291 .filter(|&n| palette_uv[n] > 0)
20292 .map(|n| format!("{n}={}", palette_uv[n]))
20293 .collect::<Vec<_>>()
20294 .join(" ")
20295 );
20296 let uv = take_uv_mode_hits();
20297 let uv_total: usize = uv.iter().sum();
20298 eprintln!(
20299 "{name}: uv modes {}",
20300 uv.iter()
20301 .enumerate()
20302 .filter(|&(_, &n)| n > 0)
20303 .map(|(m, &n)| format!(
20304 "{}={n} ({:.1}%)",
20305 UV_MODE_NAMES[m],
20306 100.0 * n as f64 / uv_total.max(1) as f64
20307 ))
20308 .collect::<Vec<_>>()
20309 .join(" ")
20310 );
20311 // Which transform depth the intra blocks of this clip's key
20312 // frames resolved to (lane-av1tx): depth 0 is one transform over
20313 // the whole block, 1 and 2 its halvings.
20314 let depths = take_tx_depth_hits();
20315 let depth_total: usize = depths.iter().sum();
20316 eprintln!(
20317 "{name}: intra tx depths {}",
20318 depths
20319 .iter()
20320 .enumerate()
20321 .map(|(d, &n)| format!(
20322 "{d}={n} ({:.1}%)",
20323 100.0 * n as f64 / depth_total.max(1) as f64
20324 ))
20325 .collect::<Vec<_>>()
20326 .join(" ")
20327 );
20328 print_inter_tx_census(name);
20329 // lane-av1obmc: how many blocks actually CODED a motion_mode
20330 // symbol and which value they took, by footprint -- "OBMC is on"
20331 // as a measurement rather than a claim (class
20332 // `gate-blind-to-feature`).
20333 let mm = crate::tile::take_motion_mode_hits();
20334 eprintln!(
20335 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
20336 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
20337 eligible)",
20338 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
20339 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20340 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20341 mm.iter().sum::<usize>(),
20342 );
20343 let (aom, aom_wall) =
20344 external_ladder(&source, width, height, "libaom-av1", &aom_points);
20345 let (rav1e, rav1e_wall) =
20346 external_ladder(&source, width, height, "librav1e", &rav1e_points);
20347 assert_monotone(&format!("{name}: ours"), &ours);
20348 assert_monotone(&format!("{name}: libaom"), &aom);
20349 assert_monotone(&format!("{name}: rav1e"), &rav1e);
20350 let points = ours
20351 .iter()
20352 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20353 .collect::<Vec<_>>()
20354 .join(", ");
20355 println!(
20356 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
20357 bd_rate(&aom, &ours) * 100.0,
20358 bd_rate(&rav1e, &ours) * 100.0,
20359 );
20360 println!(
20361 "| references | libaom {} | rav1e {} | | |",
20362 aom.iter()
20363 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20364 .collect::<Vec<_>>()
20365 .join(", "),
20366 rav1e
20367 .iter()
20368 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20369 .collect::<Vec<_>>()
20370 .join(", "),
20371 );
20372 }
20373 assert_ladder_decodes();
20374 }
20375 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
20376 /// split by block class in lane-av1txdepth): depth 0 is one transform over
20377 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
20378 /// leaves and the 32x32 root, each single-reference or compound. A class
20379 /// with no counts at all never reached `commit_inter_luma` -- which is
20380 /// what its knob being off looks like (class `gate-blind-to-feature`).
20381 fn print_inter_tx_census(name: &str) {
20382 let splits = take_inter_tx_split_hits();
20383 let total: usize = splits.iter().sum();
20384 let row = |label: &str, base: usize| {
20385 let (n0, n1) = (splits[base], splits[base + 1]);
20386 format!(
20387 "{label} 0={n0} 1={n1} ({:.1}% split)",
20388 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
20389 )
20390 };
20391 eprintln!(
20392 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
20393 row("leaf single", 0),
20394 row("leaf compound", 2),
20395 row("32x32 single", 4),
20396 row("32x32 compound", 6),
20397 );
20398 // lane-txrd: which types the two searches actually COMMITTED over
20399 // this row's four encodes -- the gate could not say whether a type
20400 // search fired at all (class `gate-blind-to-feature`).
20401 const NAMES: [&str; 16] = [
20402 "IDTX", "DCT_DCT", "ADST_ADST", "ADST_DCT", "DCT_ADST", "V_DCT", "H_DCT",
20403 "FLIPADST_DCT", "DCT_FLIPADST", "FLIPADST_FLIPADST", "ADST_FLIPADST",
20404 "FLIPADST_ADST", "V_ADST", "H_ADST", "V_FLIPADST", "H_FLIPADST",
20405 ];
20406 let name_of = |t: usize| NAMES[t];
20407 for (label, hits) in [("inter", take_inter_tx_type_hits()), ("intra", take_tx_type_hits())] {
20408 let total: usize = hits.iter().sum();
20409 let live: Vec<String> = hits
20410 .iter()
20411 .enumerate()
20412 .filter(|&(_, &n)| n > 0)
20413 .map(|(t, &n)| format!("{}={n} ({:.1}%)", name_of(t), 100.0 * n as f64 / total.max(1) as f64))
20414 .collect();
20415 eprintln!("{name}: {label} tx_type of {total} units -- {}", live.join(" "));
20416 }
20417 let t = take_txrd_stats();
20418 if t[0] > 0 {
20419 eprintln!(
20420 "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \
20421 bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",
20422 t[0], t[1], t[3] as f64 / 64.0, t[2], t[4] as f64 / 64.0,
20423 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,
20424 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,
20425 );
20426 eprintln!(
20427 "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \
20428 flat: dsse {:+.2}%, dbits {:+.2}%)",
20429 t[5], t[6] as f64 / 64.0,
20430 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,
20431 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,
20432 );
20433 }
20434 }
20435
20436 /// The video stream's coded size, from ffprobe.
20437 fn probe_dims(clip: &str) -> Option<(usize, usize)> {
20438 crate::probe::dims(clip)
20439 }
20440
20441 /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
20442 /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
20443 /// superblock-aligned one, still centred and still even for 4:2:0.
20444 ///
20445 /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
20446 /// superblocks by design, so no default gate row has a block the frame
20447 /// edge cuts through -- while every arbitrary export size does (3840x1608
20448 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
20449 /// 1920x1080` is the straddling arm the edge-clipped distortion score is
20450 /// read on.
20451 fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
20452 let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
20453 let (w, h) = spec.split_once('x').expect("EC_AV1_NATIVE_CROP is <width>x<height>");
20454 let (cw, ch): (usize, usize) =
20455 (w.parse().expect("crop width"), h.parse().expect("crop height"));
20456 let (nw, nh) = crate::probe::dims(clip)?;
20457 assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
20458 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
20459 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
20460 }
20461
20462 /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
20463 /// with `probe_screen_detect` so the detector sweep measures exactly the
20464 /// clips the keep table is read off. Selector env vars as documented on
20465 /// the gate; a missing clip prints a SKIP and drops its row.
20466 fn native_gate_clips() -> Vec<(String, String, String)> {
20467 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
20468 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
20469 let (film, film4k, screen) = (
20470 on("EC_AV1_NATIVE_FILM"),
20471 on("EC_AV1_NATIVE_FILM4K"),
20472 on("EC_AV1_NATIVE_SCREEN"),
20473 );
20474 // No selector at all means every clip; any selector means that subset.
20475 let all = !(film || film4k || screen);
20476 // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
20477 // not film -- they print as "bars" so no reader takes them for real
20478 // content -- and the two rows below them are the real AV1 films.
20479 let mut clips: Vec<(String, String, String)> = Vec::new();
20480 for (want, label, file) in [
20481 (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
20482 (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
20483 ] {
20484 if !want {
20485 continue;
20486 }
20487 let path = fixtures.join("video").join(file);
20488 match path.exists() {
20489 true => {
20490 clips.push((label.to_string(), path.to_str().unwrap().to_string(), "0".into()))
20491 }
20492 false => eprintln!("SKIP {label}: {file} missing"),
20493 }
20494 }
20495 let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
20496 // The real films, taken out of the real-library manifest by codec and
20497 // coded width so no title and no home path lives in this file. Each
20498 // seek is PINNED (class `seeded fixture not reproducible`) at a
20499 // moving, non-black window -- a black leader would make every arm
20500 // read +0.000 (class `flat sample window`). Both sources are 10-bit
20501 // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
20502 // what all three encoders see, so the comparison stays
20503 // encoder-vs-encoder.
20504 let pick = |width: &str| -> Option<String> {
20505 let m = manifest.as_ref().ok()?;
20506 m.lines()
20507 .skip(1)
20508 .map(|l| l.split('\t').collect::<Vec<_>>())
20509 .find(|f| {
20510 f.len() > 4
20511 && f[2] == "av1"
20512 && f[3] == width
20513 && std::path::Path::new(f[0]).exists()
20514 })
20515 .map(|f| f[0].to_string())
20516 };
20517 for (want, label, width, seek) in [
20518 (all || film, "film A (1080p source)", "1920", "00:35:00"),
20519 (all || film4k, "film B (2160p HDR source)", "3840", "00:40:00"),
20520 ] {
20521 if !want {
20522 continue;
20523 }
20524 match pick(width) {
20525 Some(path) => clips.push((label.to_string(), path, seek.to_string())),
20526 None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
20527 }
20528 }
20529 if all || screen {
20530 match &manifest {
20531 Ok(manifest) => match manifest
20532 .lines()
20533 .skip(1)
20534 .filter_map(|l| l.split('\t').next())
20535 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
20536 {
20537 Some(p) => clips.push((
20538 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
20539 p.to_string(),
20540 "0".into(),
20541 )),
20542 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
20543 },
20544 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
20545 }
20546 }
20547 clips
20548 }
20549
20550 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
20551 /// downscales the OBS capture to 640x384, which destroys exactly the
20552 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
20553 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
20554 /// on that recipe is taken on content the tool cannot serve. This arm
20555 /// crops -- never scales -- a superblock-aligned window out of the middle
20556 /// of the capture at its own resolution (at most 1920x1024, so the wall
20557 /// stays in the minutes) and runs the same 12-frame, four-quantizer
20558 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
20559 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
20560 /// sample-exactness assertion `our_ladder` makes.
20561 ///
20562 /// It is its own `--ignored` test so the default gate's wall does not
20563 /// grow. Every variant is an environment knob, and each of those is a
20564 /// `OnceLock` read once per process, so a variant is a separate run:
20565 ///
20566 /// cargo test -p ec-av1 --release --lib -- --ignored \
20567 /// bd_rate_screen_native --nocapture # baseline
20568 /// EC_AV1_INTRABC=1 ... same command # intra block copy
20569 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
20570 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
20571 /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
20572 /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing
20573 /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
20574 ///
20575 /// The coding pyramid is the DEFAULT of the sequence path this arm codes
20576 /// through (lane-av1pyrdef); the run prints the requested and the
20577 /// effective pyramid per clip, and a screen clip's effective one is
20578 /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
20579 /// streaming facade instead, which prints the per-level frame and byte
20580 /// census and asserts ffmpeg's decode against our own decoder on all
20581 /// three planes in display order; both arms code the same bytes
20582 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
20583 ///
20584 /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
20585 /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
20586 /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
20587 /// cost -- so every "film" column in the historical tables of this file
20588 /// is that generator, not film. The real content is `film A`, `film B`
20589 /// (native crops out of the two AV1 films the real-library manifest
20590 /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
20591 /// decision only the bars rows support is not supported.
20592 ///
20593 /// Measured 2026-09-07, the five rows before and after the screen
20594 /// detector grew libaom's variance term ([`screen_var`]) -- before it,
20595 /// BOTH real films were classified as screen content on 48/48 frames, so
20596 /// their coefficients were priced against the DEFAULT CDFs and the
20597 /// palette search ran over film; after, both are non-screen (0/48) and
20598 /// the capture is unchanged at 48/48:
20599 ///
20600 /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
20601 /// |---|---|---|---|
20602 /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
20603 /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
20604 /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
20605 /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
20606 /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
20607 ///
20608 /// Both bars rows and the capture are byte-identical across that change
20609 /// (their classification never moved); the palette search over film was
20610 /// costing roughly a tenth of the film rows' wall.
20611 ///
20612 /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
20613 /// sequence path's default -- the four non-screen rows take `4:-16:8`,
20614 /// the capture is gated flat and does not move a byte:
20615 ///
20616 /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
20617 /// |---|---|---|---|---|
20618 /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
20619 /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
20620 /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
20621 /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
20622 /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
20623 ///
20624 /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
20625 /// which is the point of the shared driver: the two entry points code one
20626 /// stream. The bars rows are fixtures (recorded, never a decision); the
20627 /// two real films are what the pyramid ships for.
20628 ///
20629 /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
20630 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
20631 /// setting any one of them keeps only the selected rows (the two 1080p
20632 /// rows, the two 2160p rows, the capture row respectively). A missing
20633 /// real film SKIPs its row; it never fails the gate.
20634 #[test]
20635 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
20636 fn bd_rate_screen_native() {
20637 let _knobs = crate::speed::knob_read();
20638 native_bd_arm("bd_rate_screen_native", 12, false);
20639 }
20640
20641 /// The LONG-GOP arm of the native BD gate: the same recipe as
20642 /// [`bd_rate_screen_native`] over the two real film rows only, but 48
20643 /// pictures with `gop = 48` (`encode_sequence` sets `gop =
20644 /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which
20645 /// reaches libaom as `--kf-max-dist=48` and rav1e as
20646 /// `key_frame_interval=48`), so every encoder sees one key frame and 47
20647 /// inter pictures.
20648 ///
20649 /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop =
20650 /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key
20651 /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`]
20652 /// above 12 codes the same stream there -- the shipped `16` was measured
20653 /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture
20654 /// group (class `instrument at bound` / `gate blind to feature`). The
20655 /// user's exports are long GOPs, so the pyramid shape is decided here.
20656 ///
20657 /// cargo test -p ec-av1 --release --lib -- --ignored \
20658 /// bd_rate_film_long_gop --nocapture
20659 ///
20660 /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1`
20661 /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape.
20662 /// Read every row off the log's own "pyramid requested/effective" print,
20663 /// never off the argument order of the runs (lane-pyr3 misattributed
20664 /// three rows that way).
20665 ///
20666 /// Table: `lanes/pyr4.sweep.txt`.
20667 #[test]
20668 #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"]
20669 fn bd_rate_film_long_gop() {
20670 let _knobs = crate::speed::knob_write();
20671 native_bd_arm("bd_rate_film_long_gop", 48, true);
20672 }
20673
20674 /// The shared driver of the two native BD arms above: `frames` pictures
20675 /// per row (the sequence's `gop` is the same number, so one key frame),
20676 /// four quantizers, `films_only` dropping every row but the two real
20677 /// films.
20678 fn native_bd_arm(label: &str, frames: usize, films_only: bool) {
20679 if !have_ffmpeg() {
20680 eprintln!("SKIP {label}: no ffmpeg");
20681 return;
20682 }
20683 let mut clips = native_gate_clips();
20684 if films_only {
20685 clips.retain(|(name, _, _)| name.starts_with("film "));
20686 }
20687 if clips.is_empty() {
20688 eprintln!("SKIP {label}: no clip");
20689 return;
20690 }
20691
20692 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
20693 .iter()
20694 .map(|q| {
20695 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
20696 .map(String::from)
20697 .to_vec()
20698 })
20699 .collect();
20700 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
20701 .iter()
20702 .map(|q| {
20703 vec![
20704 "-rav1e-params".to_string(),
20705 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
20706 ]
20707 })
20708 .collect();
20709 println!(
20710 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
20711 intrabc {}, palette maxcolors {}",
20712 armed_tiles(),
20713 crate::par::tile_threads(),
20714 intrabc_enabled(),
20715 palette_max_colors(),
20716 );
20717 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |");
20718 println!("|---|---|---|---|---|");
20719 for (name, path, seek) in &clips {
20720 let fctx = &crate::decode::FrameCtx::for_encoder();
20721 if probe_dims(path).is_none() {
20722 eprintln!("SKIP {name}: ffprobe gave no size");
20723 continue;
20724 }
20725 // A whole number of 128-wide superblocks, at most 1920x1024, out
20726 // of the middle of the frame; the offsets stay even for 4:2:0.
20727 // ONE definition, shared with `examples/enc_probe` so the probe
20728 // cannot measure a different window than this gate (lane-probe).
20729 let (vf, cw, ch) = match native_crop_override(path) {
20730 Some(over) => over,
20731 None => crate::probe::gate_crop(path),
20732 };
20733 let source = clip_frames_vf(path, seek, &vf, cw, ch, frames);
20734 SCREEN_FRAMES.iter().for_each(|c| {
20735 c.store(0, std::sync::atomic::Ordering::Relaxed);
20736 });
20737 let _ = crate::tile::take_palette_hits();
20738 let _ = crate::tile::take_palette_uv_hits();
20739 let _ = crate::tile::take_intrabc_hits();
20740 let _ = take_intrabc_search();
20741 let _ = crate::tile::take_filter_intra_hits();
20742 let _ = take_edge_census();
20743 // The sequence path itself codes the pyramid now
20744 // (lane-av1pyrdef), and prints what it requested and what the
20745 // content gate left effective.
20746 let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx);
20747 // lane-sse: the blocks the true frame edge cuts through, and how
20748 // much of their RAW squared error sat in the padding the encoder
20749 // invented past it -- what the inside-only score stopped ranking
20750 // on. Empty on a superblock-aligned crop, which is every default
20751 // gate row (class `gate-blind-to-feature`).
20752 if edge_census() {
20753 for (side, n, inside, padding) in take_edge_census() {
20754 eprintln!(
20755 "{name}: edge {side}x{side} scores={n} inside_sse={inside} \
20756 padding_sse={padding} ({:.1}% of raw)",
20757 100.0 * padding as f64 / (inside + padding).max(1) as f64,
20758 );
20759 }
20760 }
20761 // gate-blind-to-feature: what the screen tools actually did at
20762 // native resolution, over this clip's four encodes.
20763 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
20764 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
20765 // Which tables the SEARCH priced against, per frame arming
20766 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
20767 // real starting ones. A film clip must show every inter arming on
20768 // the real side, a screen clip none of them.
20769 let (price_default, price_real) = crate::tile::take_pricing_hits();
20770 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
20771 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
20772 // superblocks stayed whole, and how many of those coded a
20773 // residual, split that residual's luma, or took a compound
20774 // reference (class `gate-blind-to-feature`).
20775 // lane-i64: the KEY frame's own 64x64 intra root -- how many of
20776 // the superblocks offered the trial were coded whole.
20777 let [i64_whole, i64_offered, i64_edge] = take_i64_root_hits();
20778 eprintln!(
20779 "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%), \
20780 {i64_edge} on a superblock the frame edge cuts",
20781 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
20782 );
20783 eprintln!(
20784 "{name}: 128x128 roots {} (search) / {} (writer), with a residual \
20785 {} (search) / {} (writer); rect/AB pieces with a residual \
20786 {} (search) / {} (writer)",
20787 take_b128_none_hits(),
20788 crate::tile::take_sb128_none_hits(),
20789 take_b128_residual_hits(),
20790 crate::tile::take_sb128_residual_hits(),
20791 take_b128_rectres_hits(),
20792 crate::tile::take_sb128_rectres_hits(),
20793 );
20794 eprintln!(
20795 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
20796 take_b64_root_hits(),
20797 take_b64_residual_hits(),
20798 take_b64_var_tx_hits(),
20799 take_b64_compound_hits(),
20800 );
20801 // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan
20802 // of every priced block): what the deadzone quantiser handed the
20803 // RDOQ pass and what the pass changed, over every TRIAL block of
20804 // this row's four encodes -- not over the coded stream, so it is
20805 // the bits AT STAKE in the search, not in the bitstream.
20806 let rq = crate::tile::take_rdoq_stats();
20807 if rq[0] > 0 {
20808 eprintln!(
20809 "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \
20810 zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)",
20811 rq[0],
20812 rq[1],
20813 100.0 * rq[2] as f64 / rq[1].max(1) as f64,
20814 100.0 * rq[3] as f64 / rq[1].max(1) as f64,
20815 rq[4],
20816 rq[5],
20817 rq[7] as f64 / 64.0,
20818 rq[6] as f64 / 64.0,
20819 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64,
20820 );
20821 }
20822 // lane-av1obmc2: the same motion_mode census the 640x384 gate
20823 // prints (class `gate-blind-to-feature`) -- how many blocks coded
20824 // the symbol at each footprint and how many took OBMC. Without it
20825 // the native table, which is the standing keep table, could not
20826 // say whether the tool fired at all.
20827 let mm = crate::tile::take_motion_mode_hits();
20828 eprintln!(
20829 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
20830 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
20831 eligible)",
20832 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
20833 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20834 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20835 mm.iter().sum::<usize>(),
20836 );
20837 print_inter_tx_census(name);
20838 // lane-last2 (class `gate-blind-to-feature`): which reference the
20839 // 32x32-and-below inter blocks of this clip's four encodes chose.
20840 // The native table is the standing keep table, so a second past
20841 // reference that never won a block has to be visible HERE and not
20842 // only in a synthetic witness.
20843 let rh = crate::encode::take_ref_frame_hits();
20844 let rtot: usize = rh.iter().sum();
20845 eprintln!(
20846 "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \
20847 (LAST2 {:.1}%)",
20848 rh[1], rh[2], rh[4], rh[7], rtot,
20849 100.0 * rh[2] as f64 / rtot.max(1) as f64,
20850 );
20851 let palette = crate::tile::take_palette_hits();
20852 let palette_uv = crate::tile::take_palette_uv_hits();
20853 let ibc = crate::tile::take_intrabc_hits();
20854 let search = take_intrabc_search();
20855 eprintln!(
20856 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
20857 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
20858 won {})",
20859 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
20860 palette[0],
20861 palette_uv[0],
20862 ibc[0],
20863 search[0],
20864 search[1],
20865 search[2],
20866 );
20867 // gate-blind-to-feature: how often the five recursive filter-intra
20868 // modes actually won a block over this clip's four encodes -- a
20869 // tool that never fires is not measured by the row above it.
20870 let fi = crate::tile::take_filter_intra_hits();
20871 eprintln!(
20872 "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})",
20873 filter_intra_on(),
20874 fi[0],
20875 fi[1],
20876 fi[2],
20877 fi[3],
20878 fi[4],
20879 fi[5],
20880 );
20881 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
20882 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
20883 assert_monotone(&format!("{name}: ours"), &ours);
20884 assert_monotone(&format!("{name}: libaom"), &aom);
20885 assert_monotone(&format!("{name}: rav1e"), &rav1e);
20886 let points = ours
20887 .iter()
20888 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20889 .collect::<Vec<_>>()
20890 .join(", ");
20891 println!(
20892 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
20893 bd_rate(&aom, &ours) * 100.0,
20894 bd_rate(&rav1e, &ours) * 100.0,
20895 );
20896 // lane-pareto2: the two references at THEIR fast presets, plus
20897 // SVT-AV1, measured in the SAME arm as the row above -- the only
20898 // way the wall column of a Pareto table means anything (class:
20899 // wall tables are comparable only inside one interleaved batch).
20900 // `EC_AV1_PARETO_REFS=1` only: it roughly doubles the arm.
20901 if std::env::var("EC_AV1_PARETO_REFS").ok().as_deref() == Some("1") {
20902 let rav1e_at = |sp: u32| -> Vec<Vec<String>> {
20903 [50, 100, 150, 200]
20904 .iter()
20905 .map(|q| {
20906 vec![
20907 "-rav1e-params".to_string(),
20908 format!(
20909 "speed={sp}:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"
20910 ),
20911 ]
20912 })
20913 .collect()
20914 };
20915 let aom_at = |cu: u32| -> Vec<Vec<String>> {
20916 [5, 20, 35, 45]
20917 .iter()
20918 .map(|q| {
20919 vec![
20920 "-cpu-used".to_string(),
20921 cu.to_string(),
20922 "-b:v".to_string(),
20923 "0".to_string(),
20924 "-crf".to_string(),
20925 q.to_string(),
20926 ]
20927 })
20928 .collect()
20929 };
20930 let svt_at = |pr: u32| -> Vec<Vec<String>> {
20931 [20, 35, 45, 55]
20932 .iter()
20933 .map(|q| {
20934 vec![
20935 "-preset".to_string(),
20936 pr.to_string(),
20937 "-crf".to_string(),
20938 q.to_string(),
20939 "-svtav1-params".to_string(),
20940 "lp=1".to_string(),
20941 ]
20942 })
20943 .collect()
20944 };
20945 let mut arms: Vec<(String, &str, Vec<Vec<String>>)> = vec![
20946 ("rav1e speed 8".into(), "librav1e", rav1e_at(8)),
20947 ("rav1e speed 10".into(), "librav1e", rav1e_at(10)),
20948 ("libaom cpu-used 8".into(), "libaom-av1", aom_at(8)),
20949 ];
20950 if have_encoder("libsvtav1") {
20951 arms.push(("svt-av1 preset 8".into(), "libsvtav1", svt_at(8)));
20952 arms.push(("svt-av1 preset 10".into(), "libsvtav1", svt_at(10)));
20953 } else {
20954 eprintln!("SKIP the SVT-AV1 rows: this ffmpeg has no libsvtav1");
20955 }
20956 for (label, encoder, points) in arms {
20957 let (lad, wall) = external_ladder(&source, cw, ch, encoder, &points);
20958 // A REFERENCE stream our decoder cannot read is a note in
20959 // this table, not a gate failure: these rows exist to
20960 // price the references, and `assert_ladder_decodes` keeps
20961 // its teeth for the two ladders the keep table is read off.
20962 let notes =
20963 std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
20964 if !notes.is_empty() {
20965 eprintln!("{name} {label}: {} point(s) our decoder could not read (reference row, not a gate failure)", notes.len());
20966 }
20967 assert_monotone(&format!("{name}: {label}"), &lad);
20968 println!(
20969 "| {name} {cw}x{ch} / {label} | -- | {:+.1}% | {:+.1}% | {wall:.1}s (ours {ours_wall:.1}s, rav1e s6 {rav1e_wall:.1}s) |",
20970 bd_rate(&aom, &lad) * 100.0,
20971 bd_rate(&rav1e, &lad) * 100.0,
20972 );
20973 }
20974 }
20975 }
20976 assert_ladder_decodes();
20977 }
20978
20979 /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator
20980 /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC)
20981 /// on the two film clips at their native gate crop. The 2160p clip loses
20982 /// at every arm of the propagating map and the named suspect was that its
20983 /// heavily filtered flat cells give a tiny denominator, so the dependence
20984 /// ratio explodes exactly where coding is cheap; this prints the numbers
20985 /// that confirm or refute it.
20986 #[test]
20987 #[ignore = "needs ffmpeg and the film fixtures"]
20988 fn tpl_intra_denominator_histogram() {
20989 let _knobs = crate::speed::knob_read();
20990 if !have_ffmpeg() {
20991 eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg");
20992 return;
20993 }
20994 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
20995 for (label, file) in [
20996 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
20997 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
20998 ] {
20999 let path = fixtures.join("video").join(file);
21000 if !path.exists() {
21001 eprintln!("SKIP {label}: {file} missing");
21002 continue;
21003 }
21004 let path = path.to_str().unwrap();
21005 let Some((nw, nh)) = probe_dims(path) else {
21006 eprintln!("SKIP {label}: ffprobe gave no size");
21007 continue;
21008 };
21009 let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128);
21010 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
21011 let source =
21012 clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8);
21013 let mut costs: Vec<f64> = Vec::new();
21014 for pic in &source {
21015 let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect();
21016 costs.extend(
21017 super::tpl_intra_costs(&y8, cw, ch).iter().map(|&c| f64::from(c)),
21018 );
21019 }
21020 let mean = costs.iter().sum::<f64>() / costs.len() as f64;
21021 let mut sorted = costs.clone();
21022 sorted.sort_by(f64::total_cmp);
21023 let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean;
21024 let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count();
21025 eprintln!(
21026 "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \
21027 as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \
21028 p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \
21029 below 1.0x {} ({:.1}%)",
21030 costs.len(),
21031 q(0.0),
21032 q(0.01),
21033 q(0.05),
21034 q(0.25),
21035 q(0.50),
21036 q(0.75),
21037 q(0.99),
21038 q(1.0),
21039 below(0.25),
21040 100.0 * below(0.25) as f64 / costs.len() as f64,
21041 below(0.5),
21042 100.0 * below(0.5) as f64 / costs.len() as f64,
21043 below(1.0),
21044 100.0 * below(1.0) as f64 / costs.len() as f64,
21045 );
21046 }
21047 }
21048
21049 /// The probe arms the gate's source (lane-probe, class `instrument
21050 /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
21051 /// command line and had no `-ss`, so it read film B from frame 0 -- a
21052 /// black leader -- and coded 59 kB where the gate's own ladder point
21053 /// coded 89 kB of the same title; every census taken through it was
21054 /// probe-relative. Both now call [`crate::probe::source`]; this pins that
21055 /// the shared loader honours the seek (arming the probe's way and the
21056 /// gate's way gives byte-identical streams, and dropping the seek does
21057 /// not), on a synthetic clip whose content moves over time.
21058 #[test]
21059 fn the_probe_arms_the_gates_source() {
21060 let _knobs = crate::speed::knob_write();
21061 if !have_ffmpeg() {
21062 eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg");
21063 return;
21064 }
21065 let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
21066 std::fs::create_dir_all(&dir).unwrap();
21067 let clip = dir.join("testsrc2.y4m");
21068 // 384x202: neither side is a multiple of 128, so the gate's centre
21069 // window is a real derivation and not the frame itself -- exactly the
21070 // shape film B has (3840x1608, never 3840x2160).
21071 let ok = Command::new("ffmpeg")
21072 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=384x202:rate=10"])
21073 .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
21074 .arg(&clip)
21075 .status()
21076 .expect("ffmpeg failed to run")
21077 .success();
21078 assert!(ok, "ffmpeg could not write the synthetic clip");
21079 let path = clip.to_str().unwrap();
21080
21081 // The window: superblock-aligned, centred, even offsets.
21082 let (vf, w, h) = crate::probe::gate_crop(path);
21083 assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
21084
21085 let (seek, q) = ("00:00:01", 150u8);
21086 let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
21087 let probe = crate::probe::source(path, seek, &vf, w, h, 6);
21088 assert!(
21089 gate.iter().zip(&probe).all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
21090 "the probe's source differs from the gate's at the same window"
21091 );
21092 let bytes = |src: &[Picture]| {
21093 encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
21094 .unwrap()
21095 .stream
21096 };
21097 assert_eq!(bytes(&gate), bytes(&probe), "probe and gate code different bytes");
21098 // The two witnesses that both halves of the arming reach ffmpeg: the
21099 // seek, and the crop's own offset (the film-B defect in miniature --
21100 // the probe was reading `crop=..:568` of a 1608-high frame).
21101 let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
21102 assert_ne!(
21103 bytes(&gate),
21104 bytes(&unseeked),
21105 "seeked and unseeked arming coded the same bytes -- the seek is inert"
21106 );
21107 let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
21108 assert_ne!(
21109 bytes(&gate),
21110 bytes(&offset),
21111 "centred and top-aligned windows coded the same bytes -- the crop is inert"
21112 );
21113 std::fs::remove_dir_all(&dir).ok();
21114 }
21115
21116 /// lane-probe diagnostic: the gate's own loader + ladder call for ONE
21117 /// point inside the test binary, to compare against `examples/enc_probe`.
21118 #[test]
21119 #[ignore = "diagnostic: needs ffmpeg and a clip"]
21120 fn probe_parity_point() {
21121 let _knobs = crate::speed::knob_write();
21122 let g = |k: &str| std::env::var(k).unwrap();
21123 let (w, h) = g("EC_PARITY_DIMS").split_once(':').map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap())).unwrap();
21124 let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap();
21125 let q: u8 = g("EC_PARITY_Q").parse().unwrap();
21126 let source = clip_frames_vf(&g("EC_PARITY_CLIP"), &g("EC_PARITY_SS"), &g("EC_PARITY_VF"), w, h, frames);
21127 let fctx = &crate::decode::FrameCtx::for_encoder();
21128 let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
21129 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
21130 for &b in &e.stream {
21131 hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
21132 }
21133 eprintln!("PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}",
21134 e.stream.len(), crate::speed::speed(), crate::encoder::Pyramid::from_env(), last_sequence_pyramid());
21135 }
21136 /// lane-refs/lane-last2: IS A SECOND PAST REFERENCE WORTH RETAINING? The
21137 /// lever this census priced SHIPS since lane-last2 (merge `321b2dc1`):
21138 /// `EC_AV1_LAST2` (default OFF) retains a second past leaf picture in
21139 /// `LEAF_SLOTS`, names it `ref_frame_idx[1]`, and offers it to the 32x32
21140 /// search with its own `NEWMV` (`EC_AV1_LAST2_NEW`); the ARF-level lags
21141 /// the census's far row measures were already banked by `arf_altref`.
21142 /// This census stays the PRICING arm (class `gate-blind-to-feature`): its
21143 /// best-of-two SAD shares are read against the fire share the gate census
21144 /// prints (`references ... LAST2 n (n%)`) and the refutation in
21145 /// `lanes/last2.report.md` §4 -- a pure-SAD best-of-two over-counts the
21146 /// lever by more than an order of magnitude once NEAR/NEAREST/DRL off
21147 /// `LAST`, the backward `ALTREF`, and the rate term price in.
21148 ///
21149 /// The measurement is on the gate's own window and loader (`gate_crop`,
21150 /// 12 pictures) of the two real films: every 16x16 luma block of every
21151 /// picture gets one full-pel diamond search against the NEAR reference
21152 /// and the same search against the FAR one, at the two lags the pyramid
21153 /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF
21154 /// level, rav1e's own pair. Reported per lag: the share of blocks the far
21155 /// reference wins at all and by more than 10%, and -- the number the
21156 /// decision is taken on -- the total SAD of best-of-{near, far} against
21157 /// the total SAD of near alone, which is the prediction energy a second
21158 /// reference could remove before any rate is paid for naming it.
21159 ///
21160 /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture
21161 #[test]
21162 #[ignore = "reads the real films"]
21163 fn last2_census() {
21164 if !have_ffmpeg() {
21165 eprintln!("SKIP last2_census: no ffmpeg");
21166 return;
21167 }
21168 const SIDE: usize = 16;
21169 // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or
21170 // `None` when the displaced block leaves the picture.
21171 let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
21172 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
21173 if sy < 0 || sx < 0 {
21174 return None;
21175 }
21176 let (sy, sx) = (sy as usize, sx as usize);
21177 if sy + SIDE > r.height || sx + SIDE > r.width {
21178 return None;
21179 }
21180 let mut acc = 0u64;
21181 for row in 0..SIDE {
21182 let c = &cur.y[(by + row) * cur.width + bx..][..SIDE];
21183 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
21184 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
21185 }
21186 Some(acc)
21187 };
21188 // A log-step diamond from the zero motion vector: the cheapest search
21189 // that still finds real pans. Both references get exactly this one,
21190 // so the comparison is search-fair.
21191 let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 {
21192 let mut best = (sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX), (0isize, 0isize));
21193 let mut step = 16isize;
21194 while step >= 1 {
21195 let centre = best.1;
21196 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
21197 let mv = (centre.0 + dy * step, centre.1 + dx * step);
21198 if let Some(s) = sad(cur, r, bx, by, mv) {
21199 if s < best.0 {
21200 best = (s, mv);
21201 }
21202 }
21203 }
21204 step /= 2;
21205 }
21206 best.0
21207 };
21208 println!("| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |");
21209 println!("|---|---|---|---|---|---|---|---|");
21210 for (name, path, seek) in native_gate_clips() {
21211 if !name.starts_with("film ") {
21212 continue;
21213 }
21214 let (vf, cw, ch) = crate::probe::gate_crop(&path);
21215 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12);
21216 for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] {
21217 let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64);
21218 let (mut near_sad, mut best_sad) = (0u64, 0u64);
21219 for i in far..pictures.len() {
21220 let cur = &pictures[i];
21221 let (rn, rf) = (&pictures[i - near], &pictures[i - far]);
21222 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
21223 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
21224 let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by));
21225 blocks += 1;
21226 wins += u64::from(f < n);
21227 big += u64::from(f as f64 * 1.1 < n as f64);
21228 near_sad += n;
21229 best_sad += n.min(f);
21230 }
21231 }
21232 }
21233 let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64;
21234 println!(
21235 "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |",
21236 pct(wins),
21237 pct(big),
21238 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64,
21239 );
21240 }
21241 }
21242 }
21243
21244 /// lane-arfpred: WHAT THE TOP ARF'S PREDICTION IS WORTH, and what a
21245 /// temporal filter of its SOURCE would take off it, priced before any
21246 /// encoder change (class `gate-blind-to-feature`).
21247 ///
21248 /// The stream census says our top ARF costs 6992 B a frame against
21249 /// rav1e's 3872 at a COARSER quantizer (118 vs 104) for the same picture
21250 /// quality, and that 61% of the gap is residual, not syntax. Two
21251 /// explanations are separable here without an encoder: our anchor
21252 /// predicts across 8 pictures where rav1e's predicts across 4 (lag), and
21253 /// the residual it codes at that lag is dominated by film grain, which no
21254 /// motion search can predict (source noise). So, per ARF position of the
21255 /// gate's own 48-picture window:
21256 ///
21257 /// * mean full-pel SAD per pixel at lag 8 (ours) and lag 4 (rav1e's),
21258 /// * the same at lag 8 with the CURRENT picture temporally filtered --
21259 /// a libaom-shaped motion-compensated average of the +-2 display
21260 /// neighbours, weights `exp(-mse / strength)` -- which is the residual
21261 /// energy an ARF temporal filter would remove, and
21262 /// * PSNR of that filtered picture against the unfiltered one, the
21263 /// CEILING the filtered ARF's own PSNR is then measured under (the
21264 /// BD gate scores against the unfiltered source).
21265 ///
21266 /// EC_ARF_TF_S=<strength> cargo test -p ec-av1 --release --lib -- \
21267 /// --ignored arf_pred_census --nocapture
21268 #[test]
21269 #[ignore = "reads the real films"]
21270 fn arf_pred_census() {
21271 if !have_ffmpeg() {
21272 eprintln!("SKIP arf_pred_census: no ffmpeg");
21273 return;
21274 }
21275 const SIDE: usize = 16;
21276 let strength: f64 = std::env::var("EC_ARF_TF_S")
21277 .ok()
21278 .and_then(|v| v.parse().ok())
21279 .unwrap_or(30.0);
21280 let past = std::env::var("EC_ARF_TF_PAST").as_deref() == Ok("1");
21281 // SAD and the matching block of `r` at full-pel `(dy, dx)`, or `None`
21282 // when the displaced block leaves the picture.
21283 let at = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
21284 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
21285 if sy < 0 || sx < 0 {
21286 return None;
21287 }
21288 let (sy, sx) = (sy as usize, sx as usize);
21289 if sy + SIDE > r.height || sx + SIDE > r.width {
21290 return None;
21291 }
21292 let mut acc = 0u64;
21293 for row in 0..SIDE {
21294 let c = &cur[row * cw..][..SIDE];
21295 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
21296 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
21297 }
21298 Some((acc, (sy, sx)))
21299 };
21300 // The same log-step diamond `last2_census` uses, so the two censuses'
21301 // SADs are comparable.
21302 let search = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize| {
21303 let mut best = match at(cur, cw, r, bx, by, (0, 0)) {
21304 Some(v) => v,
21305 None => return (u64::MAX, (by, bx)),
21306 };
21307 let mut centre = (0isize, 0isize);
21308 let mut step = 16isize;
21309 while step >= 1 {
21310 let from = centre;
21311 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
21312 let mv = (from.0 + dy * step, from.1 + dx * step);
21313 if let Some(s) = at(cur, cw, r, bx, by, mv) {
21314 if s.0 < best.0 {
21315 best = s;
21316 centre = mv;
21317 }
21318 }
21319 }
21320 step /= 2;
21321 }
21322 best
21323 };
21324 println!(
21325 "| clip | ARFs | strength {strength} past {past} | lag8 SAD/px | lag4 SAD/px | tf lag8 SAD/px | tf removes | tf PSNR ceiling |"
21326 );
21327 println!("|---|---|---|---|---|---|---|");
21328 for (name, path, seek) in native_gate_clips() {
21329 if !name.starts_with("film ") {
21330 continue;
21331 }
21332 let (vf, cw, ch) = crate::probe::gate_crop(&path);
21333 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 48);
21334 let (mut n8, mut n4, mut ntf, mut px, mut arfs) = (0u64, 0u64, 0u64, 0u64, 0usize);
21335 let (mut tf_sse, mut tf_px) = (0f64, 0u64);
21336 for i in (8..pictures.len()).step_by(8) {
21337 arfs += 1;
21338 let cur = &pictures[i];
21339 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
21340 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
21341 let block: Vec<u16> = (0..SIDE)
21342 .flat_map(|row| cur.y[(by + row) * cur.width + bx..][..SIDE].to_vec())
21343 .collect();
21344 n8 += search(&block, SIDE, &pictures[i - 8], bx, by).0;
21345 n4 += search(&block, SIDE, &pictures[i - 4], bx, by).0;
21346 // The temporal filter: each +-2 display neighbour is
21347 // motion-compensated onto this block and averaged in
21348 // with libaom's shape, a weight that falls with the
21349 // match's own mean squared error.
21350 let mut acc: Vec<f64> = block.iter().map(|&v| f64::from(v)).collect();
21351 let mut wsum = 1.0f64;
21352 // `EC_ARF_TF_PAST=1` restricts the filter to the
21353 // DISPLAY-PAST neighbours -- the only ones the
21354 // encoder's own group buffer holds when it codes its
21355 // top ARF (the group's future is not buffered yet).
21356 let offs: &[isize] = match past {
21357 true => &[-2, -1],
21358 false => &[-2, -1, 1, 2],
21359 };
21360 for &d in offs {
21361 let j = i as isize + d;
21362 let Some(nb) = usize::try_from(j).ok().and_then(|j| pictures.get(j))
21363 else {
21364 continue;
21365 };
21366 let (_, (sy, sx)) = search(&block, SIDE, nb, bx, by);
21367 let mut sse = 0f64;
21368 for row in 0..SIDE {
21369 for col in 0..SIDE {
21370 let d = f64::from(block[row * SIDE + col])
21371 - f64::from(nb.y[(sy + row) * nb.width + sx + col]);
21372 sse += d * d;
21373 }
21374 }
21375 let w = (-sse / ((SIDE * SIDE) as f64) / strength).exp();
21376 for row in 0..SIDE {
21377 for col in 0..SIDE {
21378 acc[row * SIDE + col] +=
21379 w * f64::from(nb.y[(sy + row) * nb.width + sx + col]);
21380 }
21381 }
21382 wsum += w;
21383 }
21384 let filtered: Vec<u16> = acc
21385 .iter()
21386 .map(|v| (v / wsum).round().clamp(0.0, 1023.0) as u16)
21387 .collect();
21388 for (a, b) in filtered.iter().zip(&block) {
21389 let d = f64::from(*a) - f64::from(*b);
21390 tf_sse += d * d;
21391 }
21392 tf_px += (SIDE * SIDE) as u64;
21393 ntf += search(&filtered, SIDE, &pictures[i - 8], bx, by).0;
21394 px += (SIDE * SIDE) as u64;
21395 }
21396 }
21397 }
21398 let per = |v: u64| v as f64 / px.max(1) as f64;
21399 let mse = tf_sse / tf_px.max(1) as f64;
21400 println!(
21401 "| {name} | {arfs} | s{strength} p{past} | {:.3} | {:.3} | {:.3} | {:.1}% | {:.2} dB |",
21402 per(n8),
21403 per(n4),
21404 per(ntf),
21405 100.0 * (n8 - ntf) as f64 / n8.max(1) as f64,
21406 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(),
21407 );
21408 }
21409 }
21410
21411 /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
21412 /// hardwire the REGULAR kernel, so the encoder could not have coded a
21413 /// SMOOTH or SHARP frame even if the header had said so -- the search,
21414 /// the trials, the recon and the frame header now all read
21415 /// `FrameCtx::interp_filter`. Each of the three kernels codes its own
21416 /// distinct stream (a filter that never reached the prediction would code
21417 /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg
21418 /// reconstructs every frame of each of them exactly, which is what proves
21419 /// the header and the prediction agree.
21420 #[test]
21421 fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() {
21422 let _knobs = crate::speed::knob_write();
21423 if !have_ffmpeg() {
21424 eprintln!("SKIP each_frame_interpolation_filter_codes_its_own_stream: no ffmpeg");
21425 return;
21426 }
21427 let (width, height) = (256usize, 128usize);
21428 // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so
21429 // all three kernels would code the same bytes and the test would pass
21430 // on a wiring that does nothing (class `fixture proves the symbol, not
21431 // the signal`). `panned_test_card` shifts by whole pixels, so the
21432 // search finds the sub-pel positions off the reconstruction instead:
21433 // three frames of a slow diagonal pan.
21434 let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect();
21435 let mut streams = Vec::new();
21436 for filter in [
21437 ec_av1_syntax::InterpolationFilter::Eighttap,
21438 ec_av1_syntax::InterpolationFilter::EighttapSmooth,
21439 ec_av1_syntax::InterpolationFilter::EighttapSharp,
21440 ] {
21441 set_frame_interp(Some(filter));
21442 let fctx = &crate::decode::FrameCtx::for_encoder();
21443 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
21444 .unwrap_or_else(|e| panic!("{filter:?}: {e}"));
21445 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
21446 assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count");
21447 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
21448 assert_eq!(decoded.y, frame.reconstruction.y, "{filter:?} frame {i}: luma");
21449 assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
21450 assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
21451 }
21452 streams.push((filter, encoded.stream));
21453 }
21454 set_frame_interp(None);
21455 for (i, (fa, a)) in streams.iter().enumerate() {
21456 for (fb, b) in &streams[i + 1..] {
21457 assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
21458 }
21459 }
21460 }
21461
21462
21463 /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
21464 /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
21465 /// residual outright (`round_to_valid_mv` rounds it away first), so the
21466 /// finest vector the encoder could commit to was a quarter pel. With the
21467 /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
21468 /// non-zero component and the search's fourth stage refines to the
21469 /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
21470 /// on arm, and -- the part that makes it a signal rather than a symbol
21471 /// count (class `fixture proves the symbol, not the signal`) -- that some
21472 /// of them come out ZERO, i.e. name a vector the off arm cannot code at
21473 /// all. Both streams are decoded by ffmpeg AND by this crate's own
21474 /// decoder and asserted sample-exact against the encoder's own
21475 /// reconstruction, which is what proves the header bit and the symbols
21476 /// agree.
21477 #[test]
21478 fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
21479 let _knobs = crate::speed::knob_write();
21480 if !have_ffmpeg() {
21481 eprintln!("SKIP a_high_precision_frame_codes_eighth_pel_motion_vectors: no ffmpeg");
21482 return;
21483 }
21484 let (width, height) = (256usize, 128usize);
21485 let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect();
21486 let mut arms = Vec::new();
21487 for hp in [false, true] {
21488 set_high_precision_mv(Some(hp));
21489 let _ = crate::tile::take_hp_symbols();
21490 let fctx = &crate::decode::FrameCtx::for_encoder();
21491 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
21492 .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
21493 let (symbols, eighth) = crate::tile::take_hp_symbols();
21494 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
21495 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
21496 assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
21497 assert_eq!(ours.len(), pictures.len(), "hp={hp}: our decoder frame count");
21498 for (i, e) in encoded.frames.iter().enumerate() {
21499 for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
21500 if let Some((plane, s, got, want)) = first_plane_mismatch(got, &e.reconstruction)
21501 {
21502 panic!(
21503 "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
21504 the encoder reconstructed {want}"
21505 );
21506 }
21507 }
21508 }
21509 arms.push((symbols, eighth, encoded.stream));
21510 }
21511 set_high_precision_mv(None);
21512 let (off, on) = (&arms[0], &arms[1]);
21513 assert_eq!(off.0, 0, "a frame without the header bit codes no hp symbol");
21514 assert!(on.0 > 0, "a high-precision frame codes hp symbols (got {})", on.0);
21515 assert!(
21516 on.1 > 0,
21517 "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)",
21518 on.0
21519 );
21520 assert_ne!(off.2, on.2, "the two arms coded the same bytes");
21521 println!(
21522 "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B",
21523 off.0,
21524 off.2.len(),
21525 on.0,
21526 on.1,
21527 on.2.len()
21528 );
21529 }
21530}