forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB1e4e107Tahinli2 months ago2830 commits

encode.rs18534 lines, 838.4 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: the INTER half of the widening is still NOT applied here, and
476/// the reason lane-txi recorded (the `refs` lane's DPB bookkeeping) was
477/// WRONG -- the refusal is `refusal-from-own-desync` twice over. Half of it
478/// was this writer coding a `V_DCT`/`H_DCT` unit as `TX_CLASS_2D`
479/// (`tile::write_coeffs`, fixed by this lane, which is what unblocked the
480/// intra half). What remains is the CHROMA inheritance: an inter block's
481/// chroma transform type is the luma type reduced to the chroma size's set
482/// (`decode::reduce_inherited_chroma_tx_type`), and (a) the encoder never
483/// sets `FrameCtx::reduced_tx_set_inter`, so [`recode_inter_chroma`] reduces
484/// against the REDUCED allowance while a `reduced_tx_set = 0` frame's
485/// decoder allows the full one, and (b) `tile::write_block_planes` codes
486/// every chroma plane as `DCT_DCT`, so an inherited 1-D type desyncs the
487/// chroma exactly as luma did. Both are deferred with the wider inter search
488/// itself; the intra half needs neither (an intra block's chroma type comes
489/// off its own UV mode, never off luma).
490fn inter_luma_set(tx: usize) -> Option<TxbSet> {
491 Some(match tx {
492 4 => TxbSet::Luma4Inter,
493 8 => TxbSet::Luma8Inter,
494 16 => TxbSet::Luma16Inter,
495 32 => TxbSet::Luma32Inter,
496 _ => return None,
497 })
498}
499
500fn tx_type_search() -> bool {
501 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
502 crate::envflags::var("EC_AV1_TXSET")
503 .ok()
504 .map(|v| !matches!(v.as_str(), "0" | "off"))
505 });
506 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH))
507}
508
509/// Whether an intra luma unit of this frame searches its own type at all:
510/// the preset lever ([`tx_type_search`]) under the screen content gate, which
511/// `EC_AV1_TXSET=all` ([`intra_tx_all_frames`]) lifts and the process-global
512/// [`set_intra_tx_search`] override wins over (the witness needs the search
513/// on a frame the detector called non-screen).
514fn intra_tx_search_on(screen: bool) -> bool {
515 match INTRA_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
516 0 => return false,
517 1 => return true,
518 _ => {}
519 }
520 (screen || intra_tx_all_frames()) && tx_type_search()
521}
522
523/// A PROCESS-GLOBAL [`intra_tx_search_on`] override (`u8::MAX` = unset), the
524/// shape [`set_inter_tx_search`] has.
525static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
526 std::sync::atomic::AtomicU8::new(u8::MAX);
527
528/// Sets [`INTRA_TX_OVERRIDE`]; `None` clears it.
529#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
530pub(crate) fn set_intra_tx_search(on: Option<bool>) {
531 INTRA_TX_OVERRIDE.store(
532 on.map_or(u8::MAX, u8::from),
533 std::sync::atomic::Ordering::Relaxed,
534 );
535}
536
537/// lane-txi: `EC_AV1_TXSET=all` offers the five-type intra set on EVERY
538/// frame -- the unconditional arm the gate measures -- instead of the screen
539/// content gate [`tx_type_candidates`] ships behind. Any other value keeps
540/// the gate (`0`/`off` still switches the search off entirely).
541fn intra_tx_all_frames() -> bool {
542 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
543 crate::envflags::var("EC_AV1_TXSET").is_ok_and(|v| v == "all")
544 });
545 *ENV
546}
547
548fn tx_select() -> bool {
549 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
550 crate::envflags::var("EC_AV1_TX_SELECT")
551 .ok()
552 .map(|v| !matches!(v.as_str(), "0" | "off"))
553 });
554 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY))
555}
556
557fn split_inter_8() -> bool {
558 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
559 Some(v) if cfg!(test) => v != "0",
560 _ => crate::speed::at(&crate::speed::SPLIT_8),
561 }
562}
563
564/// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
565/// NEARESTMV candidate it always had.
566pub(crate) const LEAF_NEW_MV: bool = true;
567
568/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
569/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
570/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
571/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
572pub(crate) const EXTRA_REF_NEW_MV: bool = true;
573
574/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
575/// own best vector before that reference's `NEWMV` search is skipped: a
576/// factor on the search cost scale, `1.0` meaning "as good or better".
577/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
578/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
579/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
580/// extra searches drop from +27% to +4% of the base count -- and on screen
581/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
582/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
583/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: 0.25
584/// reads +16.6/-0.6, +47.0/+19.1, +51.3/-14.3 and 0.5 reads +16.6/-0.7,
585/// +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, +47.0/+19.1,
586/// +51.3/-14.3 -- one row 0.1-0.2 down, two flat, inside the measurement's
587/// own noise. 0.35 stays; the lever that did move at the new rate weight is
588/// [`LEAF_SECOND_NEW_MARGIN`], not this one.
589const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
590
591/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
592fn extra_new_skip_margin() -> f64 {
593 match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
594 Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
595 _ => EXTRA_NEW_SKIP_MARGIN,
596 }
597}
598
599/// The margin on a LEAF's SECOND-reference motion search, the same early-out
600/// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference
601/// `NEWMV`: the search is skipped when that reference's own
602/// `NEAREST_NEARESTMV` vector already prices this many times better than the
603/// leaf's `LAST` search found. `0.0` never skips.
604///
605/// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs
606/// libaom (1080p/2160p/screen) against the extra `motion::search` calls at
607/// 2160p (38195 with no second-reference search at all):
608/// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093,
609/// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at
610/// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the
611/// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter
612/// of its extra searches; past it the calls double for another -0.3/-0.5.
613/// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is
614/// all `NEAREST_NEARESTMV` and no searched second vector ever wins there --
615/// so the margin is pure wall on that content (+10% searches at 0.8).
616///
617/// RE-SWEPT on lane-av1rejudge after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, on
618/// the native gate with local warp on, BD vs libaom / vs rav1e:
619///
620/// | margin | film 1080p | film 2160p | screen |
621/// |---|---|---|---|
622/// | 0.6 | +16.9 / -0.4 | +47.0 / +19.1 | +51.2 / -14.4 |
623/// | 0.8 (was) | +16.7 / -0.5 | +47.0 / +19.1 | +51.3 / -14.3 |
624/// | 1.2 | +16.2 / -1.1 | +46.6 / +18.8 | +51.3 / -14.4 |
625/// | 1.6 | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
626/// | 0.0 (never skip) | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
627///
628/// 1.2 is the floor of that bowl -- two rows 0.3-0.6 down on BOTH columns
629/// with screen flat -- and it beats never-skipping, i.e. the early-out is
630/// still worth having, just at a looser margin than the old rate weight
631/// wanted. It costs about 10% encoder wall on the two film clips (36.6s vs
632/// 32.6s at 2160p), which is the price of the extra second-reference
633/// searches.
634const LEAF_SECOND_NEW_MARGIN: f64 = 1.2;
635
636/// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the
637/// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`.
638fn leaf_second_new_margin() -> f64 {
639 match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() {
640 Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN),
641 None => LEAF_SECOND_NEW_MARGIN,
642 }
643}
644
645/// Whether a leaf searches its SECOND reference at all (lane-av1comp4).
646fn leaf_second_new_mv() -> bool {
647 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
648 Some(v) => v != "0",
649 None => crate::speed::at(&crate::speed::LEAF_SECOND),
650 }
651}
652
653/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
654/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
655/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
656/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
657/// was missing was the encoder ever forming one below 32x32.
658pub(crate) const LEAF_COMPOUND: bool = true;
659
660/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
661fn leaf_compound() -> bool {
662 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
663 Some(v) => v != "0",
664 None => crate::speed::at(&crate::speed::LEAF_COMPOUND),
665 }
666}
667
668/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
669fn leaf_new_mv() -> bool {
670 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
671 Some(v) if cfg!(test) => v != "0",
672 _ => LEAF_NEW_MV,
673 }
674}
675
676/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
677/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
678/// the true frame edge cut through was ever split there; inside the frame
679/// every block was coded whole, which left the partition decision the key
680/// frame already makes unmade for eleven frames out of twelve.
681pub(crate) const SPLIT_INTER_BLOCKS: bool = true;
682
683/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
684/// measurement that keeps it is running (test builds only, like
685/// [`lambda_scale`]).
686fn split_inter_blocks() -> bool {
687 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
688 Some(v) if cfg!(test) => v != "0",
689 _ => crate::speed::at(&crate::speed::SPLIT_INTER),
690 }
691}
692
693/// Whether the inter search offers the whole superblock as ONE 64x64 block
694/// (`PARTITION_NONE` at `BLOCK_64X64`), coded SKIP, against the four 32x32
695/// quadrants it would otherwise always split into.
696///
697/// The census (`lanes/census-filmB.md`) is what points here: rav1e speed 6
698/// codes 45.2% of its blocks at 64x64 -- 73.8% of its LEAF blocks, 99.2% of
699/// them skip at 328 bytes a frame -- while every block this encoder wrote was
700/// 32x32 or smaller, which put our mode+mv+partition+tx_size spend at 162,669
701/// bits against rav1e's 61,988, about 46% of the film B gap.
702///
703/// lane-tx64: no longer skip-only. The root also prices a REAL residual --
704/// one TX_64X64 luma transform (`transform.rs`'s forward network has always
705/// reached 64 points; what was missing was the block coder and the writer
706/// around it) and one TX_32X32 per chroma plane -- see [`b64_residual`],
707/// which carries that arm's own gate table. Still refused at the 64 root:
708/// compound references, a depth-1 4x32x32 var-tx tree, intra, and a
709/// superblock the true frame edge cuts through.
710///
711/// Switched off by `EC_AV1_B64=0` in any build; `EC_AV1_B64RES=0` keeps the
712/// root and restores the skip-only shape lane-b64 shipped.
713pub(crate) const B64_ROOT: bool = true;
714
715/// How many superblocks took the 64x64 root since the last
716/// [`take_b64_root_hits`], so a gate reports how often it fires rather than
717/// assuming it does (class `gate-blind-to-feature`).
718static B64_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
719
720/// The 64x64-root count since the last call, and zero it.
721pub fn take_b64_root_hits() -> usize {
722 B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
723}
724
725/// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq).
726/// Preset-gated: it re-prices the block once per candidate level, so it buys
727/// bits with wall (see `crate::speed::RDOQ` for the per-preset table).
728///
729/// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser --
730/// which is what the byte pins are taken under when they name it.
731fn rdoq_on() -> bool {
732 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
733 crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0")
734 });
735 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ))
736}
737
738/// The rate weight [`crate::tile::rdoq`] trades bits for squared error at, in
739/// units of one squared AC quantiser step -- the search's own
740/// [`LAMBDA_SCALE`], so the quantiser and the mode search speak one currency.
741///
742/// The per-frame factors the search multiplies onto it ([`key_lambda_factor`],
743/// [`hidden_lambda_factor`], both 1.0 as shipped) and the per-superblock
744/// temporal map ([`tpl_lambda_factors`]) are NOT threaded down here:
745/// corner-cut, ceiling = a superblock the temporal map weighs away from the
746/// frame average has its coefficients optimised at the frame's weight. The
747/// upgrade is one `lambda` field on the trial call sites, which is the whole
748/// mode-search argument list.
749///
750/// SWEPT (lane-rdoq, 12-frame `bd_rate_screen_native`, BD vs libaom
751/// `cpu-used 6` on the three real rows). The bowl is a factor of TWO above
752/// the mode search's own weight, and it is the same multiplier on all three
753/// rows:
754///
755/// | `EC_AV1_RDOQ_LAMBDA` | film A | film B | screen |
756/// |---|---|---|---|
757/// | 0.7 | +27.6 | +39.5 | +29.6 |
758/// | 1.0 | +26.3 | +37.5 | +29.1 |
759/// | 1.3 | +25.6 | +37.0 | +28.8 |
760/// | 1.6 | +24.6 | +35.9 | +28.7 |
761/// | 2.2 (shipped) | +24.4 | +35.5 | +28.1 |
762/// | 3.2 | +24.7 | +36.1 | +29.4 |
763///
764/// A coefficient's rate is worth twice here what the mode search prices it
765/// at, and the likeliest reason is that the price is taken against tables
766/// that have not adapted yet ([`crate::tile::coeff_bits`]): a block coded
767/// late in a frame whose `txb_skip`/`base` tables have narrowed really costs
768/// less than the pricer says, and this pass is the one decision taken per
769/// COEFFICIENT, so it feels that error most. The honest fix is an adapted
770/// price, not a fitted multiplier; this is the fitted multiplier, and its
771/// bowl is measured rather than assumed.
772const RDOQ_LAMBDA_MULT: f64 = 2.2;
773
774/// [`RDOQ_LAMBDA_MULT`], or what `EC_AV1_RDOQ_LAMBDA` names (the rate-term
775/// calibration sweep).
776fn rdoq_lambda() -> f64 {
777 static MULT: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
778 crate::envflags::var("EC_AV1_RDOQ_LAMBDA")
779 .ok()
780 .and_then(|v| v.parse().ok())
781 .unwrap_or(RDOQ_LAMBDA_MULT)
782 });
783 lambda_scale() * *MULT
784}
785
786/// [`B64_ROOT`], or what `EC_AV1_B64` names.
787fn b64_root() -> bool {
788 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
789 crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0")
790 });
791 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))
792}
793
794/// The KEY frame's own 64x64 root (lane-i64): the whole superblock searched
795/// as ONE intra block -- every mode the 32x32 search offers, one TX_64X64
796/// luma transform (`TxbSet::Luma64`, whose coded quarter is the 32x32 corner)
797/// and one TX_32X32 per chroma plane -- and compared against the four 32x32
798/// quadrants at the same lambda, exactly the shape the inter root
799/// ([`B64_ROOT`]) takes on an inter frame. The writer has always been able to
800/// code one (`crate::tile::sb_coeff_key_frame_tile`'s `Superblock::Whole`);
801/// nothing produced one, so the key frame -- 21.6% of a real film stream --
802/// coded every superblock split while libaom and rav1e leave 45-54% of theirs
803/// whole.
804///
805/// No CfL (spec `is_cfl_allowed` stops at 32x32, and `search_chroma` gates on
806/// it), no filter intra (`filter_intra_size_class` has no 64 row) and no
807/// transform-depth split (the writer's `Superblock::Whole` arm takes a 32x32
808/// level grid, so only depth 0 is representable) -- the root is refused
809/// outright on an `allow_intrabc` frame, whose quadrant searches carry DV
810/// state a discarded trial would desync.
811///
812/// Switched off by `EC_AV1_I64=0` in any build.
813pub(crate) const I64_ROOT: bool = true;
814
815/// How many key-frame superblocks were coded as one 64x64 intra block since
816/// the last [`take_i64_root_hits`], so a gate reports the fire rate rather
817/// than assuming it (class `gate-blind-to-feature`).
818/// Index 1 is how many were OFFERED the trial at all, so a gate reads a
819/// SHARE and not a bare count, and index 2 how many of the whole ones sat on
820/// a superblock the true frame edge CUTS THROUGH (lane-corner) -- the
821/// `gate-blind-to-feature` guard for the edge path, which no
822/// superblock-aligned clip fires at all.
823static I64_HITS: [std::sync::atomic::AtomicUsize; 3] =
824 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
825
826/// The key-frame `(whole, offered, edge)` 64x64-intra-root counts since the
827/// last call, and zero them.
828pub fn take_i64_root_hits() -> [usize; 3] {
829 std::array::from_fn(|i| I64_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
830}
831
832/// [`I64_ROOT`], or what `EC_AV1_I64` names.
833fn i64_root() -> bool {
834 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
835 crate::envflags::var("EC_AV1_I64").ok().map(|v| v != "0")
836 });
837 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::I64_ROOT))
838}
839
840/// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the
841/// winner's prediction through one TX_64X64 luma transform and two TX_32X32
842/// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root
843/// lane-b64 shipped, so the two can be measured against each other on the
844/// same build.
845///
846/// MEASURED on the native gate (two arms of one build, baseline reproduced to
847/// the tenth): both film rows improve on both columns -- film A
848/// +43.0/+15.0 -> +42.9/+14.8, film B +64.7/+34.0 -> +63.3/+31.5 -- and
849/// SCREEN CAPTURE loses +33.4/-23.8 -> +34.3/-23.4, outside the keep rule's
850/// +-0.3 screen clause. So the caller gates this off on a screen frame
851/// (`allow_screen_content_tools`), the same content gate the coding pyramid
852/// takes: a desktop capture's 64x64 superblocks are flat runs whose skip arm
853/// already codes them for nothing, and a residual there only spends bits the
854/// intra/palette tools would have spent better.
855///
856/// CENSUS on film B (12 frames, q120, `EC_AV1_BITCENSUS=1` +
857/// `examples/syntax_census.rs`, both streams read by OUR decoder), off vs on:
858///
859/// | | skip-only | + residual |
860/// |---|---|---|
861/// | 64x64 share, all frames | 36.4% | 38.3% |
862/// | 64x64 share, leaf frames | 53.3% | 56.0% |
863/// | skip area, all frames | 80.4% | 78.8% |
864/// | skip area, leaf frames | 90.2% | 88.5% |
865/// | stream bytes | 34,366 | 34,295 |
866/// | encoder wall | 13.4s | 9.6s |
867///
868/// `base_luma_64` enters the leaf frames' top tables at 5.7%, i.e. the
869/// TX_64X64 coefficients are really being coded. The root wins MORE often
870/// with a residual to offer (rav1e speed 6's own 64x64 share on this clip is
871/// 45.2%), which is also why the arm is 28% FASTER despite costing three more
872/// transforms per superblock: a root that wins is four quadrant searches that
873/// never run.
874fn b64_residual() -> bool {
875 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
876 crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0")
877 });
878 ENV.unwrap_or(true) && b64_root()
879}
880
881/// How many 64x64 roots came out cheaper with a residual than skipped, since
882/// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate
883/// rather than assuming one (class `gate-blind-to-feature`).
884static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
885
886/// The non-skip 64x64-root count since the last call, and zero it.
887pub fn take_b64_residual_hits() -> usize {
888 B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
889}
890
891/// Whether the 64x64 root also prices COMPOUND candidates (lane-b64b): the
892/// `LAST` + extra-reference pairs the 32x32 level already offers, at the
893/// three modes a root can form without a second 64x64 motion search --
894/// `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` (whose NEW half
895/// is the vector `search_skip_64`'s own single-reference search already
896/// found). `NEAREST_NEWMV`/`NEW_NEWMV` need the SECOND reference's own
897/// `NEWMV` vector, which only a second search per superblock produces -- the
898/// wall this root exists to save -- so they are not offered here.
899///
900/// Off by `EC_AV1_B64COMP=0`, so both arms measure on one build.
901fn b64_compound() -> bool {
902 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
903 crate::envflags::var("EC_AV1_B64COMP").ok().map(|v| v != "0")
904 });
905 ENV.unwrap_or(true) && b64_root()
906}
907
908/// How many 64x64 roots took a COMPOUND candidate since the last
909/// [`take_b64_compound_hits`] (class `gate-blind-to-feature`).
910static B64_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
911
912/// The compound 64x64-root count since the last call, and zero it.
913pub fn take_b64_compound_hits() -> usize {
914 B64_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
915}
916
917/// Whether a 64x64 root that codes a residual may SPLIT its luma transform
918/// (lane-b64b): four TX_32X32 units instead of the one TX_64X64, decided by
919/// [`commit_inter_luma`] like every other inter block's var-tx, and coded by
920/// the writer's `Whole64` arm as `txfm_split = 1`. It exists because
921/// TX_64X64 zeroes everything outside its 32x32 corner, so a root whose
922/// residual has detail in the other three quadrants cannot code it at all.
923///
924/// Off by `EC_AV1_B64VARTX=0`.
925fn b64_var_tx() -> bool {
926 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
927 crate::envflags::var("EC_AV1_B64VARTX").ok().map(|v| v != "0")
928 });
929 ENV.unwrap_or(true) && b64_root()
930}
931
932/// How many 64x64 roots split their luma transform since the last
933/// [`take_b64_var_tx_hits`].
934static B64_VAR_TX_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
935
936/// The split-luma 64x64-root count since the last call, and zero it.
937pub fn take_b64_var_tx_hits() -> usize {
938 B64_VAR_TX_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
939}
940
941/// Whether a superblock the true frame edge CUTS THROUGH may be left whole
942/// (lane-b64b). AV1 asks only that the block's own half is inside
943/// (`has_cols`/`has_rows`, spec `decode_partition`), and the writer already
944/// codes that case; what was missing was a trial whose SSE is scored over the
945/// INSIDE part alone ([`Plane::block_sse`], which clips since lane-sse)
946/// instead of over the padding the encoder
947/// invented past the edge. Both gate films are superblock-aligned, so this
948/// only reaches the user's own arbitrary export sizes.
949///
950/// Off by `EC_AV1_B64EDGE=0`.
951fn b64_edge() -> bool {
952 edge_root_enabled() && b64_root()
953}
954
955/// What `EC_AV1_B64EDGE` names on its own, without the inter root's own
956/// preset switch -- the key frame's root ([`I64_ROOT`]) reads the same flag
957/// but is gated by [`i64_root`].
958fn edge_root_enabled() -> bool {
959 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
960 crate::envflags::var("EC_AV1_B64EDGE").ok().map(|v| v != "0")
961 });
962 ENV.unwrap_or(true)
963}
964
965/// How many 64x64 roots the frame edge cut through since the last
966/// [`take_b64_edge_hits`] (class `gate-blind-to-feature`: both gate films are
967/// superblock-aligned, so nothing but a synthetic size fires this).
968static B64_EDGE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
969
970/// The edge 64x64-root count since the last call, and zero it.
971pub fn take_b64_edge_hits() -> usize {
972 B64_EDGE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
973}
974
975/// Whether the encoder searches loop restoration at all (spec 7.17): one
976/// Wiener filter per 64x64 luma restoration unit, picked from
977/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
978/// test build, like [`lambda_scale`].
979pub(crate) const RESTORATION: bool = true;
980
981/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
982fn restoration_enabled() -> bool {
983 match std::env::var("EC_AV1_LR").ok() {
984 Some(v) if cfg!(test) => v != "0",
985 _ => crate::speed::at(&crate::speed::RESTORATION),
986 }
987}
988
989/// libaom's `partition_search_breakout` shape: how many non-zero luma
990/// coefficients per 256 luma samples a block may code and still be judged
991/// well enough predicted that the split below it is not worth trying. `0`
992/// disables the breakout (only the existing all-skip prune applies), which
993/// is the default until the sweep below justifies otherwise.
994///
995/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
996/// is where this lane's wall would have gone: 1 cuts the three clips'
997/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
998/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
999/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
1000/// encoder's inter quality lives, so `0` ships and the knob stays for a
1001/// future explicit speed preset.
1002pub(crate) const SPLIT_BREAKOUT_COEFFS: usize = 0;
1003
1004/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
1005/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
1006/// out under `threshold * lambda` is not offered the split at all, and a
1007/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
1008/// always, as before this lever.
1009///
1010/// The census is what points here: the split trial runs on nearly every
1011/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
1012/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
1013/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
1014/// points, so the gate has to read the block's own RD cost, not its levels.
1015///
1016/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
1017/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
1018/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
1019/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
1020/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
1021/// the largest threshold whose BD stays inside the +0.3 keep rule on every
1022/// clip.
1023/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on (base
1024/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3): 0.0625 is +16.9/-0.4, +47.0/+19.1,
1025/// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is
1026/// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off
1027/// the screen wall). Neither clears the keep rule; 0.125 stays.
1028pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125;
1029
1030/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
1031fn split_rd_threshold() -> f64 {
1032 static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| {
1033 crate::envflags::var("EC_AV1_SPLIT_RD").ok().and_then(|v| v.parse().ok())
1034 });
1035 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD))
1036}
1037
1038/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
1039/// [`split_rd_threshold`] withholds the split trial.
1040fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
1041 split_rd_breakout_at(split_rd_threshold(), cost, side, lambda)
1042}
1043
1044/// [`split_rd_breakout`] at an explicit threshold -- what the 64x64 root's own
1045/// early-out reads.
1046fn split_rd_breakout_at(t: f64, cost: f64, side: usize, lambda: f64) -> bool {
1047 t > 0.0 && cost < t * lambda * (side * side) as f64
1048}
1049
1050/// The threshold the 64x64 root's early-out uses: [`split_rd_threshold`]
1051/// CLAMPED at the shipped [`SPLIT_RD_THRESHOLD`] (lane-tx64).
1052///
1053/// The 32x32 level is allowed to loosen its breakout with the speed preset
1054/// (`crate::speed::SPLIT_RD` steps to 0.5 at preset 6), but lane-b64 measured
1055/// what that does one size up: at 0.5 a whole superblock is taken at 64x64
1056/// without its four quadrants ever being searched, and film B goes
1057/// +91.5/+53.4 -> +114.6/+71.5. A 64x64 block is four times the area, so the
1058/// same per-pixel threshold withholds four times as much search -- the
1059/// preset's step is priced for the 32 level and does not carry up here.
1060fn b64_breakout_threshold() -> f64 {
1061 split_rd_threshold().min(SPLIT_RD_THRESHOLD)
1062}
1063
1064/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
1065/// build.
1066fn split_breakout_coeffs() -> usize {
1067 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
1068 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
1069 _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT),
1070 }
1071}
1072
1073/// How often each partition decision was taken since the last
1074/// [`take_partition_hits`], so a gate can report how often a new partition
1075/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
1076/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
1077/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
1078static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
1079 std::sync::atomic::AtomicUsize::new(0),
1080 std::sync::atomic::AtomicUsize::new(0),
1081 std::sync::atomic::AtomicUsize::new(0),
1082 std::sync::atomic::AtomicUsize::new(0),
1083];
1084
1085/// Records one such decision.
1086fn partition_hit(which: usize) {
1087 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1088}
1089
1090/// Takes (and clears) the counts.
1091#[cfg(test)]
1092pub(crate) fn take_partition_hits() -> [usize; 4] {
1093 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1094}
1095
1096/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
1097/// rate-distortion trials the block search actually runs, by kind, and where
1098/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
1099/// default, and a measurement build rather than a speed one -- the census
1100/// runs the SAD pre-pass the unpruned search otherwise skips.
1101pub fn census_on() -> bool {
1102 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1103 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
1104}
1105
1106/// What each [`CENSUS`] counter counts.
1107pub const CENSUS_KINDS: [&str; 11] = [
1108 "intra blocks searched (key frame + inter leaves)",
1109 "intra luma mode trials",
1110 "chroma searches",
1111 "chroma mode trials (each = 2 plane trials)",
1112 "tx-depth trials (transform units, depth >= 1)",
1113 "inter 32x32 blocks searched",
1114 "inter block intra-mode trials",
1115 "inter mv candidates (each = 3 mc trials)",
1116 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
1117 " of those, intra won",
1118 " of those, the NEARESTMV trial coded no residual",
1119];
1120
1121/// The census counters themselves, indexed by [`CENSUS_KINDS`].
1122static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
1123 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
1124
1125/// Where the RD winner sat in the SAD ranking, for the luma intra search and
1126/// the chroma mode search -- what says whether a top-N prune would have kept
1127/// the block the search actually chose.
1128static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
1129 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
1130static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
1131 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1132
1133fn census_add(kind: usize, n: usize) {
1134 if census_on() {
1135 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
1136 }
1137}
1138
1139/// Reads (and clears) the census, so a driver can attribute it to its own encode.
1140pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
1141 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
1142 (
1143 std::array::from_fn(|i| take(&CENSUS[i])),
1144 std::array::from_fn(|i| take(&LUMA_RANK[i])),
1145 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
1146 )
1147}
1148
1149/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
1150/// first -- the census's one shared rule, so the luma and chroma histograms
1151/// mean the same thing.
1152fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
1153 scored
1154 .iter()
1155 .filter(|&&(score, mode)| {
1156 mode != winner
1157 && score
1158 < scored
1159 .iter()
1160 .find(|&&(_, m)| m == winner)
1161 .map_or(f64::INFINITY, |&(s, _)| s)
1162 })
1163 .count()
1164}
1165
1166/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
1167/// four cost less. Set from the measurement in the lane report.
1168const SPLIT_BLOCKS: bool = true;
1169
1170/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
1171/// by calling [`encode_key_frame_inner`] both ways.
1172pub(crate) fn split_blocks() -> bool {
1173 SPLIT_BLOCKS
1174}
1175
1176/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
1177/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
1178/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
1179/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
1180/// stream's decode output actually carries 10-bit precision instead of
1181/// silently losing its low 2 bits). The encoder only ever produces values in
1182/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
1183/// decision); `Plane::source` narrows right back to `u8` at its two
1184/// construction sites, a lossless round trip for that range.
1185#[derive(Clone, Debug, PartialEq, Eq)]
1186pub struct Picture {
1187 /// The picture's width in luma samples.
1188 pub width: usize,
1189 /// Its height in luma samples.
1190 pub height: usize,
1191 /// The luma plane, `width * height` samples in raster order.
1192 pub y: Vec<u16>,
1193 /// The U plane, at half the width and half the height.
1194 pub u: Vec<u16>,
1195 /// The V plane, the same shape as U.
1196 pub v: Vec<u16>,
1197}
1198
1199impl Picture {
1200 /// A mid-grey picture of the given size.
1201 #[must_use]
1202 pub fn grey(width: usize, height: usize) -> Self {
1203 Self {
1204 width,
1205 height,
1206 y: vec![128; width * height],
1207 u: vec![128; width * height / 4],
1208 v: vec![128; width * height / 4],
1209 }
1210 }
1211
1212 pub(crate) fn check(&self) -> Result<()> {
1213 if self.width == 0
1214 || !self.width.is_multiple_of(BLOCK)
1215 || !self.height.is_multiple_of(BLOCK)
1216 || !self.height.is_multiple_of(BLOCK)
1217 {
1218 return Err(Error::unsupported(
1219 "AV1 encode",
1220 "the picture must be a whole number of 32x32 blocks in each direction",
1221 ));
1222 }
1223 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1224 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1225 return Err(Error::unsupported(
1226 "AV1 encode",
1227 "each plane must carry one sample per position at 4:2:0",
1228 ));
1229 }
1230 Ok(())
1231 }
1232
1233 /// What the public entry points require of the picture they are handed,
1234 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
1235 /// needs a whole chroma sample per two luma ones) and one sample per
1236 /// position on each plane.
1237 pub(crate) fn check_even(&self) -> Result<()> {
1238 if self.width == 0
1239 || self.height == 0
1240 || !self.width.is_multiple_of(2)
1241 || !self.height.is_multiple_of(2)
1242 {
1243 return Err(Error::unsupported(
1244 "AV1 encode",
1245 "the picture's width and height must each be even and nonzero",
1246 ));
1247 }
1248 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1249 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1250 return Err(Error::unsupported(
1251 "AV1 encode",
1252 "each plane must carry one sample per position at 4:2:0",
1253 ));
1254 }
1255 Ok(())
1256 }
1257
1258 /// This picture, padded by edge replication to the next whole number of
1259 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
1260 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
1261 /// sequence (what the inter tile writer's partition needs on top of
1262 /// that). Identity (a plain clone, not a copy through the replication
1263 /// loop) when the picture is already that size — the multiple-of-32 (or
1264 /// -64) fast path is unchanged.
1265 pub(crate) fn padded_to(&self, align: usize) -> Picture {
1266 let padded_width = self.width.next_multiple_of(align);
1267 let padded_height = self.height.next_multiple_of(align);
1268 if padded_width == self.width && padded_height == self.height {
1269 return self.clone();
1270 }
1271 Picture {
1272 width: padded_width,
1273 height: padded_height,
1274 y: pad_plane(
1275 &self.y,
1276 self.width,
1277 self.height,
1278 padded_width,
1279 padded_height,
1280 ),
1281 u: pad_plane(
1282 &self.u,
1283 self.width / 2,
1284 self.height / 2,
1285 padded_width / 2,
1286 padded_height / 2,
1287 ),
1288 v: pad_plane(
1289 &self.v,
1290 self.width / 2,
1291 self.height / 2,
1292 padded_width / 2,
1293 padded_height / 2,
1294 ),
1295 }
1296 }
1297}
1298
1299/// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8`
1300/// (8-bit only, unchanged this round -- widening the encoder is out of this
1301/// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that
1302/// lets it keep calling [`crate::intra::predict`] now that shape is `u16`
1303/// in and out. A block-sized round-trip through `u16` is exact for 8-bit
1304/// content (every value fits both ways), so this changes no encoder output.
1305#[allow(clippy::too_many_arguments)]
1306fn intra_predict_u8(
1307 mode: u8,
1308 angle_delta: i32,
1309 above: Option<&[u8]>,
1310 left: Option<&[u8]>,
1311 corner: Option<u8>,
1312 bw: usize,
1313 bh: usize,
1314 enable_edge_filter: bool,
1315 smooth_neighbor: bool,
1316 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
1317) {
1318 // Three heap allocations per call became three stack buffers: this runs
1319 // once per mode per trial, and an edge is at most `bw + bh` samples while
1320 // a block is at most `SUPERBLOCK * SUPERBLOCK` (lane-i64: the key frame's
1321 // 64x64 intra root predicts through here too, and reads up to `2 * bw`
1322 // samples above).
1323 let mut above_buf = [0u16; 2 * SUPERBLOCK];
1324 let mut left_buf = [0u16; 2 * SUPERBLOCK];
1325 // lane-av1speed2: a `BLOCK * BLOCK` scratch is 2 KB zeroed on every mode
1326 // trial of every block, and a 4x4 block writes 32 bytes of it. The
1327 // predictor fills every sample it is handed, so the zeros are dead
1328 // either way -- size the scratch to the block instead of to the largest
1329 // block there is.
1330
1331 let widen = |src: &[u8], buf: &mut [u16; 2 * SUPERBLOCK]| {
1332 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1333 *d = u16::from(v);
1334 }
1335 };
1336 if let Some(s) = above {
1337 widen(s, &mut above_buf);
1338 }
1339 if let Some(s) = left {
1340 widen(s, &mut left_buf);
1341 }
1342 let above16 = above.map(|s| &above_buf[..s.len()]);
1343 let left16 = left.map(|s| &left_buf[..s.len()]);
1344 let mut run = |dst16: &mut [u16]| {
1345 crate::intra::predict(
1346 mode,
1347 angle_delta,
1348 above16,
1349 left16,
1350 corner.map(u16::from),
1351 bw,
1352 bh,
1353 enable_edge_filter,
1354 smooth_neighbor,
1355 dst16, fctx,
1356 );
1357 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
1358 *d = s as u8;
1359 }
1360 };
1361 let n = bw * bh;
1362 if n <= 64 {
1363 run(&mut [0u16; 64][..n]);
1364 } else if n <= 256 {
1365 run(&mut [0u16; 256][..n]);
1366 } else if n <= BLOCK * BLOCK {
1367 run(&mut [0u16; BLOCK * BLOCK][..n]);
1368 } else {
1369 run(&mut [0u16; SUPERBLOCK * SUPERBLOCK][..n]);
1370 }
1371}
1372
1373/// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same
1374/// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one
1375/// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode.
1376fn filter_intra_predict_u8(
1377 mode: usize,
1378 above: Option<&[u8]>,
1379 left: Option<&[u8]>,
1380 corner: Option<u8>,
1381 side: usize,
1382 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
1383) {
1384 let mut above_buf = [0u16; 2 * BLOCK];
1385 let mut left_buf = [0u16; 2 * BLOCK];
1386 let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
1387 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1388 *d = u16::from(v);
1389 }
1390 };
1391 if let Some(a) = above {
1392 widen(a, &mut above_buf);
1393 }
1394 if let Some(l) = left {
1395 widen(l, &mut left_buf);
1396 }
1397 let mut dst16 = [0u16; BLOCK * BLOCK];
1398 let n = side * side;
1399 crate::intra::predict_filter_intra(
1400 mode,
1401 above.map(|a| &above_buf[..a.len()]),
1402 left.map(|l| &left_buf[..l.len()]),
1403 corner.map(u16::from),
1404 side,
1405 side,
1406 &mut dst16[..n], fctx,
1407 );
1408 for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) {
1409 *d = v as u8;
1410 }
1411}
1412
1413/// Pads one plane to `(padded_width, padded_height)` by repeating its last
1414/// row and column, so the block coder always sees a whole number of blocks.
1415/// [`crop_plane`] undoes this on the way back out.
1416fn pad_plane<T: Copy + Default>(
1417 source: &[T],
1418 width: usize,
1419 height: usize,
1420 padded_width: usize,
1421 padded_height: usize,
1422) -> Vec<T> {
1423 let mut out = vec![T::default(); padded_width * padded_height];
1424 for row in 0..padded_height {
1425 let src = source[row.min(height - 1) * width..][..width].as_ref();
1426 let dst = &mut out[row * padded_width..][..padded_width];
1427 dst[..width].copy_from_slice(src);
1428 dst[width..].fill(src[width - 1]);
1429 }
1430 out
1431}
1432
1433/// The top-left `width` x `height` region of a plane that is `padded_width`
1434/// wide, which is the render-size crop [`Picture::padded`]'s replication
1435/// exists to let a decoder undo.
1436fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
1437 let mut out = Vec::with_capacity(width * height);
1438 for row in 0..height {
1439 out.extend_from_slice(&source[row * padded_width..][..width]);
1440 }
1441 out
1442}
1443
1444/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
1445/// region a decoder produces, which is the public contract for what a caller
1446/// sees back — the padded planes the encoder coded against never leave this
1447/// module. Identity when the reconstruction is already that size.
1448pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
1449 let reconstruction = &encoded.reconstruction;
1450 let cropped = if reconstruction.width == width && reconstruction.height == height {
1451 reconstruction.clone()
1452 } else {
1453 Picture {
1454 width,
1455 height,
1456 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
1457 u: crop_plane(
1458 &reconstruction.u,
1459 reconstruction.width / 2,
1460 width / 2,
1461 height / 2,
1462 ),
1463 v: crop_plane(
1464 &reconstruction.v,
1465 reconstruction.width / 2,
1466 width / 2,
1467 height / 2,
1468 ),
1469 }
1470 };
1471 Encoded {
1472 stream: encoded.stream.clone(),
1473 modes: encoded.modes.clone(),
1474 inter_block_share: encoded.inter_block_share,
1475 reconstruction: cropped,
1476 tile: encoded.tile.clone(),
1477 mi_cols: encoded.mi_cols,
1478 mi_rows: encoded.mi_rows,
1479 base_q_idx: encoded.base_q_idx,
1480 tx_select: encoded.tx_select,
1481 switchable_motion_mode: encoded.switchable_motion_mode,
1482 screen: encoded.screen,
1483 start_cdfs: encoded.start_cdfs.clone(),
1484 next_cdfs: encoded.next_cdfs.clone(),
1485 loop_filter: encoded.loop_filter,
1486 loop_restoration: encoded.loop_restoration,
1487 allow_intrabc: encoded.allow_intrabc,
1488 delta: encoded.delta.clone(),
1489 cdef: encoded.cdef,
1490 }
1491}
1492
1493/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
1494/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
1495#[derive(Clone)]
1496pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
1497
1498impl std::fmt::Debug for CdfSnapshot {
1499 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1500 f.write_str("CdfSnapshot")
1501 }
1502}
1503
1504/// What one call to [`encode_key_frame`] produced.
1505#[derive(Clone, Debug)]
1506pub struct Encoded {
1507 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
1508 /// OBU carrying one tile.
1509 pub stream: Vec<u8>,
1510 /// What a decoder will produce from `stream` — the encoder's own
1511 /// reconstruction, which its prediction was built on.
1512 pub reconstruction: Picture,
1513 /// The luma intra mode each block was coded under, in the order the blocks
1514 /// are coded — raster order among the quadrants of each superblock, and
1515 /// among the four 16x16 blocks of a quadrant that was split.
1516 pub modes: Vec<u8>,
1517 /// The fraction of this frame's 32x32 blocks that were coded inter (any
1518 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
1519 /// for a key frame, which has no such choice — so a caller can tell a
1520 /// frame with no motion worth coding from one that never got the chance.
1521 pub inter_block_share: f64,
1522 /// The tile payload alone, undecorated by any OBU framing, and the frame
1523 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
1524 /// `crate::decode`'s tests are the only reader; a real decoder gets these
1525 /// off the wire by parsing `stream`'s OBUs instead.
1526 pub(crate) tile: Vec<u8>,
1527 pub(crate) mi_cols: u32,
1528 pub(crate) mi_rows: u32,
1529 pub(crate) base_q_idx: u8,
1530 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
1531 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
1532 /// and reading it off `stream`'s header is what `decode_stream` does. A
1533 /// test that decodes `tile` directly must pass this one along, or it reads
1534 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
1535 /// block.
1536 pub(crate) tx_select: bool,
1537 /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the
1538 /// bit that makes every eligible single-reference inter block carry a
1539 /// `motion_mode` symbol. Same contract as `tx_select` above: a test
1540 /// decoding `tile` directly must pass it along or it desyncs at the
1541 /// first eligible block.
1542 pub(crate) switchable_motion_mode: bool,
1543 /// The CDF state this frame's tile writer started from -- the defaults
1544 /// for a key frame and for the first inter frame, and the previous
1545 /// frame's stored tables after that. A test that decodes `tile` directly
1546 /// must feed the decoder this, exactly as `decode_stream` feeds it what
1547 /// the frame's `primary_ref_frame` slot holds (same class as
1548 /// `tx_select`: a header bit a raw tile decode cannot guess).
1549 pub(crate) start_cdfs: CdfSnapshot,
1550 /// What this frame stores into the slots it refreshes (spec 7.20,
1551 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
1552 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
1553 /// started from when it is on.
1554 pub(crate) next_cdfs: CdfSnapshot,
1555 /// This frame header's chosen deblocking parameters
1556 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
1557 /// picture the decoder produces UNDER them, so a test that decodes
1558 /// `tile` directly must pass these along, exactly as it must `tx_select`
1559 /// (class: test asserts against a stale header).
1560 pub(crate) loop_filter: LoopFilterParams,
1561 /// This frame header's chosen CDEF parameters, threaded for the same
1562 /// reason as `loop_filter`.
1563 pub(crate) cdef: CdefParams,
1564 /// This frame header's `allow_screen_content_tools`
1565 /// ([`screen_content`]) -- every intra block of the tile carries the two
1566 /// palette-mode symbols under it, so a raw tile decode that guessed
1567 /// `false` would desync at the first block (same class as `tx_select`).
1568 pub(crate) screen: bool,
1569 /// This frame header's chosen loop restoration parameters, threaded for
1570 /// the same reason as `loop_filter` -- and doubly so: the per-unit
1571 /// filters themselves are coded in `tile`, so a decode of it under a
1572 /// stale `RESTORE_NONE` header desyncs at the first superblock.
1573 pub(crate) loop_restoration: LoopRestorationParams,
1574 /// This frame header's `allow_intrabc` -- every intra block of the tile
1575 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
1576 /// guessed `false` would desync at the first block (same class as
1577 /// `screen`/`tx_select`).
1578 pub(crate) allow_intrabc: bool,
1579 /// This frame header's `delta_q_params`/`delta_lf_params` (spec
1580 /// 5.9.17/5.9.18) -- with `delta_q_present` every superblock's first
1581 /// coded block carries a `delta_qindex` symbol group, so a raw tile
1582 /// decode that guessed the defaults desyncs at the first superblock
1583 /// (same class as `screen`/`tx_select`).
1584 pub(crate) delta: ec_av1_syntax::DeltaParams,
1585}
1586
1587thread_local! {
1588 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
1589 /// for on the last key frame encoded on this thread -- read by the gates,
1590 /// which print it beside the block counts (class `gate-blind-to-feature`).
1591 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
1592}
1593
1594/// [`IBC_SHARE`] for the last key frame encoded on this thread.
1595#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1596pub(crate) fn intrabc_source_share() -> f64 {
1597 IBC_SHARE.with(std::cell::Cell::get)
1598}
1599
1600thread_local! {
1601 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
1602 /// header offers the per-frame `allow_screen_content_tools` bit at all.
1603 /// Armed once by the key frame ([`encode_key_frame_inner`], from
1604 /// [`screen_content`]) and read by every header builder after it, so that
1605 /// the inter frames of a screen sequence lay their headers out the same
1606 /// way the sequence header the key frame wrote says they do -- a per-call
1607 /// parameter would have to thread through `inter_frame_headers`' four
1608 /// public entry points and every hand-built-stream test that calls them.
1609 /// A sequence with no screen content leaves this false and writes exactly
1610 /// the bits it wrote before this lane.
1611 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1612}
1613
1614thread_local! {
1615 /// Overrides [`screen_content`] for the calling thread, which is what the
1616 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
1617 /// codes every block losslessly, so both arms of a mode ablation reach
1618 /// infinite PSNR and the ablation measures nothing at all (the
1619 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
1620 /// variable cannot do this -- the tests run in one process, in parallel.
1621 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1622}
1623
1624thread_local! {
1625 /// What the last [`encode_sequence_with_ctx`] call on this thread coded
1626 /// under, AFTER the content gate: the pyramid, or `None` for a stream
1627 /// that stayed flat. Read by the BD gates, which print the requested and
1628 /// the effective pyramid side by side -- a screen clip requests one and
1629 /// codes flat, and that difference is the gate (class
1630 /// `gate-blind-to-feature`).
1631 static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> =
1632 const { std::cell::Cell::new(None) };
1633}
1634
1635/// The pyramid the last sequence coded on this thread was EFFECTIVELY under.
1636#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1637pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> {
1638 LAST_SEQ_PYRAMID.with(std::cell::Cell::get)
1639}
1640
1641#[cfg(test)]
1642pub(crate) fn force_screen(value: Option<bool>) {
1643 SCREEN_FORCE.with(|c| c.set(value));
1644}
1645
1646// lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE
1647// ablation can measure the mode search alone. Setting it also clears the
1648// sequence header's own `enable_filter_intra` bit, so the stream the arm
1649// writes is exactly the one this encoder wrote before the lane.
1650#[cfg(test)]
1651thread_local! {
1652 static FILTER_INTRA_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1653}
1654
1655#[cfg(test)]
1656pub(crate) fn force_filter_intra(value: Option<bool>) {
1657 FILTER_INTRA_FORCE.with(|c| c.set(value));
1658}
1659
1660pub(crate) fn arm_seq_screen(on: bool) {
1661 SEQ_SCREEN.with(|c| c.set(on));
1662}
1663
1664fn seq_screen() -> bool {
1665 SEQ_SCREEN.with(std::cell::Cell::get)
1666}
1667
1668/// How many distinct colours a 16x16 luma block may hold and still count as
1669/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
1670/// `av1_set_screen_content_options` bound is 4, which separates nothing on
1671/// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against
1672/// the variance floor below on the five gate clips at BOTH the native crop
1673/// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of
1674/// the frame is the widest-margin split of those ten rows -- every
1675/// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5
1676/// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6%
1677/// native and 17.9% scaled.
1678fn screen_colors() -> usize {
1679 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1680 *N.get_or_init(|| {
1681 std::env::var("EC_AV1_SCREEN_COLORS")
1682 .ok()
1683 .and_then(|v| v.parse().ok())
1684 .unwrap_or(16)
1685 })
1686}
1687
1688/// The reciprocal of the frame area those blocks must cover, in tenths --
1689/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth;
1690/// 8 (an eighth) is the midpoint of the two populations
1691/// `probe_screen_detect` measures at the colour bound and variance floor
1692/// around it. `EC_AV1_SCREEN_PCT`.
1693fn screen_pct() -> usize {
1694 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
1695 *N.get_or_init(|| {
1696 std::env::var("EC_AV1_SCREEN_PCT")
1697 .ok()
1698 .and_then(|v| v.parse().ok())
1699 .unwrap_or(10)
1700 })
1701}
1702
1703/// The per-pixel variance a few-colour block must clear before it counts as
1704/// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its
1705/// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it
1706/// a smooth dark film frame is all few-colour blocks and reads as a desktop
1707/// capture -- which is exactly what this detector did until 2026-09-07, when
1708/// it called BOTH real films screen content on 48/48 frames, priced every
1709/// coefficient against the default CDFs and ran the palette search over
1710/// film. `probe_screen_detect`: at 16 colours the floor takes both films
1711/// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to
1712/// 23.6%.
1713fn screen_var() -> u64 {
1714 static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
1715 *N.get_or_init(|| {
1716 std::env::var("EC_AV1_SCREEN_VAR")
1717 .ok()
1718 .and_then(|v| v.parse().ok())
1719 .unwrap_or(16)
1720 })
1721}
1722
1723/// How many frames [`screen_content`] said yes/no to, so a gate can print
1724/// whether the detector fired at all (class `gate-blind-to-feature`).
1725pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
1726 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
1727
1728/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
1729/// the distinct colours of every 16x16 block and turn the screen-content
1730/// tools on when the blocks holding between 2 and [`screen_colors`] of them
1731/// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the
1732/// frame. `width` is the plane's
1733/// stride, `true_*` the frame's real (decodable) extent.
1734fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
1735 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
1736 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1737 return forced;
1738 }
1739 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
1740 let on = v != "0";
1741 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1742 return on;
1743 }
1744 let (blk, limit, floor) = (16usize, screen_colors(), screen_var());
1745 let mut counted = 0usize;
1746 for by in (0..true_height).step_by(blk) {
1747 for bx in (0..true_width).step_by(blk) {
1748 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
1749 let mut seen = [false; 256];
1750 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
1751 for row in 0..h {
1752 for col in 0..w {
1753 let v = y[(by + row) * width + bx + col];
1754 sum += u64::from(v);
1755 sq += u64::from(v) * u64::from(v);
1756 if !seen[usize::from(v)] {
1757 seen[usize::from(v)] = true;
1758 colors += 1;
1759 }
1760 }
1761 }
1762 // Per-pixel variance over the block's real (edge-clipped) extent.
1763 let n = (h * w) as u64;
1764 let var = (sq - sum * sum / n) / n;
1765 if colors > 1 && colors <= limit && var > floor {
1766 counted += 1;
1767 }
1768 }
1769 }
1770 let on = counted * blk * blk * screen_pct() > true_width * true_height;
1771 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1772 on
1773}
1774
1775/// Whether this SOURCE picture reads as screen content, for a caller that has
1776/// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`]
1777/// gates its coding pyramid on this (a desktop capture keeps the flat
1778/// one-in-one-out structure the BD gate measured it on, camera material takes
1779/// the mini-GOP). The key frame runs the same detector again when it builds
1780/// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to
1781/// count, so this probe undoes its own tick and leaves the gate prints
1782/// reading one detection per coded frame.
1783pub(crate) fn picture_is_screen(picture: &Picture) -> bool {
1784 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
1785 let on = screen_content(&y, picture.width, picture.width, picture.height);
1786 SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
1787 on
1788}
1789
1790/// The sequence and frame headers a picture of this size is coded under: one
1791/// tile, one transform size per block, no in-loop filter parameters yet
1792/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
1793/// CDEF strengths in once the tile is coded), no CDF adaptation
1794/// and no tool the tile writer does not code.
1795///
1796/// # Errors
1797/// Returns an error when the picture is larger than the 16-bit frame size the
1798/// sequence header carries.
1799pub fn key_frame_headers(
1800 width: usize,
1801 height: usize,
1802 base_q_idx: u8,
1803) -> Result<(SequenceHeader, FrameHeader)> {
1804 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
1805}
1806
1807/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
1808/// studio (limited) range: what this crate's sequence header carried before
1809/// [`crate::encoder`]'s facade could configure it, and what
1810/// [`key_frame_headers`] still asks for.
1811fn unspecified_color_config() -> ColorConfig {
1812 ColorConfig {
1813 bit_depth: 8,
1814 mono_chrome: false,
1815 num_planes: 3,
1816 color_primaries: 2,
1817 transfer_characteristics: 2,
1818 matrix_coefficients: 2,
1819 color_range: false,
1820 subsampling_x: 1,
1821 subsampling_y: 1,
1822 chroma_sample_position: ChromaSamplePosition::Unknown,
1823 separate_uv_delta_q: false,
1824 }
1825}
1826
1827/// [`key_frame_headers`] with the sequence header's colour config named
1828/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
1829/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
1830/// which is all a player picks a colour transform from and which
1831/// [`crate::encoder::Colour`] is the facade's own name for.
1832///
1833/// # Errors
1834/// The same as [`key_frame_headers`].
1835pub(crate) fn key_frame_headers_colour(
1836 width: usize,
1837 height: usize,
1838 base_q_idx: u8,
1839 color_config: ColorConfig,
1840) -> Result<(SequenceHeader, FrameHeader)> {
1841 let bits = |n: usize| -> Result<u32> {
1842 let n = u32::try_from(n).map_err(|_| too_large())?;
1843 if n == 0 || n > 1 << 16 {
1844 return Err(too_large());
1845 }
1846 Ok((32 - (n - 1).leading_zeros()).max(1))
1847 };
1848 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
1849 let (w, h) = (width as u32, height as u32);
1850 let seq = SequenceHeader {
1851 seq_profile: 0,
1852 operating_points: vec![OperatingPoint {
1853 seq_level_idx: 8,
1854 ..OperatingPoint::default()
1855 }],
1856 frame_width_bits,
1857 frame_height_bits,
1858 max_frame_width: w,
1859 max_frame_height: h,
1860 use_128x128_superblock: sb128_on(),
1861 // lane-fintra: the encoder's intra search offers the five recursive
1862 // filter-intra modes on eligible blocks, so the sequence bit is set
1863 // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both
1864 // off and restores the streams this encoder wrote before the lane).
1865 enable_filter_intra: filter_intra_on(),
1866 enable_intra_edge_filter: false,
1867 enable_order_hint: true,
1868 order_hint_bits: 7,
1869 enable_superres: false,
1870 // spec 5.9.19: with the sequence bit set every frame header carries
1871 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
1872 // pair for the whole frame, chosen by `crate::filter_search` -- so no
1873 // `cdef_idx` literal is coded in the tile and a frame that wants no
1874 // CDEF simply carries zero strengths.
1875 enable_cdef: true,
1876 enable_restoration: true,
1877 // SELECT (2) when this sequence's key frame detected screen content
1878 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
1879 // is then coded in every frame header, and only the frames that want
1880 // the palette syntax set it. 0 -- the forced-off form, no bit at all
1881 // -- otherwise, which is what every non-screen stream this encoder
1882 // writes still carries.
1883 seq_force_screen_content_tools: if seq_screen() {
1884 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
1885 } else {
1886 0
1887 },
1888 seq_force_integer_mv: 0,
1889 color_config,
1890 still_picture: false,
1891 reduced_still_picture_header: false,
1892 timing_info: None,
1893 decoder_model_info: None,
1894 initial_display_delay_present_flag: false,
1895 operating_point: 0,
1896 operating_point_idc: 0,
1897 frame_id_numbers_present_flag: false,
1898 delta_frame_id_length: 0,
1899 additional_frame_id_length: 0,
1900 enable_interintra_compound: false,
1901 enable_masked_compound: false,
1902 // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
1903 // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
1904 // header is byte-identical to the streams before this lane.
1905 enable_warped_motion: warp_on(),
1906 enable_dual_filter: false,
1907 enable_jnt_comp: false,
1908 enable_ref_frame_mvs: false,
1909 film_grain_params_present: false,
1910 };
1911 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
1912 // own (true, unpadded) width and height, not from any block-grid
1913 // alignment — a decoder derives these straight from `frame_width`/
1914 // `frame_height` below, so this must match it exactly.
1915 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
1916 let header = FrameHeader {
1917 frame_type: FrameType::Key,
1918 frame_is_intra: true,
1919 show_frame: true,
1920 error_resilient_mode: true,
1921 // The tile writer keeps the same CDF state the decoder does and
1922 // updates it in the same order, so the frame lets the decoder adapt.
1923 disable_cdf_update: false,
1924 // Nothing reads the state this frame leaves behind: a key frame always
1925 // starts from the defaults, and this encoder emits one frame.
1926 disable_frame_end_update_cdf: true,
1927 force_integer_mv: true,
1928 refresh_frame_flags: 0xFF,
1929 primary_ref_frame: PRIMARY_REF_NONE,
1930 frame_width: w,
1931 frame_height: h,
1932 upscaled_width: w,
1933 render_width: w,
1934 render_height: h,
1935 mi_cols,
1936 mi_rows,
1937 tile_info: TileInfo {
1938 uniform_spacing: true,
1939 cols: 1,
1940 rows: 1,
1941 mi_col_starts: vec![0, mi_cols],
1942 mi_row_starts: vec![0, mi_rows],
1943 tile_size_bytes: 1,
1944 ..TileInfo::default()
1945 },
1946 quantization: QuantizationParams {
1947 base_q_idx,
1948 ..QuantizationParams::default()
1949 },
1950 tx_mode: TxMode::Largest,
1951 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
1952 // intra transform below 32x32, not only 16x16 -- the set this crate
1953 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
1954 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
1955 // so a decoder honouring the header picks the same CDF the writer
1956 // used only if this is set here too, not only on the inter variant
1957 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
1958 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
1959 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
1960 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
1961 // the arithmetic coder's `rng` register from the very first 8x8-leaf
1962 // luma transform onward with no symbol value ever differing.
1963 reduced_tx_set: true,
1964 ..FrameHeader::default()
1965 };
1966 Ok((seq, header))
1967}
1968
1969/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
1970/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
1971/// 1 still holds the key frame however long the GOP runs.
1972pub const GOLDEN_SLOT: u8 = 1;
1973
1974/// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every inter
1975/// frame this encoder writes carries. `EC_AV1_INTERP=smooth|sharp` codes the
1976/// EIGHTTAP_SMOOTH / EIGHTTAP_SHARP kernel instead of the default REGULAR --
1977/// one filter for the whole frame, which is what libaom does on this content
1978/// too (`lanes/obmc3.report.md` read `switchable_interp 0/0` out of its own
1979/// stream, so a per-BLOCK filter search has no bits to win). The kernel
1980/// reaches the search, the trials and the recon through
1981/// `FrameCtx::interp_filter`, so the stream a decoder reads and the
1982/// prediction the search priced are the same one.
1983/// A PROCESS-GLOBAL [`frame_interp_filter`] override that wins over the
1984/// environment (`u8::MAX` = unset), the shape [`set_inter_tx_search`] has:
1985/// the witness that has to see a non-REGULAR kernel coded and decoded turns
1986/// it on through this while holding [`crate::speed::knob_write`].
1987static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 =
1988 std::sync::atomic::AtomicU8::new(u8::MAX);
1989
1990/// Sets [`INTERP_OVERRIDE`]; `None` clears it.
1991#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
1992pub(crate) fn set_frame_interp(filter: Option<ec_av1_syntax::InterpolationFilter>) {
1993 INTERP_OVERRIDE.store(
1994 filter.map_or(u8::MAX, |f| f as u8),
1995 std::sync::atomic::Ordering::Relaxed,
1996 );
1997}
1998
1999fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter {
2000 use ec_av1_syntax::InterpolationFilter as F;
2001 match INTERP_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
2002 0 => return F::Eighttap,
2003 1 => return F::EighttapSmooth,
2004 2 => return F::EighttapSharp,
2005 _ => {}
2006 }
2007 static ENV: std::sync::LazyLock<Option<F>> = std::sync::LazyLock::new(|| {
2008 crate::envflags::var("EC_AV1_INTERP").ok().map(|v| match v.as_str() {
2009 "smooth" => F::EighttapSmooth,
2010 "sharp" => F::EighttapSharp,
2011 _ => F::Eighttap,
2012 })
2013 });
2014 ENV.unwrap_or(F::Eighttap)
2015}
2016
2017/// The frame header for a shown inter frame that predicts from the single
2018/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
2019/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
2020/// reused verbatim: an inter frame never changes the sequence.
2021///
2022/// # Errors
2023/// Returns an error under the same conditions as [`key_frame_headers`].
2024pub fn inter_frame_headers(
2025 width: usize,
2026 height: usize,
2027 base_q_idx: u8,
2028 order_hint: u32,
2029 last_slot: u8,
2030) -> Result<(SequenceHeader, FrameHeader)> {
2031 inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
2032}
2033
2034/// [`inter_frame_headers`] with the three slots named apart: the one read as
2035/// `LAST_FRAME`, the one this frame refreshes, and the one read as
2036/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
2037/// so that the frame two back is still intact in the slot this one is about
2038/// to overwrite -- read before write, spec 7.20's decode order.
2039///
2040/// # Errors
2041/// As [`inter_frame_headers`].
2042pub fn inter_frame_headers_slots(
2043 width: usize,
2044 height: usize,
2045 base_q_idx: u8,
2046 order_hint: u32,
2047 last_slot: u8,
2048 self_slot: u8,
2049 altref_slot: u8,
2050) -> Result<(SequenceHeader, FrameHeader)> {
2051 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
2052 let header = FrameHeader {
2053 frame_type: FrameType::Inter,
2054 frame_is_intra: false,
2055 show_frame: true,
2056 error_resilient_mode: false,
2057 disable_cdf_update: false,
2058 // The tile writer hands its end-of-tile tables to the next frame
2059 // (`encode_sequence_with_ctx`), so the frame stores them the way the
2060 // decoder will load them (spec 7.20).
2061 disable_frame_end_update_cdf: false,
2062 force_integer_mv: false,
2063 order_hint,
2064 primary_ref_frame: 0,
2065 refresh_frame_flags: 1 << self_slot,
2066 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
2067 // names the slot this frame both predicts from and refreshes;
2068 // GOLDEN names slot 1, which the key frame wrote when it refreshed
2069 // all eight and which no inter frame ever overwrites, so it holds
2070 // the key frame's own picture for the whole GOP.
2071 ref_frame_idx: {
2072 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
2073 idx[3] = GOLDEN_SLOT;
2074 idx[6] = altref_slot;
2075 idx
2076 },
2077 allow_high_precision_mv: false,
2078 // A FIXED frame-level filter, so no block codes an `interp_filter`
2079 // symbol. lane-obmc3 instrumented whether that costs anything: a
2080 // libaom `cpu-used 6` crf 41 stream of the long-GOP film B window
2081 // (45941 B, the same point `lanes/libcen.report.md` matched) read
2082 // back through `EC_AV1_BITCENSUS=1 syntax_census` codes
2083 // `switchable_interp 0/0` in EVERY frame -- libaom picks a fixed
2084 // frame filter here too, so there are ZERO per-block filter bits at
2085 // stake on this content and the per-block switchable search was not
2086 // built (the charter's premise that libaom codes switchable interp
2087 // per block on film B is refuted by its own stream).
2088 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
2089 // lane-av1obmc: with this bit set every single-reference inter block
2090 // libaom's `motion_mode_allowed` accepts carries a `motion_mode`
2091 // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion`
2092 // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied
2093 // to the OBMC knob rather than always on: with every block choosing
2094 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
2095 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
2096 // and stays byte-identical to the streams before this lane.
2097 // lane-av1obmc2: the warp knob joins that disjunction, and turns on
2098 // `allow_warped_motion` besides -- which is what makes an eligible
2099 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
2100 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
2101 is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC")
2102 || warp_on(),
2103 allow_warped_motion: warp_on(),
2104 use_ref_frame_mvs: false,
2105 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
2106 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
2107 // set this crate carries a table for at 16x16 (see
2108 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
2109 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
2110 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
2111 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
2112 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
2113 // path) -- with this flag set, `get_tx_set`'s intra branch returns
2114 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
2115 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
2116 reduced_tx_set: true,
2117 ..key
2118 };
2119 Ok((seq, header))
2120}
2121
2122fn too_large() -> Error {
2123 Error::unsupported(
2124 "AV1 encode",
2125 "the picture is larger than a frame size can carry",
2126 )
2127}
2128
2129/// One plane of the picture being coded, and the reconstruction being built
2130/// beside it.
2131/// What one committed 4x4 cell left behind for the coefficient contexts of
2132/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
2133/// is the same state decode.rs records.
2134#[derive(Clone, Copy, Default, PartialEq, Eq)]
2135struct CoefCtx {
2136 /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
2137 level: u8,
2138 /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
2139 /// the DC itself was zero (tile.rs `dc_vote`).
2140 dc: i8,
2141}
2142
2143/// One plane's coefficient contexts, committed in CODING ORDER: the search
2144/// prices partition TREES, so the neighbour state a candidate reads has to be
2145/// whatever the blocks coded before it left -- the parent's committed
2146/// neighbours for a tree's first child, the just-committed sibling for the
2147/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
2148/// writer's two running bands is what makes that fall out: a trial commits
2149/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
2150/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
2151/// to its left is exactly what the tile writer's `Neighbours` bands will hold
2152/// when it gets there.
2153///
2154/// Before this map the pricer took both contexts as zero, which is exact for
2155/// a luma transform covering its whole block and the largest remaining row of
2156/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
2157#[derive(Default)]
2158struct CoefCtxMap {
2159 cells: Vec<CoefCtx>,
2160 stride: usize,
2161 /// Whether the transforms being priced right now are SMALLER than the
2162 /// block they sit in -- a `TxMode::Select` depth split
2163 /// ([`Plane::code_tx_depth`]) or an inter var-tx split
2164 /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
2165 /// trial cannot tell, and it is what decides whether luma reads context 0
2166 /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
2167 tu_split: bool,
2168}
2169
2170/// Whether [`Plane::block_sse`] scores a block the true frame edge cuts
2171/// through over its INSIDE part alone. On; `EC_AV1_EDGESSE=0` restores the
2172/// padding-inclusive score the search used before lane-sse, which is how the
2173/// before/after arms of the straddling gate rows are read off ONE binary.
2174fn edge_sse() -> bool {
2175 static ENV: std::sync::LazyLock<Option<bool>> =
2176 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGESSE").ok().map(|v| v != "0"));
2177 ENV.unwrap_or(true)
2178}
2179
2180/// Whether [`Plane::block_sse`] counts the blocks the true frame edge cuts
2181/// through and the share of their raw squared error that sat in the padding
2182/// (`EC_AV1_EDGE_CENSUS=1`). Off by default: only edge blocks would pay for
2183/// it, but the numbers are an instrument, not a decision (class
2184/// `gate-blind-to-feature` -- both gate films are superblock-aligned, so
2185/// without this census no gate row can say the clip fires at all).
2186fn edge_census() -> bool {
2187 static ENV: std::sync::LazyLock<bool> =
2188 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1"));
2189 *ENV
2190}
2191
2192/// Per block side (indexed by `side.trailing_zeros()`, so 2 is 4x4 and 7 is
2193/// 128x128): how many scores clipped, the inside squared error they kept and
2194/// the padding squared error they dropped.
2195static EDGE_SCORES: [[std::sync::atomic::AtomicU64; 3]; 8] =
2196 [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 8];
2197
2198/// One clipped score, for [`take_edge_census`].
2199fn record_edge_score(side: usize, inside: u64, padding: u64) {
2200 let row = &EDGE_SCORES[(side.trailing_zeros() as usize).min(7)];
2201 row[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2202 row[1].fetch_add(inside, std::sync::atomic::Ordering::Relaxed);
2203 row[2].fetch_add(padding, std::sync::atomic::Ordering::Relaxed);
2204}
2205
2206/// The straddling-block census since the last call, and zero it: one
2207/// `(side, scores, inside_sse, padding_sse)` row per block size that fired.
2208#[must_use]
2209pub fn take_edge_census() -> Vec<(usize, u64, u64, u64)> {
2210 EDGE_SCORES
2211 .iter()
2212 .enumerate()
2213 .filter_map(|(log2, row)| {
2214 let n = row[0].swap(0, std::sync::atomic::Ordering::Relaxed);
2215 let inside = row[1].swap(0, std::sync::atomic::Ordering::Relaxed);
2216 let padding = row[2].swap(0, std::sync::atomic::Ordering::Relaxed);
2217 (n != 0).then_some((1usize << log2, n, inside, padding))
2218 })
2219 .collect()
2220}
2221
2222struct Plane<'a> {
2223 source: &'a [u8],
2224 reconstruction: Vec<u8>,
2225 width: usize,
2226 height: usize,
2227 /// The frame's true, decodable extent in this plane's own units --
2228 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
2229 /// not `width`/`height` above, which is the padded coding-surface size.
2230 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
2231 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
2232 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
2233 /// this bound, even though the padded reconstruction buffer holds real
2234 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
2235 /// those instead of stopping here is what desyncs prediction at the true
2236 /// edge.
2237 true_width: usize,
2238 true_height: usize,
2239 /// This plane's own tile's pixel bounds, in this plane's units -- the
2240 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
2241 /// prediction never reaches across a tile edge even though the
2242 /// neighbouring tile's real samples sit right there in the shared
2243 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
2244 /// leaves every edge exactly as it was before tiles existed.
2245 tile_x0: usize,
2246 tile_y0: usize,
2247 tile_x1: usize,
2248 tile_y1: usize,
2249 /// [`CoefCtxMap`]: what the blocks already committed left for the
2250 /// coefficient contexts of the ones still being priced. Sized on the
2251 /// first commit, so a plane literal does not have to know its own extent
2252 /// twice.
2253 ctx: CoefCtxMap,
2254}
2255
2256impl Plane<'_> {
2257 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
2258 /// called at every superblock of the frame-raster search with the rect
2259 /// of the tile that superblock belongs to.
2260 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
2261 self.tile_x0 = x0;
2262 self.tile_y0 = y0;
2263 self.tile_x1 = x1.min(self.width);
2264 self.tile_y1 = y1.min(self.height);
2265 }
2266 /// The reconstructed samples a block at `(x, y)` predicts from: the row
2267 /// above it, the column to its left and the sample between them, each
2268 /// missing where the block sits against an edge of the frame.
2269 ///
2270 /// `reach` says whether the samples above the block's right and below its
2271 /// left are decoded, which is what a directional mode reads into; where
2272 /// they are not, or where the frame ends first, the edge is shorter and
2273 /// the predictor repeats its last sample, exactly as the decoder's clamp
2274 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
2275 /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and
2276 /// a free per mode per block, on the search's hottest path -- while an
2277 /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same
2278 /// samples, on the caller's stack.
2279 fn edges_into<'a>(
2280 &self,
2281 x: usize,
2282 y: usize,
2283 side: usize,
2284 reach: Reach,
2285 above_buf: &'a mut [u8; 2 * SUPERBLOCK],
2286 left_buf: &'a mut [u8; 2 * SUPERBLOCK],
2287 ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) {
2288 // Even a block's *own* edge is clamped to the true frame bound, not
2289 // just a `reach` extension: libaom's `av1_predict_intra_block`
2290 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
2291 // this block's own right/bottom to the frame edge -- from
2292 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
2293 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
2294 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
2295 // samples the row/column above/left holds before the decoder starts
2296 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
2297 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
2298 // extent straddles that edge legally (`has_half`) -- the transform
2299 // still covers the whole block, but prediction does not get to read
2300 // real reconstructed pixels past the true edge for its own row/column,
2301 // only for the padded tail it invents.
2302 let own_across = x + side.min(self.true_width.saturating_sub(x));
2303 let across = if reach.above_right {
2304 own_across + side.min(self.true_width.saturating_sub(own_across))
2305 } else {
2306 own_across
2307 }
2308 .min(self.width);
2309 let own_down = y + side.min(self.true_height.saturating_sub(y));
2310 let down = if reach.below_left {
2311 own_down + side.min(self.true_height.saturating_sub(own_down))
2312 } else {
2313 own_down
2314 }
2315 .min(self.height);
2316 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
2317 // whose own origin already sits past the true edge -- only reachable
2318 // through a partition trial priced for comparison on a split this
2319 // frame's straddling quadrant will go on to refuse (see
2320 // `a_picture_off_the_block_grid_is_refused`), never through a block
2321 // this encoder actually commits. Such a block has no true-edge
2322 // samples above or left of it at all, same as `y == 0`/`x == 0`.
2323 let across = across.min(self.tile_x1);
2324 let down = down.min(self.tile_y1);
2325 let above_n = (y > self.tile_y0 && across > x).then(|| across - x);
2326 if let Some(n) = above_n {
2327 above_buf[..n]
2328 .copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
2329 }
2330 let left_n = (x > self.tile_x0 && down > y).then(|| down - y);
2331 if let Some(n) = left_n {
2332 for (d, row) in left_buf[..n].iter_mut().zip(y..down) {
2333 *d = self.reconstruction[row * self.width + x - 1];
2334 }
2335 }
2336 let corner = (x > self.tile_x0 && y > self.tile_y0)
2337 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
2338 (
2339 above_n.map(|n| &above_buf[..n]),
2340 left_n.map(|n| &left_buf[..n]),
2341 corner,
2342 )
2343 }
2344
2345 /// Codes one block under one mode without committing it: hands back the
2346 /// levels, the block the decoder would reconstruct, the squared error
2347 /// against the source and an estimate of what the levels cost in bits.
2348 fn trial(&self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
2349 self.trial_typed(at, mode, angle_delta, base_q_idx, deadzone, TxType::DctDct, fctx)
2350 }
2351
2352 /// [`Self::trial`] under a named transform type -- what an intra chroma
2353 /// block gets, since chroma codes no `tx_type` symbol and the decoder
2354 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
2355 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
2356 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
2357 #[allow(clippy::too_many_arguments)]
2358 /// Sum of absolute differences between the source block at `(x, y)` and a
2359 /// `side x side` prediction, as the whole number it is.
2360 ///
2361 /// Bit-identical to the `f64` accumulation it replaces: every partial sum
2362 /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
2363 /// exactly, so no add here rounds and the order of the adds cannot change
2364 /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
2365 /// integer division per sample -- is what lets the row walk vectorize.
2366 fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
2367 let mut sad = 0u32;
2368 for row in 0..side {
2369 let source = &self.source[(y + row) * self.width + x..][..side];
2370 for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
2371 sad += u32::from(s.abs_diff(p));
2372 }
2373 }
2374 f64::from(sad)
2375 }
2376
2377 /// Squared error between the source block at `(x, y)` and a reconstruction
2378 /// of it, over the part of the block that is INSIDE the true frame.
2379 /// Exact for the same reason [`Self::block_sad`] is: the largest total is
2380 /// `255^2 * 64 * 64`, under 2^28.
2381 ///
2382 /// A block the frame edge cuts through is still coded whole -- the
2383 /// decoder reconstructs its outside samples too and the display crop
2384 /// throws them away -- so scoring the padding would rank a mode, a
2385 /// transform or a partition tree by how well it codes samples the source
2386 /// does not have (libaom clips the same way: `av1_dist_block` measures
2387 /// over `max_blocks_wide`/`max_blocks_high`). The padding is replicated
2388 /// edge pixels, so predicting it is nearly free, but coding coefficients
2389 /// for it spends real bits. Both gate films are superblock-aligned; this
2390 /// only reaches arbitrary export sizes (lane-sse, generalising
2391 /// lane-b64b's 64-root-only rescore of the 64 root).
2392 fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
2393 let inside_rows = side.min(self.true_height.saturating_sub(y));
2394 let inside_cols = side.min(self.true_width.saturating_sub(x));
2395 let straddles = inside_rows < side || inside_cols < side;
2396 // The knob is read only for a block the edge cuts, so the interior
2397 // path -- the hot one -- carries no extra load at all.
2398 let (rows, cols) = match straddles && !edge_sse() {
2399 true => (side, side),
2400 false => (inside_rows, inside_cols),
2401 };
2402 let mut sse = 0u64;
2403 for row in 0..rows {
2404 let source = &self.source[(y + row) * self.width + x..][..cols];
2405 for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..cols]) {
2406 let d = u32::from(s.abs_diff(r));
2407 sse += u64::from(d * d);
2408 }
2409 }
2410 if straddles && edge_census() {
2411 let (mut inside, mut whole) = (0u64, 0u64);
2412 for row in 0..side {
2413 let source = &self.source[(y + row) * self.width + x..][..side];
2414 for (col, (&s, &r)) in
2415 source.iter().zip(&reconstruction[row * side..][..side]).enumerate()
2416 {
2417 let d = u64::from(u32::from(s.abs_diff(r)).pow(2));
2418 whole += d;
2419 if row < inside_rows && col < inside_cols {
2420 inside += d;
2421 }
2422 }
2423 }
2424 record_edge_score(side, inside, whole - inside);
2425 }
2426 sse as f64
2427 }
2428
2429 fn trial_typed(
2430 &self,
2431 at: At,
2432 mode: u8,
2433 // This block's `angle_delta_y`/`angle_delta_uv` (spec
2434 // `read_intra_angle_info`, -3..=3), zero for every non-directional
2435 // mode -- the predictor's own `angle_delta` argument.
2436 angle_delta: i32,
2437 base_q_idx: u8,
2438 deadzone: f64,
2439 tx_type: TxType,
2440 fctx: &crate::decode::FrameCtx,
2441 ) -> Trial {
2442 let At {
2443 x, y, side, reach, ..
2444 } = at;
2445 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2446 let (above, left, corner) =
2447 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2448 // Per-candidate scratch on the search's hottest path, so both buffers
2449 // live on the stack -- `side` is at most `BLOCK` -- rather than
2450 // costing a malloc/free pair per trial (`mc_trial` already does this).
2451 let mut prediction = [0u8; BLOCK * BLOCK];
2452 let prediction = &mut prediction[..side * side];
2453 intra_predict_u8(
2454 mode,
2455 angle_delta,
2456 above,
2457 left,
2458 corner,
2459 side,
2460 side,
2461 false,
2462 false,
2463 prediction, fctx,
2464 );
2465
2466 let mut residual = [0i32; BLOCK * BLOCK];
2467 let residual = &mut residual[..side * side];
2468 for row in 0..side {
2469 for col in 0..side {
2470 residual[row * side + col] =
2471 i32::from(self.source[(y + row) * self.width + x + col])
2472 - i32::from(prediction[row * side + col]);
2473 }
2474 }
2475 #[cfg(test)]
2476 let t = stage_start();
2477 // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the
2478 // reconstruction below and the price further down are both of the
2479 // grid this trial would really code.
2480 let (levels, rdoq_bits) = if rdoq_on() {
2481 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
2482 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2483 );
2484 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2485 let bits = crate::tile::rdoq(
2486 &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(),
2487 tx_type,
2488 );
2489 (levels, Some(bits))
2490 } else {
2491 (
2492 forward_and_quantize_typed(
2493 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2494 ),
2495 None,
2496 )
2497 };
2498 // lane-av1speed2: 60% of the transform units of an inter stream carry
2499 // no coefficient at all, and the square entry point re-inflates that
2500 // case into `side * side` zeros (one allocate-and-memset per trial)
2501 // only for the sum below to add them to the prediction. The `_wh`
2502 // entry hands back the empty all-zero marker instead, and a zero
2503 // residual reconstructs to the prediction itself -- `clamp(p + 0)` is
2504 // `p` for a `u8`, so the bytes are the same.
2505 let coded = dequant_and_inverse_typed_wh(
2506 &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type,
2507 );
2508 #[cfg(test)]
2509 stage_since(2, t);
2510
2511 let reconstruction: Vec<u8> = if coded.is_empty() {
2512 prediction.to_vec()
2513 } else {
2514 prediction
2515 .iter()
2516 .zip(&coded)
2517 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
2518 .collect()
2519 };
2520 let sse = self.block_sse(x, y, side, &reconstruction);
2521 // What the levels cost is priced through the same CDFs the tile writer
2522 // will code them with, so the search ranks modes -- and the partition
2523 // trial ranks trees -- by the bits they actually spend.
2524 #[cfg(test)]
2525 let t = stage_start();
2526 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
2527 // What the search used before it could price a block exactly: a
2528 // level costs its magnitude's width plus a sign and a run. Kept
2529 // reachable from the sweep so the two rate terms can be compared
2530 // on one build.
2531 levels
2532 .iter()
2533 .filter(|&&level| level != 0)
2534 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
2535 .sum()
2536 } else if let Some(bits) = rdoq_bits {
2537 // Already priced, against the grid the pass settled on.
2538 bits
2539 } else {
2540 {
2541 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2542 crate::tile::coeff_bits_typed(
2543 &levels,
2544 at.set,
2545 crate::decode::q_ctx_of(base_q_idx),
2546 skip_ctx,
2547 sign_ctx,
2548 tx_type,
2549 )
2550 }
2551 };
2552 #[cfg(test)]
2553 stage_since(3, t);
2554 Trial {
2555 levels,
2556 reconstruction,
2557 sse,
2558 bits,
2559 }
2560 }
2561
2562 /// [`Self::trial`] with the prediction already built, so that an inter
2563 /// block's motion-compensated prediction can go through the same
2564 /// residual/quantize/reconstruct path an intra block's does. `skip`
2565 /// takes the prediction as the reconstruction outright, coding no
2566 /// residual at all — what a `NEARESTMV` block that names no coefficients
2567 /// codes.
2568 #[allow(clippy::too_many_arguments)]
2569 fn code_from_prediction(
2570 &self,
2571 x: usize,
2572 y: usize,
2573 side: usize,
2574 prediction: &[u8],
2575 skip: bool,
2576 base_q_idx: u8,
2577 deadzone: f64,
2578 set: TxbSet,
2579 ) -> Trial {
2580 self.code_from_prediction_typed(
2581 x, y, side, prediction, skip, base_q_idx, deadzone, set, TxType::DctDct,
2582 )
2583 }
2584
2585 /// [`Self::code_from_prediction`] coding the residual with a NAMED
2586 /// transform type (lane-txset2): the inter luma sets carry a two-type
2587 /// alphabet (`TX_SET_INTER_3`, `IDTX`/`DCT_DCT`) the writer already codes
2588 /// a symbol for, and [`commit_inter_luma`] prices both through this.
2589 #[allow(clippy::too_many_arguments)]
2590 fn code_from_prediction_typed(
2591 &self,
2592 x: usize,
2593 y: usize,
2594 side: usize,
2595 prediction: &[u8],
2596 skip: bool,
2597 base_q_idx: u8,
2598 deadzone: f64,
2599 set: TxbSet,
2600 tx_type: TxType,
2601 ) -> Trial {
2602 if skip {
2603 let sse = self.block_sse(x, y, side, prediction);
2604 return Trial {
2605 levels: vec![0i32; side * side],
2606 reconstruction: prediction.to_vec(),
2607 sse,
2608 bits: 0.0,
2609 };
2610 }
2611 // A 64x64 root's residual is four times the scratch every other
2612 // block coder here sizes for [`BLOCK`]; only that one case pays for
2613 // a heap buffer, so the 4x4..32x32 path keeps its stack array.
2614 let mut small = [0i32; BLOCK * BLOCK];
2615 let mut big = if side > BLOCK {
2616 vec![0i32; side * side]
2617 } else {
2618 Vec::new()
2619 };
2620 let residual: &mut [i32] = if side > BLOCK {
2621 &mut big
2622 } else {
2623 &mut small[..side * side]
2624 };
2625 for row in 0..side {
2626 for col in 0..side {
2627 residual[row * side + col] =
2628 i32::from(self.source[(y + row) * self.width + x + col])
2629 - i32::from(prediction[row * side + col]);
2630 }
2631 }
2632 #[cfg(test)]
2633 let t = stage_start();
2634 // lane-rdoq, as in [`Self::trial_typed`].
2635 let (levels, rdoq_bits) = if rdoq_on() {
2636 let (mut levels, scaled) =
2637 forward_and_quantize_typed_scaled(
2638 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2639 );
2640 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
2641 let bits = crate::tile::rdoq(
2642 &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(),
2643 tx_type,
2644 );
2645 (levels, Some(bits))
2646 } else {
2647 (
2648 forward_and_quantize_typed(
2649 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2650 ),
2651 None,
2652 )
2653 };
2654 // The same all-zero shortcut [`Self::trial_typed`] takes.
2655 let coded = dequant_and_inverse_typed_wh(
2656 &levels,
2657 side,
2658 side,
2659 8,
2660 i32::from(base_q_idx),
2661 0,
2662 0,
2663 tx_type,
2664 );
2665 #[cfg(test)]
2666 stage_since(2, t);
2667 let reconstruction: Vec<u8> = if coded.is_empty() {
2668 prediction.to_vec()
2669 } else {
2670 prediction
2671 .iter()
2672 .zip(&coded)
2673 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
2674 .collect()
2675 };
2676 let sse = self.block_sse(x, y, side, &reconstruction);
2677 // A 64-point transform codes only its top-left 32x32 corner (spec
2678 // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the
2679 // key frame writer takes a 32x32 level grid for one). The inverse
2680 // above reads the whole 64x64 array, but the price below and the
2681 // levels the writer takes are that corner.
2682 let levels = if side > BLOCK {
2683 coded_corner(&levels, side, BLOCK)
2684 } else {
2685 levels
2686 };
2687 #[cfg(test)]
2688 let t = stage_start();
2689 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
2690 levels
2691 .iter()
2692 .filter(|&&level| level != 0)
2693 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
2694 .sum()
2695 } else if let Some(bits) = rdoq_bits {
2696 bits
2697 } else {
2698 {
2699 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
2700 crate::tile::coeff_bits_typed(
2701 &levels,
2702 set,
2703 crate::decode::q_ctx_of(base_q_idx),
2704 skip_ctx,
2705 sign_ctx,
2706 tx_type,
2707 )
2708 }
2709 };
2710 #[cfg(test)]
2711 stage_since(3, t);
2712 Trial {
2713 levels,
2714 reconstruction,
2715 sse,
2716 bits,
2717 }
2718 }
2719
2720 /// Codes this block's luma at transform depth `depth`: the
2721 /// `(side >> depth)^2` transform units in raster order, each predicted
2722 /// from the reconstruction the units before it left behind -- exactly
2723 /// what the decoder's multi-transform-unit branch does (decode.rs
2724 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
2725 /// reconstructed on its own. Commits the result and hands back the
2726 /// block-coordinate levels, the block's squared error and what its
2727 /// coefficients cost.
2728 #[allow(clippy::too_many_arguments)]
2729 fn code_tx_depth(
2730 &mut self,
2731 at: At,
2732 mode: u8,
2733 angle_delta: i32,
2734 depth: usize,
2735 // This block's `filter_intra_mode` when it is coded with one, in
2736 // which case every transform unit predicts recursively off the
2737 // reconstruction the units before it left -- what the decoder does
2738 // per unit (decode.rs `decode_block`, `push_intra_rect`'s
2739 // `filter_intra`), not once over the whole block.
2740 filter_intra: Option<u8>,
2741 search: &Search, fctx: &crate::decode::FrameCtx,
2742 ) -> (Vec<i32>, f64, f64, Vec<TxType>) {
2743 let At { x, y, side, reach, .. } = at;
2744 let tx = side >> depth;
2745 let n = 1usize << depth;
2746 let set = luma_set_for(
2747 match tx {
2748 32 => TxbSet::Luma32,
2749 16 => TxbSet::Luma16,
2750 8 => TxbSet::Luma8,
2751 _ => TxbSet::Luma4,
2752 },
2753 search.screen,
2754 );
2755 let mut levels = vec![0i32; side * side];
2756 census_add(4, n * n);
2757 // A unit smaller than its block reads the neighbour magnitude table
2758 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
2759 self.ctx.tu_split = n > 1;
2760 let (mut sse, mut bits) = (0.0, 0.0);
2761 // One entry per unit at its own `tu_row * n + tu_col`, which is how
2762 // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the
2763 // frame edge cuts away is never coded there, so a compacted list
2764 // would slide every later unit's type onto the wrong transform.
2765 let mut tx_types = vec![TxType::DctDct; n * n];
2766 for tu_row in 0..n {
2767 for tu_col in 0..n {
2768 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
2769 let tu = At {
2770 x: x + col_off,
2771 y: y + row_off,
2772 side: tx,
2773 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
2774 set,
2775 };
2776 let trial = match filter_intra {
2777 Some(fi) => {
2778 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2779 let (above, left, corner) =
2780 self.edges_into(tu.x, tu.y, tx, tu.reach, &mut above_buf, &mut left_buf);
2781 let mut prediction = vec![0u8; tx * tx];
2782 filter_intra_predict_u8(
2783 usize::from(fi),
2784 above,
2785 left,
2786 corner,
2787 tx,
2788 &mut prediction,
2789 fctx,
2790 );
2791 self.code_from_prediction(
2792 tu.x,
2793 tu.y,
2794 tx,
2795 &prediction,
2796 false,
2797 search.base_q_idx,
2798 search.deadzone,
2799 set,
2800 )
2801 }
2802 None => {
2803 // lane-txset: the unit picks its own transform type
2804 // out of the set the writer can name it in, priced
2805 // through the same RDOQ'd trial path (its `bits`
2806 // already carry the `tx_type` symbol itself).
2807 let mut best: Option<(f64, TxType, Trial)> = None;
2808 for &tx_type in tx_type_candidates(set, search.screen) {
2809 let candidate = self.trial_typed(
2810 tu, mode, angle_delta, search.base_q_idx, search.deadzone,
2811 tx_type, fctx,
2812 );
2813 // lane-txi: a non-`DCT_DCT` type is charged its
2814 // bits at `EC_AV1_TXRD_LAMBDA` times the mode
2815 // search's weight (default 1 = unchanged). The
2816 // film rows buy 0.04 dB for 1.2% more bytes at
2817 // weight 1 on every frame and every PLANE, key
2818 // frame included -- a rate term this decision
2819 // under-charges (class
2820 // `rd-rate-term-calibration`), not the
2821 // propagation loss the leaves would have shown.
2822 let cost = candidate.sse
2823 + search.lambda * candidate.bits
2824 + non_dct_surcharge(search.lambda, tx_type, candidate.bits);
2825 if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {
2826 best = Some((cost, tx_type, candidate));
2827 }
2828 }
2829 let (_, tx_type, trial) =
2830 best.expect("the candidate list is never empty");
2831 tx_types[tu_row * n + tu_col] = tx_type;
2832 TX_TYPE_HITS[tx_type as usize]
2833 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2834 trial
2835 }
2836 };
2837 sse += trial.sse;
2838 bits += trial.bits;
2839 self.commit(tu.x, tu.y, tx, &trial);
2840 for row in 0..tx {
2841 levels[(row_off + row) * side + col_off..][..tx]
2842 .copy_from_slice(&trial.levels[row * tx..][..tx]);
2843 }
2844 }
2845 }
2846 self.ctx.tu_split = false;
2847 (levels, sse, bits, tx_types)
2848 }
2849
2850 /// Writes a trial's reconstruction back into the plane, and the
2851 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
2852 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
2853 for row in 0..side {
2854 self.reconstruction[(y + row) * self.width + x..][..side]
2855 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
2856 }
2857 self.commit_ctx(x, y, side, &trial.levels);
2858 }
2859
2860 /// Publishes one committed transform's own context over every 4x4 cell it
2861 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
2862 /// which is what the writer will read when it reaches the next block.
2863 fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
2864 if self.ctx.cells.is_empty() {
2865 self.ctx.stride = self.width.div_ceil(4);
2866 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
2867 }
2868 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
2869 let state = CoefCtx {
2870 level: cul,
2871 dc: match levels[0].signum() {
2872 0 => 0,
2873 -1 => -1,
2874 _ => 1,
2875 },
2876 };
2877 let n = (side / 4).max(1);
2878 // Only up to the frame's TRUE extent: the writer's own
2879 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
2880 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
2881 // and leaves the cells past it uncoded even mid-block, so a
2882 // straddling block publishes context for its inside part only.
2883 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
2884 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
2885 for row in 0..rows {
2886 let start = (y / 4 + row) * self.ctx.stride + x / 4;
2887 let end = (start + cols).min(self.ctx.cells.len());
2888 if start < end {
2889 self.ctx.cells[start..end].fill(state);
2890 }
2891 }
2892 }
2893
2894 /// A block committed without any residual at all ([`ibc_commit`]): the
2895 /// cells it covers coded nothing, and leaving an earlier trial's state
2896 /// there would price its neighbours off a block that was never coded.
2897 fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
2898 self.commit_ctx(x, y, side, &[0i32]);
2899 }
2900
2901 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
2902 /// plane reads, off what the blocks before it in coding order committed
2903 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
2904 /// the above/left neighbours coded anything (tile.rs
2905 /// `write_block_planes`), luma reads context 0 when its transform covers
2906 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
2907 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
2908 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
2909 /// the same neighbours (tile.rs `dc_sign_ctx`).
2910 ///
2911 /// A neighbour outside this plane's own TILE does not exist, exactly as
2912 /// the writer's per-tile `Neighbours` bands start blank.
2913 ///
2914 /// CLOSED (lane-av1straddle): the decisions this price changes used to
2915 /// make `decode_stream_round_trips_an_odd_size_gop` and
2916 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
2917 /// fail at 216x96. Never this map: the writer coded the phantom
2918 /// transform units of a right-edge-straddling 32x32 (tile.rs
2919 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
2920 /// like decode.rs and libaom), which libdav1d and libaom both refused
2921 /// outright while a decision change was what first walked into it.
2922 fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
2923 if self.ctx.cells.is_empty() {
2924 return (0, 0);
2925 }
2926 let n = (side / 4).max(1);
2927 let (cx, cy) = (x / 4, y / 4);
2928 let (mut top, mut left) = (0u8, 0u8);
2929 let mut vote = 0i32;
2930 if y > self.tile_y0 && cy > 0 {
2931 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
2932 top |= cell.level;
2933 vote += i32::from(cell.dc);
2934 }
2935 }
2936 if x > self.tile_x0 && cx > 0 {
2937 for row in 0..n {
2938 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
2939 left |= cell.level;
2940 vote += i32::from(cell.dc);
2941 }
2942 }
2943 let skip_ctx = if set.is_chroma() {
2944 usize::from(top != 0) + usize::from(left != 0)
2945 } else if self.ctx.tu_split {
2946 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
2947 } else {
2948 0
2949 };
2950 let sign_ctx = match vote.signum() {
2951 0 => 0,
2952 -1 => 1,
2953 _ => 2,
2954 };
2955 (skip_ctx, sign_ctx)
2956 }
2957
2958 /// The source samples of one square, contiguous — what a motion search
2959 /// compares its candidates' predictions against ([`motion::search`]'s
2960 /// `source`), since [`Self::source`] itself is the whole plane, strided
2961 /// by [`Self::width`].
2962 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
2963 rows_of(self.source, self.width, x, y, side)
2964 }
2965
2966 /// The reconstructed samples of one square, so that a partition trial can
2967 /// be undone.
2968 /// The reconstructed samples of one square AND the coefficient contexts
2969 /// its cells hold, so that a partition trial can be undone whole: a
2970 /// losing trial that left its own nz/DC state behind would price the
2971 /// blocks after it off a block the tile writer never codes.
2972 fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
2973 (
2974 rows_of(&self.reconstruction, self.width, x, y, side),
2975 self.ctx_rows(x, y, side),
2976 )
2977 }
2978
2979 fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
2980 if self.ctx.cells.is_empty() {
2981 return Vec::new();
2982 }
2983 let n = (side / 4).max(1);
2984 (0..n)
2985 .flat_map(|row| {
2986 let start = (y / 4 + row) * self.ctx.stride + x / 4;
2987 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
2988 })
2989 .collect()
2990 }
2991
2992 /// Puts a snapshot back.
2993 fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
2994 for row in 0..side {
2995 self.reconstruction[(y + row) * self.width + x..][..side]
2996 .copy_from_slice(&saved.0[row * side..][..side]);
2997 }
2998 if saved.1.is_empty() {
2999 return;
3000 }
3001 let n = (side / 4).max(1);
3002 for row in 0..n {
3003 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3004 let end = (start + n).min(self.ctx.cells.len());
3005 if start < end {
3006 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
3007 }
3008 }
3009 }
3010
3011 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
3012 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
3013 /// prescreen by the identical rule rather than a second one that could
3014 /// drift from it.
3015 fn intra_scores(
3016 &self,
3017 at: At,
3018 modes: &[u8],
3019 mode_bits: &[f64; 13],
3020 lambda: f64, fctx: &crate::decode::FrameCtx,
3021 ) -> Vec<(f64, u8)> {
3022 let At {
3023 x, y, side, reach, ..
3024 } = at;
3025 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3026 let (above, left, corner) =
3027 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3028 modes
3029 .iter()
3030 .map(|&mode| {
3031 let mut prediction = vec![0u8; side * side];
3032 intra_predict_u8(
3033 mode,
3034 0,
3035 above,
3036 left,
3037 corner,
3038 side,
3039 side,
3040 false,
3041 false,
3042 &mut prediction, fctx,
3043 );
3044 let sad = self.block_sad(x, y, side, &prediction);
3045 (sad + lambda * mode_bits[usize::from(mode)], mode)
3046 })
3047 .collect()
3048 }
3049
3050 /// Codes one block under every mode the search offers (or, when
3051 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
3052 /// pre-pass plus DC) and commits the one whose squared error and
3053 /// estimated rate come out cheapest.
3054 ///
3055 /// The prediction is built once per mode regardless -- the full RD trial
3056 /// needs it too -- so ranking modes by SAD on that same prediction before
3057 /// running the expensive part (forward transform, quantize, reconstruct,
3058 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
3059 /// only to sum.
3060 fn search_block(
3061 &mut self,
3062 at: At,
3063 search: &Search,
3064 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
3065 ) -> (Vec<Coeff>, u8, i32, f64, TxType) {
3066 let At {
3067 x, y, side, reach, ..
3068 } = at;
3069 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3070 let (above, left, corner) =
3071 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3072 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
3073 // the census reports it), so summing it under the default unpruned
3074 // search is `side * side` absolute differences per mode spent on a
3075 // number no one reads.
3076 let want_sad = search.top_k.is_some() || census_on();
3077 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
3078 .modes
3079 .iter()
3080 .map(|&mode| {
3081 let mut prediction = vec![0u8; side * side];
3082 intra_predict_u8(
3083 mode,
3084 0,
3085 above,
3086 left,
3087 corner,
3088 side,
3089 side,
3090 false,
3091 false,
3092 &mut prediction, fctx,
3093 );
3094 let sad = if want_sad {
3095 self.block_sad(x, y, side, &prediction)
3096 } else {
3097 0.0
3098 };
3099 (
3100 sad + search.lambda * mode_bits[usize::from(mode)],
3101 mode,
3102 prediction,
3103 )
3104 })
3105 .collect();
3106 if let Some(k) = search.top_k {
3107 if k < scored.len() {
3108 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
3109 let dc_entry = dc_pos.map(|i| scored.remove(i));
3110 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
3111 scored.truncate(if dc_entry.is_some() {
3112 k.saturating_sub(1)
3113 } else {
3114 k
3115 });
3116 if let Some(dc_entry) = dc_entry {
3117 scored.push(dc_entry);
3118 }
3119 }
3120 }
3121 let ranking: Vec<(f64, u8)> = if census_on() {
3122 scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
3123 } else {
3124 Vec::new()
3125 };
3126 census_add(0, 1);
3127 census_add(1, scored.len());
3128 let mut best: Option<(f64, u8, Trial)> = None;
3129 for (_, mode, prediction) in scored {
3130 let trial = self.code_from_prediction(
3131 x,
3132 y,
3133 side,
3134 &prediction,
3135 false,
3136 search.base_q_idx,
3137 search.deadzone,
3138 at.set,
3139 );
3140 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
3141 if best
3142 .as_ref()
3143 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
3144 {
3145 best = Some((cost, mode, trial));
3146 }
3147 }
3148 let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
3149 // `angle_delta_y` (spec `read_intra_angle_info`): the eight
3150 // directional modes each carry a -3..=3 delta, three degrees a step,
3151 // which the writer has always coded as ZERO because nothing searched
3152 // it. Refined on the winning mode only -- libaom's own ordering, and
3153 // six extra trials on the directional blocks instead of on every
3154 // block times every mode. The edges are the ones the base angle
3155 // already read (`enable_intra_edge_filter` is off in this encoder's
3156 // sequence header, so no delta changes which samples exist), and the
3157 // predictor is the decoder's, `angle_delta` argument and all.
3158 let mut angle_delta = 0i32;
3159 // Not on a screen frame: measured on the 5-row native gate, the
3160 // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
3161 // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
3162 // synthetic edges land on the base angles, so every delta there buys
3163 // a symbol and no prediction. Same `search.screen` gate palette and
3164 // intrabc already stand behind.
3165 if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
3166 let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
3167 let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
3168 let mut prediction = vec![0u8; side * side];
3169 for delta in [-3i32, -2, -1, 1, 2, 3] {
3170 intra_predict_u8(
3171 mode,
3172 delta,
3173 above,
3174 left,
3175 corner,
3176 side,
3177 side,
3178 false,
3179 false,
3180 &mut prediction, fctx,
3181 );
3182 let candidate = self.code_from_prediction(
3183 x,
3184 y,
3185 side,
3186 &prediction,
3187 false,
3188 search.base_q_idx,
3189 search.deadzone,
3190 at.set,
3191 );
3192 let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
3193 - zero_bits;
3194 let cost_d = candidate.sse
3195 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
3196 if cost_d < cost {
3197 cost = cost_d;
3198 angle_delta = delta;
3199 trial = candidate;
3200 }
3201 }
3202 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
3203 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3204 }
3205 // lane-txset: the block's own transform type, searched on the mode
3206 // and angle the trials above settled -- the same ordering the angle
3207 // refinement uses, and the same RD terms.
3208 let mut tx_type = TxType::DctDct;
3209 for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) {
3210 let candidate = self.trial_typed(
3211 at, mode, angle_delta, search.base_q_idx, search.deadzone, candidate_type, fctx,
3212 );
3213 let cost_t =
3214 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
3215 // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is
3216 // `DCT_DCT` and pays none of it, so the returned `cost` stays the
3217 // block's true one for the caller's own decision.
3218 if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost {
3219 cost = cost_t;
3220 tx_type = candidate_type;
3221 trial = candidate;
3222 }
3223 }
3224 TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3225 if census_on() {
3226 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
3227 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3228 }
3229 self.commit(x, y, side, &trial);
3230 // A 64-point transform codes only its top-left 32x32 corner, which is
3231 // the grid `code_from_prediction` hands back (lane-i64).
3232 (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost, tx_type)
3233 }
3234}
3235
3236/// Where one block sits in its plane, and how far past its own edges its
3237/// prediction may read.
3238#[derive(Clone, Copy)]
3239struct At {
3240 x: usize,
3241 y: usize,
3242 side: usize,
3243 reach: Reach,
3244 /// Which of the tile writer's coefficient tables this block's levels are
3245 /// coded with, and so which the search prices them through.
3246 set: TxbSet,
3247}
3248
3249/// Which of the samples past a block's own edges the decoder has decoded by
3250/// the time it predicts the block, and so which a directional mode may read.
3251///
3252/// The decoder derives these from its `BlockDecoded` flags, which are cleared
3253/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
3254/// that map, this reads the answer the same way libaom and rav1e do: for a
3255/// block whose transform covers it whole, whether the samples above its right
3256/// (or below its left) are decoded depends only on where the block sits inside
3257/// its 64x64 superblock, which is a pinned table per block size.
3258#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3259pub(crate) struct Reach {
3260 pub(crate) above_right: bool,
3261 pub(crate) below_left: bool,
3262}
3263
3264/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
3265/// libaom): for a block that is neither in the superblock's top row nor its
3266/// rightmost column, whether the block above and to its right is coded before
3267/// it. Indexed by the block's position in the superblock, in blocks of its own
3268/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
3269/// 128, not this crate's 64 superblock -- bit by bit from the low end.
3270const HAS_TOP_RIGHT: [&[u8]; 4] = [
3271 &[255, 85, 119, 85, 127, 85, 119, 85],
3272 &[95, 87],
3273 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
3274 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
3275 &[
3276 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
3277 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
3278 ],
3279
3280 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
3281 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
3282 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
3283 // with side 4 outside a TX4 split; without their own row they clamped
3284 // into the 8x8 table and read above-right samples the decoder has not
3285 // written yet (all-zero pixels in the bottom-right triangle of a
3286 // directional 4x4 leaf).
3287 &[
3288 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
3289 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
3290 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
3291 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
3292 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
3293 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
3294 119, 119, 119, 119, 85, 85, 85, 85,
3295 ],
3296];
3297
3298/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
3299/// left.
3300const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
3301 &[84, 16, 84, 0, 84, 16, 84, 0],
3302 &[4, 4],
3303 // has_bl_8x8 (libaom av1/common/reconintra.c)
3304 &[
3305 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
3306 84, 85, 16, 17, 84, 85, 0, 0,
3307 ],
3308
3309 // has_bl_4x4 (same source, same order).
3310 &[
3311 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
3312 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,
3313 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
3314 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,
3315 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
3316 85, 85, 0, 0, 0, 0,
3317 ],
3318];
3319
3320/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
3321/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
3322/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
3323/// rather than in raster order, so the bottom-left square's top-right
3324/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
3325/// libaom switches tables on the partition type (`get_has_tr_table`); the
3326/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
3327/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
3328/// lane-part32 r5 caught reading undecoded samples.
3329const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
3330 // has_tr_vert_16x16
3331 &[255, 0, 119, 0, 127, 0, 119, 0],
3332 // has_tr_vert_32x32
3333 &[15, 7],
3334 // has_tr_vert_8x8
3335 &[
3336 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
3337 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
3338 ],
3339];
3340
3341/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
3342const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
3343 // has_bl_vert_16x16
3344 &[254, 16, 254, 0, 254, 16, 254, 0],
3345 // has_bl_vert_32x32
3346 &[14, 14],
3347 // has_bl_vert_8x8
3348 &[
3349 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
3350 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
3351 ],
3352];
3353
3354thread_local! {
3355 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
3356 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
3357 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
3358 /// threading one bool through this crate's already twenty-argument
3359 /// `decode_block` would touch every call site instead of the two arms
3360 /// that need it.
3361 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3362}
3363
3364/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
3365pub(crate) struct VertAbGuard(bool);
3366
3367impl Drop for VertAbGuard {
3368 fn drop(&mut self) {
3369 VERT_AB_PARTITION.with(|c| c.set(self.0));
3370 }
3371}
3372
3373/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
3374/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
3375/// so no byte is retyped). Each is indexed by
3376/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
3377/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
3378/// superblock grid; on this crate's 64-pixel superblock the highest index a
3379/// shape can reach stays inside its own table, so no wrap is involved.
3380///
3381/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
3382/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
3383/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
3384/// 10 of the 21 reachable superblock positions for above-right and 7 for
3385/// below-left.
3386/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3387const 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];
3388/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3389const 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];
3390/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3391const 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];
3392/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3393const 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];
3394/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3395const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119];
3396/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3397const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
3398/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3399const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
3400/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3401const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0];
3402/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3403const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
3404/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3405const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
3406/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3407const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
3408/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3409const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
3410/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3411const HAS_TR_32X64: [u8; 1] = [127];
3412/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3413const HAS_BL_32X64: [u8; 1] = [0];
3414/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3415const HAS_TR_64X32: [u8; 1] = [19];
3416/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3417const HAS_BL_64X32: [u8; 1] = [34];
3418/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3419const 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];
3420/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3421const 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];
3422/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3423const 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];
3424/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3425const 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];
3426/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3427const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
3428/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3429const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
3430/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3431const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
3432/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3433const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
3434/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3435const HAS_TR_16X64: [u8; 2] = [255, 127];
3436/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3437const HAS_BL_16X64: [u8; 2] = [0, 0];
3438/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3439const HAS_TR_64X16: [u8; 2] = [3, 1];
3440/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3441const HAS_BL_64X16: [u8; 2] = [42, 42];
3442
3443/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
3444fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
3445 match (bw, bh) {
3446 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
3447 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
3448 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
3449 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
3450 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
3451 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
3452 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
3453 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
3454 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
3455 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
3456 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
3457 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
3458 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
3459 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
3460 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
3461 }
3462}
3463
3464impl Reach {
3465 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
3466 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
3467 /// own answer is `block` -- a different rule from the standalone-block
3468 /// tables, because a unit's neighbours are mostly its own block's
3469 /// already-reconstructed units:
3470 /// * top-right: available while the unit to the right is still inside
3471 /// the block (`col_off + tx < bw`); otherwise only the block's top row
3472 /// of units reaches past it, through the block-level answer
3473 /// (libaom's `row_off > 0` branch returns exactly
3474 /// `col_off + txw < plane_bw`).
3475 /// * bottom-left: a unit outside the block's left column has none
3476 /// (libaom returns 0 for `col_off > 0`); inside the block
3477 /// (`row_off + tx < bh`) they are the left unit's, already
3478 /// reconstructed; the bottom row falls back to the block-level answer.
3479 pub(crate) fn of_tu(
3480 bw: usize,
3481 bh: usize,
3482 col_off: usize,
3483 row_off: usize,
3484 // The unit's own width and height in pixels; equal for a square
3485 // transform, different for the rect unit a 1:4 strip's first split
3486 // produces (lane-rectsplitx r1).
3487 tx_w: usize,
3488 tx_h: usize,
3489 block: Self,
3490 ) -> Self {
3491 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
3492 // order, so both libaom predicates special-case it (lane-sb128c r10);
3493 // without this the last unit column of every chunk of a 128x64 block
3494 // predicts from a chunk libaom has not decoded yet.
3495 let wide = bw > 64;
3496 Self {
3497 above_right: if row_off > 0 {
3498 // `has_top_right`'s `row_off > 0` branch: the offset is taken
3499 // modulo the 64-wide chunk, except for the one unit whose
3500 // top-right corner is the centre of a 128x128 block.
3501 if wide {
3502 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
3503 } else {
3504 col_off + tx_w < bw
3505 }
3506 } else if col_off + tx_w < bw {
3507 true
3508 } else {
3509 block.above_right
3510 },
3511 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
3512 // `has_bottom_left`: at the left edge of a right-hand chunk
3513 // the bottom-left pixels are in the already-coded left chunk,
3514 // provided they stay inside it.
3515 (row_off % 64) + tx_h < bh.min(64)
3516 } else if col_off > 0 {
3517 false
3518 } else if row_off + tx_h < bh {
3519 true
3520 } else {
3521 block.below_left
3522 },
3523 }
3524 }
3525
3526 /// What a block of `side` samples at `(x, y)` may read past its own edges,
3527 /// in a frame of `width` by `height`.
3528 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
3529 Self {
3530 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
3531 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
3532 }
3533 }
3534
3535 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
3536 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
3537 /// block's own width for the row stride and by its own height for the
3538 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
3539 /// unlike the square [`Self::of`] which uses one `side` for everything.
3540 pub(crate) fn of_rect(
3541 bw: usize,
3542 bh: usize,
3543 x: usize,
3544 y: usize,
3545 width: usize,
3546 height: usize, fctx: &crate::decode::FrameCtx,
3547 ) -> Self {
3548 Self {
3549 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
3550 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
3551 }
3552 }
3553
3554 /// [`Self::of`] for one transform unit of a square block whose transform
3555 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
3556 /// non-zero `row_off`/`col_off`): interior units answer from the block's
3557 /// own geometry, and only a unit on the block's top row (resp. left
3558 /// column) reaches the table -- which is the BLOCK's table read at the
3559 /// BLOCK's position, never a table row for the transform's size. Letting
3560 /// the unit stand in for a block of its own size agrees with libaom for
3561 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
3562 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
3563 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
3564 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
3565 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
3566 /// the transform covering the whole block, luma): everything before the
3567 /// table lookup is that function's own early-exit ladder.
3568 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3569 let sb_mi: usize = reach_sb_px(fctx) / 4;
3570 let (mi_row, mi_col) = (y / 4, x / 4);
3571 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3572 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3573 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3574 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3575 // Top row of the superblock: the top-right pixels are in the (already
3576 // decoded) superblock above.
3577 if blk_row == 0 {
3578 return true;
3579 }
3580 // Rightmost column: they fall in the superblock to the right.
3581 if ((blk_col + 1) << bw_log2) >= sb_mi {
3582 return false;
3583 }
3584 let table = rect_reach_tables(bw, bh).0;
3585 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
3586 }
3587
3588 /// libaom `has_top_right`'s own index arithmetic:
3589 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
3590 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
3591 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
3592 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
3593 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
3594 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
3595 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
3596 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
3597 (blk_row << (5 - bw_log2)) + blk_col
3598 }
3599
3600 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
3601 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3602 let sb_mi: usize = reach_sb_px(fctx) / 4;
3603 let (mi_row, mi_col) = (y / 4, x / 4);
3604 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3605 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3606 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3607 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3608 // Leftmost column of the superblock: the bottom-left pixels are in
3609 // the left superblock iff they stay inside its height.
3610 if blk_col == 0 {
3611 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
3612 }
3613 // Bottom row (and not the leftmost column): they fall in the
3614 // superblock below, which is not decoded yet.
3615 if ((blk_row + 1) << bh_log2) >= sb_mi {
3616 return false;
3617 }
3618 let table = rect_reach_tables(bw, bh).1;
3619 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
3620 }
3621
3622 /// Marks every [`Reach::of`] made until the returned guard drops as being
3623 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
3624 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
3625 /// unaffected: libaom's own comment says vertical rectangles keep their
3626 /// non-vert table, which is what [`Reach::of_rect`] already reads.
3627 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
3628 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
3629 /// can count the sub-block work that partition creates (lane-ab16).
3630 pub(crate) fn in_vert_ab() -> bool {
3631 VERT_AB_PARTITION.with(std::cell::Cell::get)
3632 }
3633
3634 pub(crate) fn vert_ab_partition() -> VertAbGuard {
3635 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
3636 }
3637
3638 /// Neither, which is all a mode that reads no further than its own edges
3639 /// needs.
3640 pub(crate) fn none() -> Self {
3641 Self {
3642 above_right: false,
3643 below_left: false,
3644 }
3645 }
3646
3647 /// `has_top_right` for a block whose transform covers it whole: the top
3648 /// row of a superblock reads into the superblock above, which is decoded;
3649 /// the rightmost column would read into the superblock to the right, which
3650 /// is not; and everything between is the table's to answer.
3651 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3652 let (row, col, per_side) = Self::position(side, x, y, fctx);
3653 if row == 0 {
3654 return true;
3655 }
3656 if col + 1 == per_side {
3657 return false;
3658 }
3659 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
3660 // (the clamp corner-cut that used to live here is gone); sides
3661 // 16/32/64 share row 0 exactly as libaom's tables repeat.
3662 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
3663 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
3664 // -- a reach over-estimate (extra above-right reference pixels),
3665 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
3666 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
3667 // NB: named `table_row`, not `row` -- `row` above is the block's
3668 // position inside the superblock and is what the bit index below
3669 // steps by (a merge that shadowed it desynced every block size).
3670 let table_row = Self::table(side);
3671 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() {
3672 HAS_TOP_RIGHT_VERT[table_row]
3673 } else {
3674 HAS_TOP_RIGHT[table_row]
3675 };
3676 Self::bit(
3677 table,
3678 (row * Self::table_stride(side) + col) % (table.len() * 8),
3679 )
3680 }
3681
3682 /// `has_bottom_left` for such a block: the leftmost column of a superblock
3683 /// reads into the superblock to its left, which is decoded only as far
3684 /// down as its own bottom; the bottom row would read into the superblock
3685 /// below, which is not decoded at all; and the table answers the rest.
3686 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3687 let (row, col, per_side) = Self::position(side, x, y, fctx);
3688 if col == 0 {
3689 return row * side + side < reach_sb_px(fctx);
3690 }
3691 if row + 1 == per_side {
3692 return false;
3693 }
3694 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
3695 // (the clamp corner-cut that used to live here is gone); sides
3696 // 16/32/64 share row 0 exactly as libaom's tables repeat.
3697 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
3698 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
3699 // -- a reach over-estimate (extra above-right reference pixels),
3700 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
3701 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
3702 // NB: named `table_row`, not `row` -- `row` above is the block's
3703 // position inside the superblock and is what the bit index below
3704 // steps by (a merge that shadowed it desynced every block size).
3705 let table_row = Self::table(side);
3706 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() {
3707 HAS_BOTTOM_LEFT_VERT[table_row]
3708 } else {
3709 HAS_BOTTOM_LEFT[table_row]
3710 };
3711 Self::bit(
3712 table,
3713 (row * Self::table_stride(side) + col) % (table.len() * 8),
3714 )
3715 }
3716
3717 /// Where a block sits inside its superblock, in blocks of its own size,
3718 /// and how many of them a superblock is across.
3719 fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
3720 let sb = reach_sb_px(fctx);
3721 ((y % sb) / side, (x % sb) / side, sb / side)
3722 }
3723
3724 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
3725 /// these tables to its compile-time maximum superblock (128, spec
3726 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
3727 /// size an encode actually uses, so a block's row in the bit index steps
3728 /// by 128 / `side` even though this crate only ever codes a 64
3729 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
3730 /// here instead indexes the wrong bit for every block size but the one
3731 /// where 64 and 128 give the same stride.
3732 fn table_stride(side: usize) -> usize {
3733 128 / side
3734 }
3735
3736 /// Which of the three block sizes the encoder codes a table row is for.
3737 fn table(side: usize) -> usize {
3738 if side == BLOCK {
3739 1
3740 } else if side == 8 {
3741 2
3742 } else if side == 4 {
3743 3
3744 } else {
3745 0
3746 }
3747 }
3748
3749 /// One bit of a table, counting from the low end of its first byte.
3750 fn bit(table: &[u8], index: usize) -> bool {
3751 (table[index / 8] >> (index % 8)) & 1 != 0
3752 }
3753}
3754
3755/// What one symbol costs against a CDF, in bits.
3756/// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the
3757/// search, the frame header's `allow_warped_motion` and the sequence's
3758/// `enable_warped_motion`, all three together. ON by default since
3759/// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at
3760/// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
3761/// bits -- back off for an A/B on one build.
3762pub(crate) fn warp_on() -> bool {
3763 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
3764 crate::envflags::var("EC_AV1_WARP").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
3765 });
3766 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
3767}
3768
3769/// The smallest LEAF an OBMC candidate is offered for, so the census can
3770/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
3771/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
3772/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
3773///
3774/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
3775/// (12 frames, four quantizers, the standing keep table):
3776///
3777/// | min side | film 1080p | film 2160p | screen |
3778/// |---|---|---|---|
3779/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
3780/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
3781/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
3782/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
3783///
3784/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
3785/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
3786/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
3787/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
3788/// that wins the local RD on five blocks in six and loses ladder bytes is
3789/// the `local-RD-on-references` class again, not a missing footprint.
3790///
3791/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
3792/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
3793/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
3794/// loss on the 1080p film became a 0.3-point win and the other two rows went
3795/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
3796/// of the "local win, ladder loss" it was charged with was the rate weight.
3797/// It still does not meet the keep rule (two down, one flat, both columns).
3798/// The tool stays OFF by default; the upgrade path is the price, not the size
3799/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
3800/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
3801/// 1080p film up, i.e. the same disagreement between the two gates).
3802///
3803/// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept
3804/// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1,
3805/// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads
3806/// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p
3807/// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference
3808/// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at
3809/// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and
3810/// the margin's gain are the same bytes. It stays OFF.
3811///
3812/// RE-MEASURED on lane-obmc3 (2026-09-08) on the REAL film rows -- every
3813/// judgement above was taken when the gate's "film" rows were the `testsrc2`
3814/// COLOUR BARS fixtures (class `gate film rows are colour bars`), so this is
3815/// the first OBMC measurement on film. BD vs libaom / vs rav1e, 12 pictures,
3816/// the standing native keep table (`bd_rate_screen_native`):
3817///
3818/// | arm | film A | film B | screen | OBMC fire A/B |
3819/// |---|---|---|---|---|
3820/// | off (control) | +21.7 / -4.4 | +26.9 / -0.6 | +20.1 / -30.4 | 0% / 0% |
3821/// | min side 8 | +21.7 / -4.3 | +27.2 / -0.3 | +20.0 / -30.4 | 15.5% / 9.7% |
3822/// | min side 16 | +21.5 / -4.5 | +27.6 / +0.1 | +20.1 / -30.4 | 10.0% / 6.9% |
3823///
3824/// and on the LONG-GOP gate (`bd_rate_film_long_gop`, 48 pictures, film B
3825/// only), where the anchors' non-skip area is the known gap:
3826///
3827/// | arm | film B long GOP | wall ours |
3828/// |---|---|---|
3829/// | off (control) | +89.8 / +9.1 | 477.5s |
3830/// | min side 8 | +89.6 / +9.0 | 514.1s |
3831///
3832/// The two gates disagree in SIGN on film B -- 0.3/0.3 worse over 12
3833/// pictures, 0.2/0.1 better over 48 -- and film A moves 0.2/0.1 the good way
3834/// only at min side 16, which is exactly where film B loses 0.7 on both
3835/// columns. Nothing here meets the keep rule (both films down on both
3836/// columns, or one down >=0.5 with the other flat), and the long-GOP gain
3837/// costs +7.7% wall. OBMC stays OFF at every preset.
3838fn obmc_min_side() -> usize {
3839 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
3840 *N.get_or_init(|| {
3841 std::env::var("EC_AV1_OBMC_MIN")
3842 .ok()
3843 .and_then(|v| v.parse().ok())
3844 .unwrap_or(8)
3845 })
3846}
3847
3848/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
3849/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
3850/// same frame-CDF price the coefficients of a non-screen frame are estimated
3851/// with, not the static default table.
3852/// The same price for whichever alphabet the writer will really use for this
3853/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
3854/// (`allow_warped_motion` and at least one warp sample), otherwise the
3855/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
3856/// search pay it, so the alphabet cancels out of a comparison and only its
3857/// per-value spread decides.
3858fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
3859 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
3860 return 0.0;
3861 };
3862 match warp_alphabet {
3863 true => crate::tile::motion_mode_symbol_bits(row, motion),
3864 false => crate::tile::obmc_symbol_bits(row, motion == 1),
3865 }
3866}
3867
3868/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
3869/// candidate, the header's `allow_warped_motion` and the sequence's
3870/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
3871/// native keep table, against the same build with the knob off:
3872///
3873/// | clip | warp on | off |
3874/// |---|---|---|
3875/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
3876/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
3877/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
3878///
3879/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
3880/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
3881/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
3882/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
3883/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
3884/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
3885/// this is a measured loss, not an inert knob. Same shape as the OBMC
3886/// candidate above it (`obmc_min_side`): a local RD win that does not convert
3887/// into ladder bytes.
3888///
3889/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
3890/// because a tool whose gain is local and whose cost is the rate it adds is
3891/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
3892///
3893/// | clip | warp on | off (both at lambda 0.05) |
3894/// |---|---|---|
3895/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
3896/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
3897/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
3898///
3899/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
3900/// column inside 0.1 everywhere -- which reads as a keep rather than the
3901/// 0.7/0.9 loss it was.
3902///
3903/// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table
3904/// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5,
3905/// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and
3906/// ran the conformance shape the lambda lane deferred: every warp stream
3907/// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1`
3908/// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside
3909/// a 16-tile frame, sample walk and all), and tile bytes still do not depend
3910/// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks
3911/// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it,
3912/// `allow_warped_motion` and `enable_warped_motion` back off together.
3913///
3914/// The WARPED_CAUSAL prediction of one square single-reference block: the
3915/// decoder's own warp-sample walk (`decode::find_samples` +
3916/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
3917/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
3918/// grid -- never a second implementation of any of the three. `None` when the
3919/// block would code no motion_mode symbol at all, when it has no warp sample
3920/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
3921/// or when the projection is not filter-representable (the decoder would then
3922/// predict translationally, so the mode is pure cost).
3923#[allow(clippy::too_many_arguments)]
3924fn warp_prediction(
3925 grid: &MiGrid,
3926 (mi_row, mi_col): (usize, usize),
3927 (mi_rows, mi_cols): (usize, usize),
3928 (x, y): (usize, usize),
3929 side: usize,
3930 mv: (i32, i32),
3931 ref_frame: i8,
3932 ref_planes: [(&[u16], usize, usize, usize); 3],
3933 fctx: &crate::decode::FrameCtx,
3934) -> Option<[Vec<u8>; 3]> {
3935 let n4 = side / 4;
3936 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
3937 return None;
3938 }
3939 let mut samples = crate::decode::find_samples(
3940 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
3941 );
3942 if samples.is_empty() {
3943 return None;
3944 }
3945 if samples.len() > 1 {
3946 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
3947 }
3948 let params = crate::warp::find_projection(
3949 &samples,
3950 side as i32,
3951 side as i32,
3952 mv.1,
3953 mv.0,
3954 mi_row as i32,
3955 mi_col as i32,
3956 )?;
3957 let mut pred = [
3958 vec![0u16; side * side],
3959 vec![0u16; side * side / 4],
3960 vec![0u16; side * side / 4],
3961 ];
3962 // The translational prediction first, exactly as the decoder builds it,
3963 // then the affine one over the planes whose OWN block is at least 8x8
3964 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
3965 // 4x4 chroma stays translational).
3966 for (i, r) in ref_planes.into_iter().enumerate() {
3967 let luma_plane = i == 0;
3968 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
3969 let s = if luma_plane { side } else { side / 2 };
3970 mc::predict(
3971 r.0,
3972 r.1,
3973 r.2,
3974 r.3,
3975 mv_to_q4(px, mv.1, luma_plane),
3976 mv_to_q4(py, mv.0, luma_plane),
3977 s,
3978 s,
3979 &mut pred[i],
3980 fctx,
3981 );
3982 if crate::decode::warp_plane_allowed(s, s) {
3983 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
3984 crate::warp::warp_affine(
3985 &params,
3986 r.0,
3987 r.2 as i32,
3988 r.3 as i32,
3989 r.1 as i32,
3990 &mut pred[i],
3991 px as i32,
3992 py as i32,
3993 cside,
3994 cside,
3995 cside,
3996 sub,
3997 sub,
3998 fctx,
3999 );
4000 }
4001 }
4002 let [py_buf, pu_buf, pv_buf] = pred;
4003 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
4004 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
4005}
4006
4007/// What tile.rs' `write_compound_ref_frames` pays for the pair
4008/// `(ref0, ref1)`, symbol for symbol, each at the context its own
4009/// `single_ref_p*_ctx`/`uni_comp_ref_p1_ctx`/`comp_reference_type_ctx`
4010/// derives from the block's above/left neighbours -- plus the `comp_mode`
4011/// symbol itself at `reference_mode_ctx`.
4012///
4013/// Before lane-ctx this was four constants at CDF row 0 that assumed the pair
4014/// was LAST+GOLDEN or LAST+ALTREF: `comp_bwdref[0][0] = 1` prices a BWDREF or
4015/// ALTREF2 partner as ALTREF and drops its `p6` symbol entirely, and the
4016/// `uni_comp_ref` leaves price a LAST+LAST2 pair as LAST+GOLDEN.
4017pub(crate) fn compound_ref_bits(
4018 (ref0, ref1): (i8, i8),
4019 stack: &crate::mvstack::MvStack,
4020) -> f64 {
4021 use crate::mvstack::{
4022 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4023 comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx,
4024 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
4025 uni_comp_ref_p1_ctx,
4026 };
4027 let (a, a1) = stack.above_refs;
4028 let (l, l1) = stack.left_refs;
4029 let unidir = is_uni_comp_ref(ref0, ref1);
4030 let comp_mode = symbol_bits(
4031 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4032 1,
4033 );
4034 let ref_type = symbol_bits(
4035 &cdf::COMP_REF_TYPE[comp_reference_type_ctx(stack.above_nbr, stack.left_nbr)],
4036 usize::from(!unidir),
4037 );
4038 if unidir {
4039 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
4040 let p0 = symbol_bits(
4041 &cdf::UNI_COMP_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4042 usize::from(both_backward),
4043 );
4044 if both_backward {
4045 return comp_mode + ref_type + p0;
4046 }
4047 let past_last2 = ref1 != LAST2_FRAME;
4048 let p1 = symbol_bits(
4049 &cdf::UNI_COMP_REF[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
4050 usize::from(past_last2),
4051 );
4052 let p2 = if past_last2 {
4053 symbol_bits(
4054 &cdf::UNI_COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4055 usize::from(ref1 == GOLDEN_FRAME),
4056 )
4057 } else {
4058 0.0
4059 };
4060 return comp_mode + ref_type + p0 + p1 + p2;
4061 }
4062 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
4063 let fwd = symbol_bits(
4064 &cdf::COMP_REF[single_ref_p3_ctx(a, a1, l, l1)][0],
4065 usize::from(far),
4066 ) + if far {
4067 symbol_bits(
4068 &cdf::COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4069 usize::from(ref0 == GOLDEN_FRAME),
4070 )
4071 } else {
4072 symbol_bits(
4073 &cdf::COMP_REF[single_ref_p4_ctx(a, a1, l, l1)][1],
4074 usize::from(ref0 == LAST2_FRAME),
4075 )
4076 };
4077 let is_altref = ref1 == ALTREF_FRAME;
4078 let bwd = symbol_bits(
4079 &cdf::COMP_BWDREF[single_ref_p2_ctx(a, a1, l, l1)][0],
4080 usize::from(is_altref),
4081 ) + if is_altref {
4082 0.0
4083 } else {
4084 symbol_bits(
4085 &cdf::COMP_BWDREF[single_ref_p6_ctx(a, a1, l, l1)][1],
4086 usize::from(ref1 == ALTREF2_FRAME),
4087 )
4088 };
4089 comp_mode + ref_type + fwd + bwd
4090}
4091
4092/// What the `skip` symbol costs at the context tile.rs really codes it with
4093/// (`above_skip[mi_c] + left_skip[mi_r]`, the two cells the MV stack now
4094/// carries) instead of row 0 -- the pricer's skip-versus-residual margin is
4095/// exactly the difference between this symbol's two values, so the row it is
4096/// read from moves that decision (class pricer-context-zero, lane-ctx).
4097pub(crate) fn skip_bits_at(stack: &crate::mvstack::MvStack, skip: bool) -> f64 {
4098 let ctx = usize::from(stack.above_skip) + usize::from(stack.left_skip);
4099 symbol_bits(&cdf::SKIP[ctx], usize::from(skip))
4100}
4101
4102/// What the `is_inter` symbol costs at tile.rs' own `intra_inter_ctx` -- the
4103/// neighbours' intra/inter state, with an out-of-tile side contributing
4104/// nothing, off the same two cells (lane-ctx).
4105pub(crate) fn intra_inter_bits_at(stack: &crate::mvstack::MvStack, inter: bool) -> f64 {
4106 let ctx = crate::tile::intra_inter_ctx(
4107 stack.above_nbr.is_some(),
4108 stack.left_nbr.is_some(),
4109 stack.above_nbr.is_some_and(|n| n.is_inter),
4110 stack.left_nbr.is_some_and(|n| n.is_inter),
4111 );
4112 symbol_bits(&cdf::INTRA_INTER[ctx], usize::from(inter))
4113}
4114
4115/// The `comp_mode = 0` symbol tile.rs' `write_comp_mode` codes ahead of a
4116/// SINGLE-reference block's reference syntax, at `reference_mode_ctx`'s own
4117/// context -- zero on a frame that carries no `reference_select` bit, where
4118/// the writer codes no symbol at all.
4119fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 {
4120 if !reference_select() {
4121 return 0.0;
4122 }
4123 symbol_bits(
4124 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4125 0,
4126 )
4127}
4128
4129/// What tile.rs' `write_single_ref` pays for `ref_frame`, symbol for symbol,
4130/// each at the context that symbol's own `single_ref_p*_ctx` derives from the
4131/// block's above/left neighbours -- plus the `comp_mode = 0` symbol
4132/// `write_comp_mode` codes ahead of it on a `reference_select` frame.
4133/// LAST is p1=0,p3=0,p4=0,
4134/// LAST2 p1=0,p3=0,p4=1, LAST3 p1=0,p3=1,p5=0, GOLDEN p1=0,p3=1,p5=1,
4135/// BWDREF p1=1,p2=0,p6=0, ALTREF2 p1=1,p2=0,p6=1 and ALTREF p1=1,p2=1.
4136/// Before lane-pricer every BACKWARD reference was priced as LAST -- three
4137/// symbols off the wrong CDFs -- which is what made the search believe an
4138/// ALTREF block cost the same syntax as a LAST one. The `comp_mode` term is
4139/// lane-ctx2's: a compound candidate paid `comp_mode = 1` while a single one
4140/// paid nothing at all, so compound was overcharged by the whole symbol.
4141pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 {
4142 use crate::mvstack::{
4143 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4144 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
4145 single_ref_p5_ctx, single_ref_p6_ctx,
4146 };
4147 let (a, a1) = stack.above_refs;
4148 let (l, l1) = stack.left_refs;
4149 let comp_mode = comp_mode_single_bits(stack);
4150 let backward = ref_frame >= BWDREF_FRAME;
4151 let p1 = symbol_bits(
4152 &cdf::SINGLE_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4153 usize::from(backward),
4154 );
4155 if backward {
4156 let is_altref = ref_frame == ALTREF_FRAME;
4157 let p2 = symbol_bits(
4158 &cdf::SINGLE_REF[single_ref_p2_ctx(a, a1, l, l1)][1],
4159 usize::from(is_altref),
4160 );
4161 return comp_mode
4162 + p1
4163 + p2
4164 + if is_altref {
4165 0.0
4166 } else {
4167 symbol_bits(
4168 &cdf::SINGLE_REF[single_ref_p6_ctx(a, a1, l, l1)][5],
4169 usize::from(ref_frame == ALTREF2_FRAME),
4170 )
4171 };
4172 }
4173 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
4174 comp_mode + p1 + symbol_bits(
4175 &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2],
4176 usize::from(far),
4177 ) + if far {
4178 symbol_bits(
4179 &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4],
4180 usize::from(ref_frame == GOLDEN_FRAME),
4181 )
4182 } else {
4183 symbol_bits(
4184 &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3],
4185 usize::from(ref_frame == LAST2_FRAME),
4186 )
4187 }
4188}
4189
4190pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
4191 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
4192 let width = cdf[symbol] - low;
4193 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
4194 // 32769 prices a symbol can carry; the `log2` behind each is computed
4195 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
4196 // profile -- this function is called for every symbol of every candidate
4197 // the RD search prices). Each entry is exactly the expression this used
4198 // to evaluate, so every price is bit-identical.
4199 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
4200 PRICES.get_or_init(|| {
4201 (0..=32768u32)
4202 .map(|w| -(f64::from(w) / 32768.0).log2())
4203 .collect()
4204 })[usize::from(width)]
4205}
4206
4207/// What the tile writer spends to say a block is coded in each of the thirteen
4208/// modes, given the modes of the blocks above it and to its left: the luma mode
4209/// symbol against the CDF those two neighbours pick, the angle delta a
4210/// directional mode carries, and the chroma mode symbol, whose CDF the luma
4211/// mode itself indexes.
4212///
4213/// Without this the search is blind to what a mode costs to name, which is not
4214/// a rounding error: a directional mode on a picture that does not run that way
4215/// is a rate loss the squared error never sees.
4216/// Codes one square of the picture as a single block: searches the luma mode,
4217/// codes both chroma planes DC, and hands back the block and what it cost --
4218/// squared error plus lambda times the bits its symbols spend.
4219/// How many halvings of a `side`-square block's transform the `tx_depth`
4220/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
4221/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
4222fn max_tx_depth(side: usize) -> usize {
4223 match side {
4224 8 => 1,
4225 16 | 32 => 2,
4226 _ => 0,
4227 }
4228}
4229
4230/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
4231/// Priced at context row 0 -- the writer picks the real row from its
4232/// neighbours' transform sizes, which the search has no view of; the term is
4233/// the same for every depth of one block either way, so it only shifts the
4234/// depth-0-versus-split margin, never the ordering between two splits.
4235fn tx_depth_bits(side: usize, depth: usize) -> f64 {
4236 match side {
4237 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
4238 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
4239 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
4240 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
4241 }
4242}
4243
4244/// lane-split: a multiplier on the RATE term of the transform-SPLIT trial
4245/// only -- the intra `tx_depth` depth>0 candidates in [`code_square`] and the
4246/// inter var-tx depth-1 trial in [`commit_inter_luma`]. `1.0` is the control
4247/// (the mode search's own weight); below 1 the split trial is charged less
4248/// for its bits and fires more often.
4249///
4250/// The knob the class `rd-rate-term-calibration` asks for: lane-txd made the
4251/// `tx_depth` SYMBOL price correct and every film row got worse, because the
4252/// correct row is a one-sided push away from splitting (depth 0 up to 1.5
4253/// bits cheaper at ctx 2, which is 66% of an inter frame's intra blocks) --
4254/// so what is mis-calibrated is the weight the split's rate is judged under,
4255/// not the price. `EC_AV1_SPLIT_LAMBDA`.
4256pub(crate) fn split_lambda_mult() -> f64 {
4257 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4258 crate::envflags::var("EC_AV1_SPLIT_LAMBDA")
4259 .ok()
4260 .and_then(|v| v.parse().ok())
4261 .unwrap_or(SPLIT_LAMBDA)
4262 });
4263 *M
4264}
4265
4266/// The shipped value of [`split_lambda_mult`]. See lanes/split.report.md for
4267/// the sweep that chose it.
4268const SPLIT_LAMBDA: f64 = 1.0;
4269
4270/// lane-split census (`EC_AV1_SPLIT_CENSUS=1`): the split decision itself,
4271/// bucketed by site (0 = intra `tx_depth`, 1 = inter var-tx), frame type
4272/// (0 = key, 1 = inter) and block side (8/16/32/64). Ten counters per bucket:
4273/// trials offered, trials the split won, then the (rate, distortion) of the
4274/// split and flat arms summed apart for the split-won and flat-won trials --
4275/// rate scaled by 64 into an integer counter, as [`TXRD_STATS`] is.
4276static SPLIT_CENSUS: [std::sync::atomic::AtomicU64; 160] =
4277 [const { std::sync::atomic::AtomicU64::new(0) }; 160];
4278
4279/// Whether [`SPLIT_CENSUS`] is armed, read once.
4280pub(crate) fn split_census_on() -> bool {
4281 static ON: std::sync::LazyLock<bool> =
4282 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_SPLIT_CENSUS"));
4283 *ON
4284}
4285
4286/// Where one (site, frame type, block side) bucket starts in [`SPLIT_CENSUS`].
4287/// Sides below 8 and above 64 fold into the end rows, which no caller offers.
4288fn split_census_base(site: usize, key: bool, side: usize) -> usize {
4289 let side_idx = (side.trailing_zeros() as usize).saturating_sub(3).min(3);
4290 ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10
4291}
4292
4293/// Records one split trial into [`SPLIT_CENSUS`]. `split` and `flat` are each
4294/// `(rate in bits, distortion as squared error)`.
4295fn split_census(
4296 site: usize,
4297 key: bool,
4298 side: usize,
4299 split_won: bool,
4300 split: (f64, f64),
4301 flat: (f64, f64),
4302) {
4303 use std::sync::atomic::Ordering::Relaxed;
4304 let base = split_census_base(site, key, side);
4305 let add = |i: usize, v: u64| {
4306 SPLIT_CENSUS[base + i].fetch_add(v, Relaxed);
4307 };
4308 add(0, 1);
4309 let off = if split_won {
4310 add(1, 1);
4311 2
4312 } else {
4313 6
4314 };
4315 let (win, lose) = if split_won { (split, flat) } else { (flat, split) };
4316 add(off, (win.0 * 64.0).max(0.0) as u64);
4317 add(off + 1, win.1.max(0.0) as u64);
4318 add(off + 2, (lose.0 * 64.0).max(0.0) as u64);
4319 add(off + 3, lose.1.max(0.0) as u64);
4320}
4321
4322/// Prints [`SPLIT_CENSUS`] to stderr when `EC_AV1_SPLIT_CENSUS=1`. Called at
4323/// the end of every `Av1Encoder::encode_frames` call and NOT reset, so the
4324/// last table a run prints is the whole encode's total (there is no flush
4325/// hook the encoder API guarantees to reach).
4326pub(crate) fn dump_split_census() {
4327 use std::sync::atomic::Ordering::Relaxed;
4328 eprintln!(
4329 "SPLITCENSUS site frame side offered split share% \
4330 win_rate win_dist lose_rate lose_dist"
4331 );
4332 for site in 0..2 {
4333 for key in [true, false] {
4334 for side_idx in 0..4 {
4335 let base = split_census_base(site, key, 8 << side_idx);
4336 let v: [u64; 10] = std::array::from_fn(|i| SPLIT_CENSUS[base + i].load(Relaxed));
4337 if v[0] == 0 {
4338 continue;
4339 }
4340 let (n, s) = (v[0] as f64, v[1] as f64);
4341 // Winner terms live at 2,3 (split won) and 6,7 (flat won),
4342 // loser terms at 4,5 and 8,9 -- so each mean is one sum over
4343 // all `n` trials, not a mean of two means.
4344 eprintln!(
4345 "SPLITCENSUS {} {} {:>3} {:>7} {:>7} {:>5.1} \
4346 {:>9.2} {:>9.0} {:>9.2} {:>9.0}",
4347 if site == 0 { "intra" } else { "inter" },
4348 if key { "key " } else { "inter" },
4349 8 << side_idx,
4350 v[0],
4351 v[1],
4352 100.0 * s / n,
4353 (v[2] + v[6]) as f64 / n / 64.0,
4354 (v[3] + v[7]) as f64 / n,
4355 (v[4] + v[8]) as f64 / n / 64.0,
4356 (v[5] + v[9]) as f64 / n,
4357 );
4358 }
4359 }
4360 }
4361}
4362
4363/// lane-newmv: a multiplier on the mv RATE term of the BLOCK-level inter
4364/// decision only -- the `NEWMV` candidate's own mv residual + DRL bits, not
4365/// its mode/reference syntax and not the search's own cost function
4366/// ([`crate::motion`]'s `EC_AV1_MV_SEARCH_LAMBDA` is that one). `1.0` is the
4367/// control; below 1 a coded vector is charged less and `NEWMV` wins more
4368/// blocks. `EC_AV1_MV_LAMBDA`, class `rd-rate-term-calibration`.
4369pub(crate) fn mv_lambda_mult() -> f64 {
4370 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4371 crate::envflags::var("EC_AV1_MV_LAMBDA")
4372 .ok()
4373 .and_then(|v| v.parse().ok())
4374 .unwrap_or(MV_LAMBDA)
4375 });
4376 *M
4377}
4378
4379/// The shipped value of [`mv_lambda_mult`]. See lanes/newmv.report.md.
4380const MV_LAMBDA: f64 = 1.0;
4381
4382/// What a `NEWMV` candidate is charged ON TOP of its own priced mv syntax
4383/// bits, `(EC_AV1_MV_LAMBDA - 1) * mv_bits` (added to the candidate's bits,
4384/// which the RD cost multiplies by lambda). Zero at the default weight.
4385fn mv_rate_surcharge(mv_bits: f64) -> f64 {
4386 (mv_lambda_mult() - 1.0) * mv_bits
4387}
4388
4389/// lane-newmv census (`EC_AV1_NEWMV_CENSUS=1`): the block-level `NEWMV`
4390/// decision, bucketed by block side (8/16/32/64). Eight counters per bucket:
4391/// 0 blocks that ran a `LAST` motion search, 1 of those whose vector the
4392/// writer could name (offered to RD), 2 blocks `NEWMV` won, 3 the summed RD
4393/// cost it won by, 4 the summed cost it lost by, 5 the summed
4394/// `|mv - nearest_mv|` (1/8-pel units, both axes), 6 blocks whose searched
4395/// vector IS the stack's `NEARESTMV`, 7 the summed mv syntax bits (x64, as
4396/// [`SPLIT_CENSUS`]'s rate terms are). Four globals follow at 32: extra-
4397/// reference searches offered/skipped by [`EXTRA_NEW_SKIP_MARGIN`], leaf
4398/// second-reference searches offered/skipped by [`LEAF_SECOND_NEW_MARGIN`].
4399static NEWMV_CENSUS: [std::sync::atomic::AtomicU64; 36] =
4400 [const { std::sync::atomic::AtomicU64::new(0) }; 36];
4401
4402/// Whether [`NEWMV_CENSUS`] is armed, read once.
4403pub(crate) fn newmv_census_on() -> bool {
4404 static ON: std::sync::LazyLock<bool> =
4405 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_NEWMV_CENSUS"));
4406 *ON
4407}
4408
4409/// Bumps one of [`NEWMV_CENSUS`]'s four global counters (32..36).
4410fn newmv_census_global(i: usize) {
4411 if newmv_census_on() {
4412 NEWMV_CENSUS[32 + i].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4413 }
4414}
4415
4416/// Records one block's `NEWMV` decision into [`NEWMV_CENSUS`]. `other_cost`
4417/// is the best cost the block had WITHOUT the `NEWMV` candidate (its
4418/// `NEAREST`/`NEAR`/`GLOBAL`/intra winner), `new_cost` the `NEWMV`
4419/// candidate's own; both `f64::INFINITY` is a block that offered neither.
4420fn newmv_census_block(
4421 side: usize,
4422 offered: bool,
4423 new_cost: f64,
4424 other_cost: f64,
4425 mv: (i32, i32),
4426 nearest: (i32, i32),
4427 mv_bits: f64,
4428) {
4429 if !newmv_census_on() {
4430 return;
4431 }
4432 use std::sync::atomic::Ordering::Relaxed;
4433 let base = (side.trailing_zeros() as usize).saturating_sub(3).min(3) * 8;
4434 let add = |i: usize, v: u64| {
4435 NEWMV_CENSUS[base + i].fetch_add(v, Relaxed);
4436 };
4437 add(0, 1);
4438 if !offered {
4439 return;
4440 }
4441 add(1, 1);
4442 if new_cost < other_cost {
4443 add(2, 1);
4444 add(3, (other_cost - new_cost).max(0.0) as u64);
4445 } else {
4446 add(4, (new_cost - other_cost).max(0.0) as u64);
4447 }
4448 add(5, ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64);
4449 if mv == nearest {
4450 add(6, 1);
4451 }
4452 add(7, (mv_bits * 64.0).max(0.0) as u64);
4453}
4454
4455/// Prints [`NEWMV_CENSUS`] to stderr when `EC_AV1_NEWMV_CENSUS=1`, on the
4456/// same guard [`dump_split_census`] rides (cumulative, so the last table a
4457/// run prints is the whole encode's).
4458pub(crate) fn dump_newmv_census() {
4459 use std::sync::atomic::Ordering::Relaxed;
4460 eprintln!(
4461 "NEWMVCENSUS side searched offered won won% win_margin lose_margin \
4462 mv_dist_q3 mv==nearest% mv_bits"
4463 );
4464 for side_idx in 0..4 {
4465 let base = side_idx * 8;
4466 let v: [u64; 8] = std::array::from_fn(|i| NEWMV_CENSUS[base + i].load(Relaxed));
4467 if v[0] == 0 {
4468 continue;
4469 }
4470 let off = v[1].max(1) as f64;
4471 eprintln!(
4472 "NEWMVCENSUS {:>3} {:>8} {:>8} {:>7} {:>5.1} {:>10.0} {:>11.0} {:>10.2} {:>12.1} {:>7.2}",
4473 8 << side_idx,
4474 v[0],
4475 v[1],
4476 v[2],
4477 100.0 * v[2] as f64 / off,
4478 v[3] as f64 / v[2].max(1) as f64,
4479 v[4] as f64 / (v[1] - v[2]).max(1) as f64,
4480 v[5] as f64 / off,
4481 100.0 * v[6] as f64 / off,
4482 v[7] as f64 / off / 64.0,
4483 );
4484 }
4485 let g: [u64; 4] = std::array::from_fn(|i| NEWMV_CENSUS[32 + i].load(Relaxed));
4486 eprintln!(
4487 "NEWMVCENSUS pre-RD margin skips: extra-reference {}/{} ({:.1}%), \
4488 leaf second reference {}/{} ({:.1}%)",
4489 g[1],
4490 g[0],
4491 100.0 * g[1] as f64 / g[0].max(1) as f64,
4492 g[3],
4493 g[2],
4494 100.0 * g[3] as f64 / g[2].max(1) as f64,
4495 );
4496 let [calls, evals, _subpel, rounds, near_pred, unmoved, widest, widest_moves] =
4497 crate::motion::take_census();
4498 let per = |n: u64| n as f64 / calls.max(1) as f64;
4499 eprintln!(
4500 "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \
4501 winner within +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%, \
4502 moved at the WIDEST step {:.1}% of calls ({:.2} such moves/call)",
4503 per(evals),
4504 per(rounds),
4505 100.0 * near_pred as f64 / calls.max(1) as f64,
4506 100.0 * unmoved as f64 / calls.max(1) as f64,
4507 100.0 * widest as f64 / calls.max(1) as f64,
4508 per(widest_moves),
4509 );
4510}
4511
4512/// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
4513/// the intra witness's fire count stays its own.
4514pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
4515 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
4516
4517/// lane-txrd: a multiplier on the rate term of the TRANSFORM-TYPE decision
4518/// only (`EC_AV1_TXRD_LAMBDA`, default 1.0 = the mode search's own weight).
4519/// `0` compares types on reconstruction error alone, which is what separates
4520/// a rate-term calibration (class `rd-rate-term-calibration`) from a
4521/// distortion the trial mis-measures.
4522pub(crate) fn tx_type_lambda_mult() -> f64 {
4523 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4524 crate::envflags::var("EC_AV1_TXRD_LAMBDA")
4525 .ok()
4526 .and_then(|v| v.parse().ok())
4527 .unwrap_or(1.0)
4528 });
4529 *M
4530}
4531
4532/// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own
4533/// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the
4534/// default weight of 1 and for `DCT_DCT` itself. The instrument the film
4535/// question needs: at weight 1 the five-type intra search spends 1.2% more
4536/// bytes for 0.04 dB on both film rows, so what it under-charges is the rate
4537/// of the type it picks.
4538pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 {
4539 if tx_type == TxType::DctDct {
4540 0.0
4541 } else {
4542 lambda * (tx_type_lambda_mult() - 1.0) * bits
4543 }
4544}
4545
4546/// lane-txrd instrument: over the FLAT inter luma decision, the summed
4547/// reconstruction error and priced bits of the type the search chose against
4548/// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an
4549/// integer counter. `EC_AV1_TXRD_CENSUS`.
4550pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [
4551 std::sync::atomic::AtomicU64::new(0),
4552 std::sync::atomic::AtomicU64::new(0),
4553 std::sync::atomic::AtomicU64::new(0),
4554 std::sync::atomic::AtomicU64::new(0),
4555 std::sync::atomic::AtomicU64::new(0),
4556 std::sync::atomic::AtomicU64::new(0),
4557 std::sync::atomic::AtomicU64::new(0),
4558];
4559
4560/// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib
4561/// build would warn `dead_code` (class from lane-txset2's `coeff_bits`).
4562#[cfg(test)]
4563pub(crate) fn take_txrd_stats() -> [u64; 7] {
4564 std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
4565}
4566
4567/// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
4568#[cfg(test)]
4569pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
4570 std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
4571}
4572
4573/// How many luma transform units resolved to each [`TxType`], indexed by the
4574/// enum's own discriminant (lane-txset): the fire count a witness asserts on,
4575/// and the instrument that says which types the search actually reaches.
4576pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
4577 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
4578
4579/// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the
4580/// counts to its own encode.
4581#[cfg(test)]
4582pub(crate) fn take_tx_type_hits() -> [usize; 16] {
4583 std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
4584}
4585
4586/// How many blocks resolved to each `tx_depth`, the fire count that says
4587/// whether the depth search below reaches its candidates at all.
4588static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
4589 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
4590
4591/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
4592/// to its own encode.
4593#[cfg(test)]
4594pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
4595 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
4596}
4597
4598/// How many inter blocks resolved to each var-tx depth (0 = one transform
4599/// over the whole block, 1 = its four halves), the fire count a gate prints
4600/// to see the split search reach its candidates at all. Indexed
4601/// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census
4602/// says which of the four block classes the split reaches -- the 32x32 root
4603/// and the compound blocks are this lane's two new ones.
4604static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
4605 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
4606
4607/// Whether a 32x32 inter winner searches its own var-tx depth (the four
4608/// 16x16 units against the flat transform) instead of coding depth 0 blind.
4609/// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off.
4610///
4611/// Rejected three times on the bars rows of the native gate (flat to +0.3).
4612/// lane-av1resweep re-judged it on the two REAL film crops at
4613/// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file
4614/// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`):
4615///
4616/// | clip | shipped | tx32 depth | + [`compound_var_tx`] |
4617/// |---|---|---|---|
4618/// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 |
4619/// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 |
4620/// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 |
4621/// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 |
4622/// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 |
4623///
4624/// The bars rows are ~90% zero-intra-cost cells, so the split never had
4625/// residual to reach there -- the tool was being judged on content that
4626/// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
4627fn tx32_depth_search() -> bool {
4628 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4629 crate::envflags::var("EC_AV1_TX32_DEPTH").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
4630 });
4631 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
4632}
4633
4634/// Whether a COMPOUND inter winner is offered the var-tx split at all: its
4635/// trial units have to be predicted from BOTH references
4636/// ([`mc_trial_compound`]) or the split would re-predict them by single-
4637/// reference translation, which is not what the decoder reconstructs.
4638/// ON by default (the table on [`tx32_depth_search`]: on real film it is
4639/// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the
4640/// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
4641/// `EC_AV1_COMP_VARTX`.
4642fn compound_var_tx() -> bool {
4643 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4644 crate::envflags::var("EC_AV1_COMP_VARTX").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
4645 });
4646 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
4647}
4648
4649/// How many 32x32-and-below inter blocks each reference frame won, indexed by
4650/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
4651/// fire count a gate prints to see an extra reference reach a block at all
4652/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
4653/// chosen is a pyramid that costs bytes and buys nothing).
4654static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
4655 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
4656
4657/// Reads [`REF_FRAME_HITS`] and zeroes it.
4658#[cfg(test)]
4659pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
4660 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
4661}
4662
4663/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
4664#[cfg(test)]
4665pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] {
4666 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
4667}
4668
4669/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
4670/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
4671/// is one flag, depth 1 is a split root plus one unsplit flag per child
4672/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
4673/// or a 4x4 sub-size).
4674fn txfm_split_bits(side: usize, depth: usize) -> f64 {
4675 let max_tx = side.min(64);
4676 let ctx = |tx: usize| {
4677 crate::decode::txfm_partition_ctx_rect(
4678 crate::decode::TXFM_CTX_INIT,
4679 crate::decode::TXFM_CTX_INIT,
4680 side,
4681 tx,
4682 tx,
4683 )
4684 };
4685 if depth == 0 {
4686 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
4687 }
4688 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
4689 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
4690}
4691
4692/// spec 5.11.40 / libaom `av1_get_tx_type`: an INTER block's chroma transform
4693/// type is never coded -- the decoder takes the LUMA type of the block's
4694/// chroma-reference position and reduces it to the set the chroma size allows
4695/// ([`crate::decode::reduce_inherited_chroma_tx_type`]). This encoder
4696/// quantised chroma under a `DCT_DCT` basis whatever luma chose, so every
4697/// non-`DCT_DCT` luma winner had its chroma levels inverse-transformed on a
4698/// basis they were never produced for: on the bars gate row the luma of the
4699/// unconditional tx-type arm came out BETTER on every frame (53.66 -> 53.70
4700/// dB) while V lost seven decibels (52.52 -> 45.53) -- the whole 20-point BD
4701/// collapse two lanes attributed to the type PRICE (class
4702/// `parsed then discarded` / `override slot on one arm`: a decoder-derived
4703/// field the encoder never mirrored).
4704///
4705/// Re-codes the two chroma planes of a committed inter block at the type the
4706/// decoder will use, `None` when the inherited type reduces to `DCT_DCT` and
4707/// the trials the caller already holds are right.
4708#[allow(clippy::too_many_arguments)]
4709fn recode_inter_chroma(
4710 chroma: &[Plane; 2],
4711 (x, y): (usize, usize),
4712 side: usize,
4713 mv: (i32, i32),
4714 refs: [(&[u16], usize, usize, usize); 2],
4715 second: Option<((i32, i32), [(&[u16], usize, usize, usize); 2])>,
4716 search: &Search,
4717 set: TxbSet,
4718 luma_tx_type: TxType,
4719 fctx: &crate::decode::FrameCtx,
4720) -> Option<[Trial; 2]> {
4721 let c = side / 2;
4722 let tx = crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx);
4723 if tx == TxType::DctDct {
4724 return None;
4725 }
4726 Some([0usize, 1].map(|p| match second {
4727 Some((mv1, r1)) => mc_trial_compound_typed(
4728 &chroma[p], x / 2, y / 2, c, (mv, mv1), false, refs[p], r1[p], search.base_q_idx,
4729 search.deadzone, set, tx, fctx,
4730 ),
4731 None => mc_trial_typed(
4732 &chroma[p], x / 2, y / 2, c, mv, false, refs[p].0, refs[p].1, refs[p].2, refs[p].3,
4733 false, search.base_q_idx, search.deadzone, set, tx, fctx,
4734 ),
4735 }))
4736}
4737
4738/// The inter block's own var-tx decision, once its motion vector is settled:
4739/// its residual as ONE transform over the whole block, or as the four
4740/// transforms of half the side the tree's first halving names. The prediction
4741/// is the same motion compensation either way, so the split trial
4742/// re-transforms the identical residual in four pieces -- it wins where four
4743/// small transforms carry a locally varying residual cheaper than one big
4744/// one. Commits the winner into `luma` and hands back its block-coordinate
4745/// levels, the depth the writer codes and the cost the winner adds to (or
4746/// takes off) the caller's already-computed flat cost.
4747///
4748/// Only for a block wholly inside the frame: past the true edge the reader's
4749/// var-tx recursion skips the units that fall outside
4750/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
4751/// leave the residual units this writes unpaired.
4752#[allow(clippy::too_many_arguments)]
4753fn commit_inter_luma(
4754 luma: &mut Plane,
4755 (x, y): (usize, usize),
4756 side: usize,
4757 mv: (i32, i32),
4758 reference: (&[u16], usize, usize, usize),
4759 search: &Search,
4760 flat: &Trial,
4761 skip: bool,
4762 // A COMPOUND winner's second half: the vector and reference planes the
4763 // trial units are blended from ([`mc_trial_compound`], the decoder's own
4764 // `comp_group_idx == 0` average). `None` is the single-reference block.
4765 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
4766 fctx: &crate::decode::FrameCtx,
4767) -> (Vec<i32>, u8, f64, Vec<TxType>) {
4768 // lane-txset2 step 1: the whole-block (depth 0) residual picks its own
4769 // type out of the two-type inter set the writer already codes a symbol
4770 // for, priced the same way the intra search is (sse + lambda * bits, the
4771 // bits carrying the `tx_type` symbol itself through RDOQ). A skipped
4772 // block codes no residual and the 64-point transform names no type.
4773 let mut flat_typed: Option<Trial> = None;
4774 let mut flat_type = TxType::DctDct;
4775 if !skip {
4776 if let Some(fset) = inter_luma_set(side) {
4777 let lambda = search.lambda * tx_type_lambda_mult();
4778 let cost = |t: &Trial| t.sse + lambda * t.bits;
4779 for &tx_type in inter_tx_type_candidates(fset, search.screen) {
4780 if tx_type == TxType::DctDct {
4781 continue;
4782 }
4783 let candidate = match second {
4784 Some((mv1, ref1)) => mc_trial_compound_typed(
4785 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
4786 search.deadzone, fset, tx_type, fctx,
4787 ),
4788 None => mc_trial_typed(
4789 luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
4790 reference.3, false, search.base_q_idx, search.deadzone, fset, tx_type,
4791 fctx,
4792 ),
4793 };
4794 if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) {
4795 flat_type = tx_type;
4796 flat_typed = Some(candidate);
4797 }
4798 }
4799 }
4800 }
4801 // Counted at the return points, so the census names the types the block
4802 // really CODES -- a split unit's winner that the flat cost then beats was
4803 // never written (class `counter from refused stream`).
4804 let count = |types: &[TxType]| {
4805 for &t in types {
4806 INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4807 }
4808 };
4809 let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat);
4810 if crate::envflags::env_flag!("EC_AV1_TXRD_CENSUS") && !skip {
4811 use std::sync::atomic::Ordering::Relaxed;
4812 TXRD_STATS[0].fetch_add(1, Relaxed);
4813 TXRD_STATS[1].fetch_add(flat_ref.sse as u64, Relaxed);
4814 TXRD_STATS[2].fetch_add(flat.sse as u64, Relaxed);
4815 TXRD_STATS[3].fetch_add((flat_ref.bits * 64.0) as u64, Relaxed);
4816 TXRD_STATS[4].fetch_add((flat.bits * 64.0) as u64, Relaxed);
4817 // Is the `DCT_DCT` baseline the search compares against the trial
4818 // THIS function would build for the same block? A stale or
4819 // differently-predicted baseline is what would let a candidate win on
4820 // both terms at once (class `local-rd-on-references` vs a real
4821 // pricing defect); re-predicting it here is the only way to tell.
4822 if let Some(fset) = inter_luma_set(side) {
4823 let here = match second {
4824 Some((mv1, ref1)) => mc_trial_compound_typed(
4825 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
4826 search.deadzone, fset, TxType::DctDct, fctx,
4827 ),
4828 None => mc_trial_typed(
4829 luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
4830 reference.3, false, search.base_q_idx, search.deadzone, fset,
4831 TxType::DctDct, fctx,
4832 ),
4833 };
4834 TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed);
4835 TXRD_STATS[6].fetch_add((here.bits * 64.0) as u64, Relaxed);
4836 static DUMPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
4837 let n = TXRD_STATS[0].load(Relaxed);
4838 if here.sse * 2.0 < flat.sse && DUMPED.fetch_add(1, Relaxed) < 30 {
4839 eprintln!(
4840 "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \
4841 flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \
4842 sse={:.0} bits={:.1}",
4843 second.is_some(), flat.sse, flat.bits, here.sse, here.bits,
4844 flat_ref.sse, flat_ref.bits,
4845 );
4846 }
4847 }
4848 }
4849 // What the caller's already-counted `flat` cost has to be corrected by
4850 // when a non-`DCT_DCT` type won it, the same way the split delta below is.
4851 let flat_gain = (flat_ref.sse + search.lambda * flat_ref.bits)
4852 - (flat.sse + search.lambda * flat.bits);
4853 let eligible = tx_select()
4854 && tx_select_inter()
4855 && !skip
4856 && side >= 16
4857 && (second.is_none() || compound_var_tx())
4858 && (side != BLOCK || tx32_depth_search())
4859 && x + side <= luma.true_width
4860 && y + side <= luma.true_height;
4861 if !eligible {
4862 luma.commit(x, y, side, flat_ref);
4863 count(&[flat_type]);
4864 return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);
4865 }
4866 let tx = side / 2;
4867 let set = if tx >= 32 {
4868 // lane-b64b: the 64x64 root's halved transform is TX_32X32.
4869 TxbSet::Luma32Inter
4870 } else if tx >= 16 {
4871 TxbSet::Luma16Inter
4872 } else {
4873 TxbSet::Luma8Inter
4874 };
4875 let mut levels = vec![0i32; side * side];
4876 let (mut sse, mut bits) = (0.0, 0.0);
4877 let mut units = Vec::with_capacity(4);
4878 // The split units are smaller than their block, so their `txb_skip`
4879 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
4880 // each unit's own commit publishes what the next one reads, coding order.
4881 luma.ctx.tu_split = true;
4882 // One type per unit in the writer's own raster order (tile.rs
4883 // `write_luma_tus`), all `DCT_DCT` when nothing else is offered.
4884 let mut split_types = vec![TxType::DctDct; 4];
4885 for tu_row in 0..2 {
4886 for tu_col in 0..2 {
4887 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
4888 let unit = |tx_type: TxType| match second {
4889 Some((mv1, ref1)) => mc_trial_compound_typed(
4890 luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1,
4891 search.base_q_idx, search.deadzone, set, tx_type, fctx,
4892 ),
4893 None => mc_trial_typed(
4894 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
4895 reference.3, false, search.base_q_idx, search.deadzone, set, tx_type, fctx,
4896 ),
4897 };
4898 let mut best: Option<(f64, TxType, Trial)> = None;
4899 for &tx_type in inter_tx_type_candidates(set, search.screen) {
4900 let candidate = unit(tx_type);
4901 let cost = candidate.sse + search.lambda * tx_type_lambda_mult() * candidate.bits;
4902 if best.as_ref().is_none_or(|(b, _, _)| cost < *b) {
4903 best = Some((cost, tx_type, candidate));
4904 }
4905 }
4906 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
4907 split_types[tu_row * 2 + tu_col] = tx_type;
4908 sse += trial.sse;
4909 bits += trial.bits;
4910 for row in 0..tx {
4911 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
4912 .copy_from_slice(&trial.levels[row * tx..][..tx]);
4913 }
4914 units.push((tu_x, tu_y, trial));
4915 }
4916 }
4917 luma.ctx.tu_split = false;
4918 let split_rate = bits + txfm_split_bits(side, 1);
4919 let flat_rate = flat_ref.bits + txfm_split_bits(side, 0);
4920 let split_cost = sse + search.lambda * split_lambda_mult() * split_rate;
4921 let flat_cost = flat_ref.sse + search.lambda * flat_rate;
4922 if split_census_on() {
4923 split_census(1, false, side, split_cost < flat_cost, (split_rate, sse), (flat_rate, flat_ref.sse));
4924 }
4925 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
4926 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
4927 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
4928 // in the leaf row (class `gate-blind-to-feature`).
4929 let counted = side <= BLOCK;
4930 if split_cost < flat_cost {
4931 for (tu_x, tu_y, trial) in &units {
4932 luma.commit(*tu_x, *tu_y, tx, trial);
4933 }
4934 if counted {
4935 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4936 }
4937 count(&split_types);
4938 return (levels, 1, flat_gain + split_cost - flat_cost, split_types);
4939 }
4940 if counted {
4941 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4942 }
4943 luma.commit(x, y, side, flat_ref);
4944 count(&[flat_type]);
4945 (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type])
4946}
4947
4948/// The largest distinct-colour count a block may hold and still be offered a
4949/// palette candidate at all: past it the k-means quantisation costs more
4950/// error than the map saves rate, and every trial is wasted wall.
4951///
4952/// Swept on the gate's own screen capture (lane-av1pal2, the
4953/// `unswept-decision-constants` class): 32 (the value this lane inherited)
4954/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
4955/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
4956/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
4957/// binds on nothing this content holds. 128 ships: best BD against both
4958/// references and no wall cost at all (6.1s, the same as at 32, because the
4959/// blocks it newly admits are ones the RD then keeps).
4960/// `EC_AV1_PAL_MAXCOLORS`.
4961fn palette_max_colors() -> usize {
4962 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
4963 *N.get_or_init(|| {
4964 std::env::var("EC_AV1_PAL_MAXCOLORS")
4965 .ok()
4966 .and_then(|v| v.parse().ok())
4967 .unwrap_or(128)
4968 })
4969}
4970
4971/// The palettes worth trying for one block's luma, in the shape libaom's
4972/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
4973/// distinct colours takes them ALL (the prediction is then exact and the
4974/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
4975/// one-dimensional Lloyd iteration seeded evenly across its range -- both
4976/// offered, because which wins is an RD question the caller answers.
4977/// `block` is `side*side` source samples, row-major.
4978fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
4979 let mut histogram = [0u32; 256];
4980 for &v in block {
4981 histogram[usize::from(v)] += 1;
4982 }
4983 let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
4984 if present.len() < 2 {
4985 return Vec::new();
4986 }
4987 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
4988 let mut base = [0u16; 8];
4989 base[..colors.len()].copy_from_slice(colors);
4990 let map = block
4991 .iter()
4992 .map(|&v| {
4993 colors
4994 .iter()
4995 .enumerate()
4996 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
4997 .map(|(i, _)| i as u8)
4998 .expect("a palette holds at least two colours")
4999 })
5000 .collect();
5001 crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
5002 };
5003 if present.len() <= 8 {
5004 return vec![exact(&present)];
5005 }
5006 if present.len() > palette_max_colors() {
5007 return Vec::new();
5008 }
5009 let (lo, hi) = (
5010 i32::from(present[0]),
5011 i32::from(present[present.len() - 1]),
5012 );
5013 let mut out = Vec::with_capacity(2);
5014 for n in [8usize, 4] {
5015 // Even seeding across the block's own range, then four Lloyd passes
5016 // over the histogram (256 bins, not `side*side` pixels).
5017 let mut centres: Vec<f64> = (0..n)
5018 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
5019 .collect();
5020 for _ in 0..4 {
5021 let mut sums = vec![0f64; n];
5022 let mut counts = vec![0u32; n];
5023 for (v, &count) in histogram.iter().enumerate() {
5024 if count == 0 {
5025 continue;
5026 }
5027 let k = (0..n)
5028 .min_by(|&a, &b| {
5029 (centres[a] - v as f64)
5030 .abs()
5031 .total_cmp(&(centres[b] - v as f64).abs())
5032 })
5033 .expect("n >= 2");
5034 sums[k] += (v as u32 * count) as f64;
5035 counts[k] += count;
5036 }
5037 for k in 0..n {
5038 if counts[k] > 0 {
5039 centres[k] = sums[k] / f64::from(counts[k]);
5040 }
5041 }
5042 }
5043 let mut colors: Vec<u16> = centres
5044 .iter()
5045 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
5046 .collect();
5047 colors.sort_unstable();
5048 colors.dedup();
5049 if colors.len() >= 2 {
5050 out.push(exact(&colors));
5051 }
5052 }
5053 out
5054}
5055
5056#[allow(clippy::too_many_arguments)]
5057// ---------------------------------------------------------------------------
5058// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
5059// validity). A key frame that detected screen content and finds enough exact
5060// repeats in its own source sets `allow_intrabc`, which the spec forces every
5061// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
5062// its place when the copied blocks pay back the deblock/CDEF/LR the frame
5063// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
5064// ---------------------------------------------------------------------------
5065
5066/// Whether intra block copy is offered at all. **Off by default** --
5067/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
5068/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
5069/// but on the gate's real screen capture it MEASURED WORSE: setting
5070/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
5071/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
5072/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
5073/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
5074/// that detected no screen content.
5075fn intrabc_enabled() -> bool {
5076 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
5077 return forced;
5078 }
5079 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5080 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
5081}
5082
5083thread_local! {
5084 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
5085 /// probe runs both arms in one process, and the suite is one process, so
5086 /// an environment variable cannot separate them (same reason
5087 /// [`SCREEN_FORCE`] exists).
5088 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
5089}
5090
5091#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5092pub(crate) fn force_intrabc(value: Option<bool>) {
5093 INTRABC_FORCE.with(|c| c.set(value));
5094}
5095
5096/// How many of a screen frame's 16x16 blocks must have an exact repeat
5097/// somewhere else in the source before `allow_intrabc` is worth the in-loop
5098/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
5099/// constant class: `probe_intrabc_threshold` measures the arm at several
5100/// values.
5101fn intrabc_pct() -> usize {
5102 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5103 *N.get_or_init(|| {
5104 std::env::var("EC_AV1_INTRABC_PCT")
5105 .ok()
5106 .and_then(|v| v.parse().ok())
5107 .unwrap_or(10)
5108 })
5109}
5110
5111/// The pixel grid intrabc source positions are hashed on
5112/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
5113/// which keeps the block-hash table (and so the search) linear in the frame
5114/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
5115/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
5116/// bilinear interpolation decode.rs applies but this encoder does not.
5117fn intrabc_step() -> usize {
5118 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5119 *N.get_or_init(|| {
5120 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
5121 .ok()
5122 .and_then(|v| v.parse().ok())
5123 .unwrap_or(4);
5124 if n % 2 == 0 { n.max(2) } else { 4 }
5125 })
5126}
5127
5128/// The side of the luma square the block-hash table is keyed on.
5129const IBC_HASH: usize = 16;
5130
5131/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
5132/// the current one the source's bottom-right corner must already be.
5133const INTRABC_DELAY_SB64: i32 = 4;
5134
5135/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
5136fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
5137 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
5138 for row in 0..IBC_HASH {
5139 let base = (y + row) * width + x;
5140 for &v in &plane[base..base + IBC_HASH] {
5141 h ^= u64::from(v);
5142 h = h.wrapping_mul(0x100_0000_01b3);
5143 }
5144 }
5145 h
5146}
5147
5148/// Every `intrabc_step()`-aligned position of `plane` inside
5149/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
5150fn ibc_index(
5151 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
5152 plane: &[u8],
5153 width: usize,
5154 (x0, y0): (usize, usize),
5155 (x1, y1): (usize, usize),
5156) {
5157 let step = intrabc_step();
5158 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
5159 return;
5160 }
5161 let mut y = y0.next_multiple_of(step);
5162 while y + IBC_HASH <= y1 {
5163 let mut x = x0.next_multiple_of(step);
5164 while x + IBC_HASH <= x1 {
5165 table
5166 .entry(ibc_hash(plane, width, x, y))
5167 .or_default()
5168 .push((x as u32, y as u32));
5169 x += step;
5170 }
5171 y += step;
5172 }
5173}
5174
5175/// Whether `screen`-detected source `y` repeats itself enough to be worth
5176/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
5177/// content appears at some other position, against [`intrabc_pct`]. Returns
5178/// the share as well, for the gate's own print.
5179fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
5180 if true_width < 4 * 64 || true_height < 2 * 64 {
5181 return (false, 0.0);
5182 }
5183 let mut table = std::collections::HashMap::new();
5184 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
5185 let (mut total, mut matched) = (0usize, 0usize);
5186 let mut by = 0;
5187 while by + IBC_HASH <= true_height {
5188 let mut bx = 0;
5189 while bx + IBC_HASH <= true_width {
5190 total += 1;
5191 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
5192 if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
5193 matched += 1;
5194 }
5195 }
5196 bx += IBC_HASH;
5197 }
5198 by += IBC_HASH;
5199 }
5200 let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
5201 (share * 100.0 >= intrabc_pct() as f64, share)
5202}
5203
5204/// One tile's intrabc search state: a block-hash table over the part of the
5205/// tile's own reconstruction that is already final (whole superblock rows --
5206/// the in-loop filters are off on this frame, so a coded superblock row never
5207/// changes again), plus the last DV chosen, which the RD price uses as its
5208/// predictor estimate.
5209struct Ibc {
5210 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
5211 /// source repeats exactly where a lossily coded reconstruction only
5212 /// nearly does, so an exact-match table over the reconstruction finds
5213 /// almost nothing. The candidate is then SCORED against the
5214 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
5215 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
5216 /// The tile's own luma rect, in samples.
5217 tile: (usize, usize, usize, usize),
5218 /// The DV the previous intrabc block of this tile took -- the *estimate*
5219 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
5220 /// against. The writer computes the true predictor off its own mi grid
5221 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
5222 /// a slightly mispriced candidate, never a wrong bitstream.
5223 last_dv: Option<(i32, i32)>,
5224 /// How many blocks took intrabc, and how many hash lookups found at least
5225 /// one valid candidate -- the gate's own fire counts.
5226 hits: usize,
5227 lookups: usize,
5228 found: usize,
5229}
5230
5231impl Ibc {
5232 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
5233 let mut table = std::collections::HashMap::new();
5234 ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
5235 Self {
5236 table,
5237 tile,
5238 last_dv: None,
5239 hits: 0,
5240 lookups: 0,
5241 found: 0,
5242 }
5243 }
5244
5245 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
5246 /// (1/8 pel), with this lane's own extra restriction on top: the source
5247 /// must lie entirely in a COMPLETED superblock row, which is exactly the
5248 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
5249 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
5250 /// wavefront's own diagonal) are legal and not searched; the upgrade path
5251 /// is to index the current row's finished superblocks too.
5252 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
5253 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
5254 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
5255 return false;
5256 }
5257 let (tx0, ty0, tx1, ty1) = (
5258 self.tile.0 as i32,
5259 self.tile.1 as i32,
5260 self.tile.2 as i32,
5261 self.tile.3 as i32,
5262 );
5263 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
5264 let (w, h) = (w as i32, h as i32);
5265 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
5266 return false;
5267 }
5268 let active_sb_row = (y as i32 - ty0) >> 6;
5269 let active_sb_col = (x as i32 - tx0) >> 6;
5270 let src_sb_row = (sy + h - 1 - ty0) >> 6;
5271 let src_sb_col = (sx + w - 1 - tx0) >> 6;
5272 // This lane's own restriction (see the doc comment).
5273 if src_sb_row >= active_sb_row {
5274 return false;
5275 }
5276 let total = ((tx1 - tx0 - 1) >> 6) + 1;
5277 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64
5278 {
5279 return false;
5280 }
5281 // libaom's wavefront: only the top-left cone of the frame is legal.
5282 let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row);
5283 src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf
5284 }
5285}
5286
5287/// How many block searches ran, how many found at least one VALID candidate,
5288/// and how many won on rate-distortion -- the hash hit rate a gate prints
5289/// (class `gate-blind-to-feature`: "the search ran" and "the search found
5290/// something" and "the block took it" are three different claims).
5291static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
5292 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
5293
5294impl Drop for Ibc {
5295 fn drop(&mut self) {
5296 for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
5297 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
5298 }
5299 }
5300}
5301
5302/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
5303/// its own encode.
5304#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5305pub(crate) fn take_intrabc_search() -> [usize; 3] {
5306 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5307}
5308
5309/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
5310/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
5311/// infers rather than codes.
5312fn dv_component_bits(diff: i32) -> f64 {
5313 let z = diff.unsigned_abs() as i32 - 1;
5314 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
5315 let class = mv_class_of(z);
5316 bits += symbol_bits(&cdf::MV_CLASS, class);
5317 let local = z - mv_class_base(class);
5318 if class == 0 {
5319 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
5320 } else {
5321 let d = local >> 3;
5322 for i in 0..class {
5323 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
5324 }
5325 }
5326 bits
5327}
5328
5329/// What one block vector costs against `pred`, plus the `skip` and
5330/// `use_intrabc` flags the block carries and the ordinary intra block does
5331/// not pay in this currency.
5332fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
5333 let diff = (dv.0 - pred.0, dv.1 - pred.1);
5334 let joint = match (diff.0 != 0, diff.1 != 0) {
5335 (false, false) => 0,
5336 (false, true) => 1,
5337 (true, false) => 2,
5338 (true, true) => 3,
5339 };
5340 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
5341 if diff.0 != 0 {
5342 bits += dv_component_bits(diff.0);
5343 }
5344 if diff.1 != 0 {
5345 bits += dv_component_bits(diff.1);
5346 }
5347 bits
5348}
5349
5350/// The squared error of copying the `side`-square block at `(sx, sy)` of each
5351/// plane's reconstruction onto the source block at `(x, y)`, luma and both
5352/// chroma planes together -- what an intrabc block's whole (residual-free)
5353/// distortion is.
5354fn ibc_sse(
5355 luma: &Plane,
5356 chroma: &[Plane; 2],
5357 (x, y): (usize, usize),
5358 (sx, sy): (usize, usize),
5359 side: usize,
5360) -> f64 {
5361 // Inside the true frame only, for the reason [`Plane::block_sse`] is
5362 // (lane-sse): an intrabc block at the edge would otherwise be ranked by
5363 // how well it copies the padding.
5364 let mut sse = 0.0f64;
5365 let clip = |whole: usize, inside: usize| match edge_sse() {
5366 true => whole.min(inside),
5367 false => whole,
5368 };
5369 let rows = clip(side, luma.true_height.saturating_sub(y));
5370 let cols = clip(side, luma.true_width.saturating_sub(x));
5371 for row in 0..rows {
5372 let src = &luma.source[(y + row) * luma.width + x..][..cols];
5373 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols];
5374 for (&s, &r) in src.iter().zip(rec) {
5375 let d = f64::from(i32::from(s) - i32::from(r));
5376 sse += d * d;
5377 }
5378 }
5379 let half = side / 2;
5380 for plane in chroma {
5381 let rows = clip(half, plane.true_height.saturating_sub(y / 2));
5382 let cols = clip(half, plane.true_width.saturating_sub(x / 2));
5383 for row in 0..rows {
5384 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols];
5385 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols];
5386 for (&s, &r) in src.iter().zip(rec) {
5387 let d = f64::from(i32::from(s) - i32::from(r));
5388 sse += d * d;
5389 }
5390 }
5391 }
5392 sse
5393}
5394
5395/// Copies the `side`-square block at `(sx, sy)` of each plane's
5396/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
5397/// since it carries no residual (`skip`). Full-pel in both planes by
5398/// construction ([`intrabc_step`] keeps every DV even), which is what makes
5399/// this a plain copy where decode.rs runs the bilinear kernel over the same
5400/// samples.
5401fn ibc_commit(
5402 luma: &mut Plane,
5403 chroma: &mut [Plane; 2],
5404 (x, y): (usize, usize),
5405 (sx, sy): (usize, usize),
5406 side: usize,
5407) {
5408 for row in 0..side {
5409 let from = (sy + row) * luma.width + sx;
5410 let to = (y + row) * luma.width + x;
5411 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
5412 luma.reconstruction[to..to + side].copy_from_slice(&copied);
5413 }
5414 let half = side / 2;
5415 for plane in chroma {
5416 for row in 0..half {
5417 let from = (sy / 2 + row) * plane.width + sx / 2;
5418 let to = (y / 2 + row) * plane.width + x / 2;
5419 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
5420 plane.reconstruction[to..to + half].copy_from_slice(&copied);
5421 }
5422 plane.commit_ctx_zero(x / 2, y / 2, half);
5423 }
5424 luma.commit_ctx_zero(x, y, side);
5425}
5426
5427/// Searches this block's own DV: every hash-table position whose 16x16 luma
5428/// square equals the block's source square, plus the previous block's DV as a
5429/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
5430/// the winning `(dv, cost)`, or `None` when nothing valid was found.
5431fn ibc_search(
5432 ibc: &mut Ibc,
5433 luma: &Plane,
5434 chroma: &[Plane; 2],
5435 (x, y): (usize, usize),
5436 side: usize,
5437 lambda: f64,
5438) -> Option<((i32, i32), f64, (usize, usize))> {
5439 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
5440 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
5441 let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
5442 let dv = (
5443 (sy as i32 - y as i32) * 8,
5444 (sx as i32 - x as i32) * 8,
5445 );
5446 if !ibc.dv_valid(x, y, side, side, dv) {
5447 return;
5448 }
5449 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
5450 if best.as_ref().is_none_or(|b| cost < b.1) {
5451 *best = Some((dv, cost, (sx, sy)));
5452 }
5453 };
5454 ibc.lookups += 1;
5455 let key = ibc_hash(luma.source, luma.width, x, y);
5456 // The table is filled in raster order, so the entries BEFORE this block's
5457 // own position are exactly the already-coded ones -- and the nearest of
5458 // them costs the fewest DV bits. Walking backwards from the block's own
5459 // slot is what makes the search look up-and-left; taking the newest
5460 // entries outright only ever finds candidates below and to the right,
5461 // every one of which `dv_valid` rejects.
5462 let hits: Vec<(u32, u32)> = ibc
5463 .table
5464 .get(&key)
5465 .map(|h| {
5466 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
5467 h[..end].iter().rev().take(32).copied().collect()
5468 })
5469 .unwrap_or_default();
5470 for (hx, hy) in hits {
5471 consider(&*ibc, hx as usize, hy as usize, &mut best);
5472 }
5473 if let Some(dv) = ibc.last_dv {
5474 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
5475 if sx >= 0 && sy >= 0 {
5476 consider(&*ibc, sx as usize, sy as usize, &mut best);
5477 }
5478 }
5479 if best.is_some() {
5480 ibc.found += 1;
5481 }
5482 best
5483}
5484
5485fn code_square(
5486 luma: &mut Plane,
5487 chroma: &mut [Plane; 2],
5488 (x, y): (usize, usize),
5489 side: usize,
5490 search: &Search,
5491 mode_bits: &[f64; 13],
5492 // The frame header's `tx_mode == TxMode::Select`: the block then searches
5493 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
5494 // transform over its whole side.
5495 tx_select: bool,
5496 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
5497 // header did not set `allow_intrabc`.
5498 ibc: Option<&mut Ibc>,
5499 // Whether this is a KEY frame's block, read only by the split census
5500 // ([`SPLIT_CENSUS`]): the two frame types split at very different rates,
5501 // which is this lane's whole finding.
5502 census_key: bool,
5503 fctx: &crate::decode::FrameCtx,
5504) -> (BlockCoeffs, f64) {
5505 let (luma_set, chroma_set) = if side == SUPERBLOCK {
5506 // A whole superblock coded as ONE intra block (lane-i64): one
5507 // TX_64X64 luma transform, whose coded quarter is the 32x32 corner
5508 // `code_from_prediction` hands back, and one TX_32X32 per chroma
5509 // plane -- the same three sets the key frame writer's
5510 // `Superblock::Whole` arm codes, and the same the inter 64x64 root
5511 // uses (`search_skip_64`).
5512 (TxbSet::Luma64, TxbSet::Chroma32)
5513 } else if side == BLOCK {
5514 (TxbSet::Luma32, TxbSet::Chroma16)
5515 } else if side == 8 {
5516 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
5517 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
5518 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
5519 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
5520 // (this branch is still unreached), so leaving `Chroma8` here would
5521 // silently wire the wrong table the moment one does; `Chroma4` is
5522 // what a real caller needs.
5523 (TxbSet::Luma8, TxbSet::Chroma4)
5524 } else {
5525 (TxbSet::Luma16, TxbSet::Chroma8)
5526 };
5527 let at = At {
5528 x,
5529 y,
5530 side,
5531 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
5532 set: luma_set_for(luma_set, search.screen),
5533 };
5534 let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) =
5535 luma.search_block(at, search, mode_bits, fctx);
5536 let mut luma_tx_types = vec![tx_type];
5537 // The depth search runs on the mode the whole-block transform picked --
5538 // libaom's own ordering, and the reason it costs one extra pass per depth
5539 // rather than one per (mode, depth) pair.
5540 let mut tx_depth = 0u8;
5541 // A 64x64 block has no depth to search (`max_tx_depth`), but the writer
5542 // still codes its `tx_depth` symbol off `TX_SIZE_CAT3`, so the incumbent
5543 // pays that zero exactly as a 32x32's depth search makes it pay
5544 // `tx_depth_bits(32, 0)` -- otherwise the 64-versus-four-32 comparison
5545 // below hands the root a symbol for free.
5546 if tx_select && side == SUPERBLOCK {
5547 cost += search.lambda * tx_depth_bits(side, 0);
5548 }
5549 if tx_select && max_tx_depth(side) > 0 {
5550 let mut best = (
5551 cost + search.lambda * tx_depth_bits(side, 0),
5552 0usize,
5553 luma.snapshot(x, y, side),
5554 luma_coeffs,
5555 );
5556 let mut best_types = std::mem::take(&mut luma_tx_types);
5557 // The census wants the flat arm's own (rate, distortion), which
5558 // `search_block` only hands back folded into one cost -- so under the
5559 // env flag alone it is re-coded at depth 0 and the plane restored.
5560 let census_flat = split_census_on().then(|| {
5561 let kept = luma.snapshot(x, y, side);
5562 let (_, sse, bits, _) =
5563 luma.code_tx_depth(at, mode, angle_delta, 0, None, search, fctx);
5564 luma.restore(x, y, side, &kept);
5565 (bits + tx_depth_bits(side, 0), sse)
5566 });
5567 let mut census_split: Option<(f64, f64)> = None;
5568 for depth in 1..=max_tx_depth(side) {
5569 let (levels, sse, bits, types) =
5570 luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
5571 let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth);
5572 let cost_d = sse + search.lambda * split_lambda_mult() * rate;
5573 if census_flat.is_some() {
5574 let c = (bits + tx_depth_bits(side, depth), sse);
5575 if census_split.is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
5576 {
5577 census_split = Some(c);
5578 }
5579 }
5580 if cost_d < best.0 {
5581 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
5582 best_types = types;
5583 }
5584 }
5585 if let (Some(flat), Some(split)) = (census_flat, census_split) {
5586 split_census(0, census_key, side, best.1 > 0, split, flat);
5587 }
5588 luma_tx_types = best_types;
5589 luma.restore(x, y, side, &best.2);
5590 cost = best.0;
5591 tx_depth = best.1 as u8;
5592 luma_coeffs = best.3;
5593 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5594 }
5595 // The palette candidate is priced against the mode the luma search (and
5596 // its transform-depth search) already settled on, so a block only takes
5597 // one when it beats the best ordinary intra coding of the same pixels.
5598 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
5599 // prediction is the colour map, not the DC of its neighbours.
5600 let mut mode = mode;
5601 let mut angle_delta = angle_delta;
5602 let mut palette = None;
5603 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
5604 let source: Vec<u8> = (y..y + side)
5605 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
5606 .collect();
5607 let kept = luma.snapshot(x, y, side);
5608 for pal in palette_candidates(&source) {
5609 let n = usize::from(pal.size);
5610 let prediction: Vec<u8> = pal
5611 .map
5612 .iter()
5613 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
5614 .collect();
5615 let trial = luma.code_from_prediction(
5616 x,
5617 y,
5618 side,
5619 &prediction,
5620 false,
5621 search.base_q_idx,
5622 search.deadzone,
5623 luma_set,
5624 );
5625 let cost_p = trial.sse
5626 + search.lambda
5627 * (trial.bits
5628 + mode_bits[DC_PRED as usize]
5629 + crate::tile::palette_bits(&pal, side)
5630 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
5631 if cost_p < cost {
5632 cost = cost_p;
5633 mode = DC_PRED as u8;
5634 angle_delta = 0;
5635 tx_depth = 0;
5636 luma_coeffs = coeffs(&trial.levels, side.min(BLOCK));
5637 luma.commit(x, y, side, &trial);
5638 palette = Some(pal);
5639 }
5640 }
5641 if palette.is_none() {
5642 luma.restore(x, y, side, &kept);
5643 }
5644 }
5645
5646 // The five recursive filter-intra modes (spec 5.11.14), priced against
5647 // whatever the mode, transform-depth and palette searches settled on --
5648 // the same "one candidate loop after the incumbent is known" shape the
5649 // palette above uses. A block that takes one is `DC_PRED` with no palette
5650 // by construction (`av1_filter_intra_allowed`), and its luma transform
5651 // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`).
5652 //
5653 // lane-fitu: on a SCREEN frame the candidate is priced at every transform
5654 // depth the ordinary intra search runs, each unit predicting recursively
5655 // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra`
5656 // arm), so a block whose ordinary winner wanted a split transform is
5657 // compared against a filter arm that may split too.
5658 //
5659 // Measured (native BD table, lane-fitu): searching the depths on EVERY
5660 // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves
5661 // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a
5662 // locally cheaper reconstruction that the film rows go on to predict from
5663 // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen
5664 // content is where it pays, and a non-screen frame keeps the depth-0-only
5665 // arm, byte for byte.
5666 let mut filter_intra: Option<u8> = None;
5667 if filter_intra_on()
5668 && palette.is_none()
5669 && let Some(class) = crate::decode::filter_intra_size_class(side)
5670 {
5671 let row = &cdf::FILTER_INTRA[class];
5672 // With the sequence bit on, EVERY `DC_PRED` block without a luma
5673 // palette carries the flag, so the incumbent pays its zero before the
5674 // comparison -- otherwise the candidate is charged a bit the block
5675 // spends either way (class `price-the-narrowing-not-the-table`).
5676 if mode == DC_PRED {
5677 cost += search.lambda * symbol_bits(row, 0);
5678 }
5679 let one_bits = symbol_bits(row, 1);
5680 let kept = luma.snapshot(x, y, side);
5681 let max_depth = if tx_select && search.screen { max_tx_depth(side) } else { 0 };
5682 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
5683 for fi in 0..5u8 {
5684 for depth in 0..=max_depth {
5685 // A filter-intra block's units are coded through
5686 // `code_from_prediction`, which is `DCT_DCT` throughout, so
5687 // this arm keeps the empty (all-`DCT_DCT`) type list.
5688 let (levels, sse, bits, _) =
5689 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);
5690 let cost_f = sse
5691 + search.lambda
5692 * (bits
5693 + mode_bits[DC_PRED as usize]
5694 + one_bits
5695 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
5696 + if tx_select { tx_depth_bits(side, depth) } else { 0.0 });
5697 if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) {
5698 best = Some((
5699 cost_f,
5700 fi,
5701 depth,
5702 luma.snapshot(x, y, side),
5703 coeffs(&levels, side),
5704 ));
5705 }
5706 }
5707 }
5708 if let Some((cost_f, fi, depth, snapshot, levels)) = best {
5709 cost = cost_f;
5710 mode = DC_PRED;
5711 angle_delta = 0;
5712 tx_depth = depth as u8;
5713 luma_coeffs = levels;
5714 luma.restore(x, y, side, &snapshot);
5715 filter_intra = Some(fi);
5716 } else {
5717 luma.restore(x, y, side, &kept);
5718 }
5719 }
5720
5721 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
5722 // planes; what it costs still counts towards the partition decision.
5723 let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
5724 search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
5725 cost += chroma_cost;
5726
5727 // The intrabc arm is priced against the WHOLE block -- luma and both
5728 // chroma planes, residual-free -- so it is compared after the chroma
5729 // search has added its own cost, not against the luma decision alone.
5730 if let Some(ibc) = ibc {
5731 if let Some((dv, cost_ibc, src)) =
5732 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
5733 {
5734 if cost_ibc < cost {
5735 ibc_commit(luma, chroma, (x, y), src, side);
5736 ibc.last_dv = Some(dv);
5737 ibc.hits += 1;
5738 return (
5739 BlockCoeffs {
5740 skip: true,
5741 dv: Some(dv),
5742 ..BlockCoeffs::default()
5743 },
5744 cost_ibc,
5745 );
5746 }
5747 }
5748 }
5749 // A palette or filter-intra block's luma was recoded through `DCT_DCT`
5750 // (its levels came from `code_from_prediction`), so the searched types
5751 // belong to a block this one no longer is.
5752 if palette.is_some() || filter_intra.is_some() {
5753 luma_tx_types = Vec::new();
5754 }
5755 (
5756 BlockCoeffs {
5757 u,
5758 v,
5759 luma: luma_coeffs,
5760 mode,
5761 uv_mode,
5762 tx_depth,
5763 palette,
5764 palette_uv,
5765 filter_intra,
5766 cfl_alphas,
5767 angle_delta_y: angle_delta as i8,
5768 luma_tx_types,
5769 ..BlockCoeffs::default()
5770 },
5771 cost,
5772 )
5773}
5774
5775/// The chroma modes the search offers, and the only ones it may offer: each
5776/// predicts from the row directly above and the column directly to the left
5777/// and nothing further, so none of them needs the above-right/below-left
5778/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
5779/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
5780/// reconstruction and its own alpha syntax; both are left out here.
5781const CHROMA_MODES: [u8; 7] = [
5782 DC_PRED,
5783 V_PRED,
5784 H_PRED,
5785 SMOOTH_PRED,
5786 SMOOTH_V_PRED,
5787 SMOOTH_H_PRED,
5788 PAETH_PRED,
5789];
5790
5791/// The thirteen intra mode names, for the chroma fire count's print.
5792#[cfg(test)]
5793const UV_MODE_NAMES: [&str; 14] = [
5794 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
5795 "SMOOTH_H", "PAETH", "CFL",
5796];
5797
5798/// How many blocks each chroma mode has won, indexed by the mode itself --
5799/// the fire count that says whether the search below reaches its candidates
5800/// at all (the `gate-blind-to-feature` class), printed once per gate run.
5801static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
5802 [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
5803
5804/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
5805/// won, summed over both chroma planes -- the alpha histogram the gate prints
5806/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
5807/// magnitude only is a search that never left its first candidate).
5808static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
5809 [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
5810
5811/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
5812/// zero on a CfL block", `1..=16` the magnitudes.
5813#[cfg(test)]
5814pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
5815 std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
5816}
5817
5818/// How many directional luma blocks won at each `angle_delta_y`, indexed
5819/// `delta + 3` -- the histogram that says whether the refinement below ever
5820/// leaves zero (`gate-blind-to-feature`).
5821static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
5822 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
5823
5824/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
5825#[cfg(test)]
5826pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
5827 std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
5828}
5829
5830/// Whether the luma search refines a directional winner's `angle_delta_y`
5831/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
5832fn angle_delta_on() -> bool {
5833 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5834 crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0")
5835 });
5836 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
5837}
5838
5839/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
5840/// switches it off, which is how the lane measured its own on/off pair).
5841fn cfl_on() -> bool {
5842 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5843 crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0")
5844 });
5845 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
5846}
5847
5848/// Whether the intra search offers the five recursive filter-intra modes at
5849/// all, and with them whether the sequence header sets `enable_filter_intra`
5850/// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
5851/// its own on/off pair -- and how every byte pin written before it still
5852/// reproduces). It is also a speed lever: on at preset 0, off above it.
5853// lane-sb128: `use_128x128_superblock` (spec 5.5.1). Off by default until
5854// the BD gate says otherwise; `EC_AV1_SB128=1` turns it on for the whole
5855// process (a sequence-header field, so it cannot change mid-stream anyway),
5856// the same env-flag shape `EC_AV1_FILTER_INTRA` uses. NOT an `EncoderConfig`
5857// field: that struct is built by 90 literal sites in this workspace.
5858
5859/// Whether this process's sequences code 128x128 superblocks. An ENCODER
5860/// knob (like `speed::SPEED`), never read by a decode: read through a
5861/// process-global (not a thread-local) because the tile writers run on
5862/// worker threads; `2` is "the environment has not been read yet".
5863static ENC_SB128: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2);
5864
5865/// Whether this process's sequences code 128x128 superblocks.
5866pub(crate) fn sb128_on() -> bool {
5867 use std::sync::atomic::Ordering::Relaxed;
5868 match ENC_SB128.load(Relaxed) {
5869 2 => {
5870 let on = crate::envflags::var("EC_AV1_SB128").ok().is_some_and(|v| v != "0");
5871 ENC_SB128.store(u8::from(on), Relaxed);
5872 on
5873 }
5874 v => v == 1,
5875 }
5876}
5877
5878/// Forces [`sb128_on`] for the rest of the process -- the superblock size is
5879/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`),
5880/// exactly like the speed-preset gates.
5881#[cfg(test)]
5882pub(crate) fn force_sb128(on: bool) {
5883 ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed);
5884}
5885
5886/// The luma loop-restoration unit size this sequence codes: a 128 superblock
5887/// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,
5888/// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is
5889/// 128), which is the one filter parameter the superblock size moves.
5890pub(crate) fn lr_unit() -> u32 {
5891 if sb128_on() { 128 } else { 64 }
5892}
5893
5894pub(crate) fn filter_intra_on() -> bool {
5895 #[cfg(test)]
5896 if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) {
5897 return forced;
5898 }
5899 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5900 crate::envflags::var("EC_AV1_FILTER_INTRA").ok().map(|v| v != "0")
5901 });
5902 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
5903}
5904
5905/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
5906/// to its own encode.
5907#[cfg(test)]
5908pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
5909 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
5910}
5911
5912/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
5913/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
5914/// Returns each plane's levels, the mode, and what the pair cost (squared
5915/// error plus lambda times bits, the same currency the luma search speaks).
5916///
5917/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
5918/// which is what the luma mode decision was taken against, so what a
5919/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
5920/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
5921/// writer then has to code.
5922#[allow(clippy::too_many_arguments)]
5923/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
5924/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
5925/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
5926/// trials all seven, as before this lever.
5927///
5928/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
5929/// the search's largest trial population by far -- seven modes times two
5930/// planes for every intra block, against 3.7 luma trials -- and the RD
5931/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
5932/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
5933fn chroma_top_k() -> Option<usize> {
5934 static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| {
5935 crate::envflags::var("EC_AV1_CHROMA_K")
5936 .ok()
5937 .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0))
5938 });
5939 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K))
5940}
5941
5942/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
5943/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
5944/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
5945/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
5946/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
5947/// BD swings by about a point in either direction as near-tie chroma modes
5948/// flip, which is the measurement's own sensitivity, not a trend: nothing
5949/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
5950/// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
5951/// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
5952/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
5953pub(crate) const CHROMA_TOP_K: Option<usize> = None;
5954
5955fn search_chroma(
5956 chroma: &mut [Plane; 2],
5957 // The luma plane's RECONSTRUCTION under this block, already committed by
5958 // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
5959 luma: &Plane,
5960 (x, y): (usize, usize),
5961 side: usize,
5962 set: TxbSet,
5963 search: &Search,
5964 luma_mode: u8,
5965 fctx: &crate::decode::FrameCtx,
5966) -> (
5967 [Vec<Coeff>; 2],
5968 u8,
5969 f64,
5970 Option<crate::tile::PaletteUv>,
5971 Option<(i32, i32)>,
5972) {
5973 let at = At {
5974 x: x / 2,
5975 y: y / 2,
5976 side: side / 2,
5977 reach: Reach::none(),
5978 set,
5979 };
5980 // The census's cheap proxy for a chroma mode: the SAD of its prediction
5981 // summed over both planes, ranked by the same rule the luma histogram
5982 // uses. Only built under `EC_AV1_CENSUS`.
5983 // The SAD of each mode's prediction, summed over both planes -- the
5984 // census's ranking rule, and what [`chroma_top_k`] prunes by.
5985 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
5986 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
5987 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
5988 u.iter()
5989 .zip(v.iter())
5990 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
5991 .collect()
5992 };
5993 let modes: Vec<u8> = match chroma_top_k() {
5994 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
5995 _ => CHROMA_MODES.to_vec(),
5996 };
5997 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
5998 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
5999 let ranking: Vec<(f64, u8)> = if census_on() {
6000 sad_scores(chroma)
6001 } else {
6002 Vec::new()
6003 };
6004 census_add(2, 1);
6005 census_add(3, modes.len());
6006 let mut best: Option<(f64, u8, Trial, Trial)> = None;
6007 for mode in modes {
6008 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
6009 if (V_PRED..=D67_PRED).contains(&mode) {
6010 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
6011 }
6012 // lane-i64: `av1_get_ext_tx_set_type` resolves a CHROMA plane at
6013 // `tx_size_sqr >= TX_32X32` to `EXT_TX_SET_DCTONLY`, so the 32x32
6014 // chroma of a 64x64 block is `DCT_DCT` whatever
6015 // `Intra_Mode_To_Tx_Type` says -- the decoder's own `side >= 32` arm
6016 // (decode.rs `read_chroma_plane`), and ADST is not even defined at 32
6017 // points.
6018 let tx_type = if at.side >= 32 {
6019 TxType::DctDct
6020 } else {
6021 crate::decode::default_intra_tx_type(mode)
6022 };
6023 let u = chroma[0].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6024 let v = chroma[1].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6025 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
6026 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
6027 best = Some((cost, mode, u, v));
6028 }
6029 }
6030 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
6031 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
6032 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
6033 // what keeps `u_colors` ascending and distinct the way
6034 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
6035 // each cluster's own mean, since the colour-index map is SHARED by the
6036 // two planes. Priced against the best ordinary chroma mode above, so a
6037 // block only takes one when it beats it; a palette block's chroma mode is
6038 // `UV_DC_PRED` by construction.
6039 let mut palette_uv = None;
6040 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6041 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
6042 let plane_source = |p: &Plane| -> Vec<u8> {
6043 (at.y..at.y + at.side)
6044 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
6045 .collect()
6046 };
6047 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
6048 for pal in palette_candidates(&u_source) {
6049 let n = usize::from(pal.size);
6050 // V's base colour per cluster: the mean of the samples the shared
6051 // map assigns to it (an empty cluster cannot happen -- every
6052 // colour `palette_candidates` returns is some pixel's nearest).
6053 let mut sums = [0u32; 8];
6054 let mut counts = [0u32; 8];
6055 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
6056 let k = usize::from(i).min(n - 1);
6057 sums[k] += u32::from(sample);
6058 counts[k] += 1;
6059 }
6060 let mut v_colors = [0u16; 8];
6061 for k in 0..n {
6062 v_colors[k] = if counts[k] > 0 {
6063 ((sums[k] + counts[k] / 2) / counts[k]) as u16
6064 } else {
6065 0
6066 };
6067 }
6068 let candidate = crate::tile::PaletteUv {
6069 size: pal.size,
6070 u_colors: pal.colors,
6071 v_colors,
6072 map: pal.map,
6073 };
6074 let predict = |colors: &[u16; 8]| -> Vec<u8> {
6075 candidate
6076 .map
6077 .iter()
6078 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
6079 .collect()
6080 };
6081 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
6082 let u_trial = chroma[0].code_from_prediction(
6083 at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
6084 );
6085 let v_trial = chroma[1].code_from_prediction(
6086 at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
6087 );
6088 let cost_p = u_trial.sse
6089 + v_trial.sse
6090 + search.lambda
6091 * (u_trial.bits
6092 + v_trial.bits
6093 + crate::tile::palette_uv_bits(&candidate, side));
6094 if cost_p < cost {
6095 cost = cost_p;
6096 mode = DC_PRED;
6097 u = u_trial;
6098 v = v_trial;
6099 palette_uv = Some(candidate);
6100 }
6101 }
6102 }
6103 // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
6104 // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
6105 // nudges every sample by `alpha_q3` times the block's subsampled,
6106 // average-subtracted luma reconstruction. Offered only where
6107 // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
6108 // and priced against the best ordinary chroma mode above, palette
6109 // included, so a block only takes it when it beats both.
6110 let mut cfl_alphas = None;
6111 if side <= 32 && cfl_on() {
6112 // The AC signal, through the decoder's own
6113 // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
6114 let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
6115 i32::from(luma.reconstruction[ly * luma.width + lx])
6116 });
6117 let dc_prediction = |plane: &Plane| -> Vec<u8> {
6118 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
6119 let (above, left, corner) =
6120 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
6121 let mut prediction = vec![0u8; at.side * at.side];
6122 intra_predict_u8(
6123 DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction,
6124 fctx,
6125 );
6126 prediction
6127 };
6128 let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
6129 // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
6130 // add the residual -- which is what [`Plane::code_from_prediction`]
6131 // does with what this returns.
6132 let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
6133 base.iter()
6134 .zip(ac.iter())
6135 .map(|(&b, &a)| {
6136 (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
6137 })
6138 .collect()
6139 };
6140 // The least-squares alpha, then its two neighbours: minimising
6141 // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
6142 // dot-product ratio, and the quantised optimum is one of the two
6143 // integers around it (the clamp and the Q6 rounding are what the SSE
6144 // check below re-decides). libaom sweeps all sixteen magnitudes under
6145 // full RD; three predictions per plane buy nearly the same alpha for a
6146 // thirtieth of the search.
6147 let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
6148 let (mut num, mut den) = (0.0f64, 0.0f64);
6149 for row in 0..at.side {
6150 for col in 0..at.side {
6151 let i = row * at.side + col;
6152 let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
6153 - f64::from(base[i]);
6154 num += d * f64::from(ac[i]);
6155 den += f64::from(ac[i]) * f64::from(ac[i]);
6156 }
6157 }
6158 if den == 0.0 {
6159 return 0;
6160 }
6161 let ideal = 64.0 * num / den;
6162 let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
6163 for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
6164 let alpha = alpha.clamp(-16, 16) as i32;
6165 if alpha == 0 {
6166 continue;
6167 }
6168 let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
6169 if sse < best.0 {
6170 best = (sse, alpha);
6171 }
6172 }
6173 best.1
6174 };
6175 let picked = [
6176 pick_alpha(&chroma[0], &bases[0]),
6177 pick_alpha(&chroma[1], &bases[1]),
6178 ];
6179 if picked != [0, 0] {
6180 let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
6181 let trial = |plane_idx: usize, alpha: i32| -> Trial {
6182 let prediction = if alpha == 0 {
6183 bases[plane_idx].clone()
6184 } else {
6185 apply(&bases[plane_idx], alpha)
6186 };
6187 chroma[plane_idx].code_from_prediction(
6188 at.x,
6189 at.y,
6190 at.side,
6191 &prediction,
6192 false,
6193 search.base_q_idx,
6194 search.deadzone,
6195 set,
6196 )
6197 };
6198 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
6199 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
6200 let combos: [(i32, i32); 3] = [
6201 (picked[0], picked[1]),
6202 (picked[0], 0),
6203 (0, picked[1]),
6204 ];
6205 for &(alpha_u, alpha_v) in &combos {
6206 if (alpha_u, alpha_v) == (0, 0) {
6207 continue;
6208 }
6209 let cu = trial(0, alpha_u);
6210 let cv = trial(1, alpha_v);
6211 let bits =
6212 cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
6213 let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
6214 if cost_cfl < cost {
6215 cost = cost_cfl;
6216 mode = crate::tile::UV_CFL_PRED as u8;
6217 u = cu;
6218 v = cv;
6219 palette_uv = None;
6220 cfl_alphas = Some((alpha_u, alpha_v));
6221 }
6222 }
6223 }
6224 }
6225 if let Some((alpha_u, alpha_v)) = cfl_alphas {
6226 for alpha in [alpha_u, alpha_v] {
6227 CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
6228 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6229 }
6230 }
6231 if census_on() {
6232 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
6233 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6234 }
6235 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6236 chroma[0].commit(at.x, at.y, at.side, &u);
6237 chroma[1].commit(at.x, at.y, at.side, &v);
6238 (
6239 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
6240 mode,
6241 cost,
6242 palette_uv,
6243 cfl_alphas,
6244 )
6245}
6246
6247/// Codes one leaf of a straddling quadrant as whichever costs least of intra
6248/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
6249/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
6250/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
6251/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
6252/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
6253/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
6254/// attempted here: these leaves only ever fill the sliver of real content a
6255/// true edge lands in the middle of a larger block, not a leaf worth a full
6256/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
6257/// (see `write_inter_frame_leaf`'s doc comment).
6258#[allow(clippy::too_many_arguments)]
6259/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
6260/// as [`code_square_inter`] wants them: empty on a frame that codes no
6261/// `reference_select`, or when the leaf compound candidates are switched off.
6262/// One helper because THREE leaf call sites need it -- the split quadrants
6263/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
6264/// `&[]` and so coded no compound block anywhere along the frame's true edge.
6265#[allow(clippy::too_many_arguments)]
6266fn leaf_compound_stacks<'a>(
6267 grid: &MiGrid,
6268 mi_row: usize,
6269 mi_col: usize,
6270 bw4: usize,
6271 bh4: usize,
6272 mi_cols: usize,
6273 mi_rows: usize,
6274 reference_select: bool,
6275 golden: Option<&'a Picture>,
6276 altref: Option<&'a Picture>,
6277) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
6278 if !(reference_select && leaf_compound()) {
6279 return Vec::new();
6280 }
6281 [
6282 (crate::mvstack::GOLDEN_FRAME, golden),
6283 (crate::mvstack::ALTREF_FRAME, altref),
6284 ]
6285 .into_iter()
6286 .filter_map(|(r, pic)| {
6287 pic.map(|p| {
6288 (
6289 r,
6290 p,
6291 crate::mvstack::find_mv_stack_compound(
6292 grid, mi_row, mi_col, bw4, bh4,
6293 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6294 grid.sign_bias_table(), &[(0, 0); 7], None,
6295 ),
6296 )
6297 })
6298 })
6299 .collect()
6300}
6301
6302/// The OBMC prediction of one square single-reference block: this block's own
6303/// translation prediction (`mc::predict`) with every bordering above/left
6304/// neighbour blended into the overlap strips by the DECODER's own plan and
6305/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
6306/// the search prices is what a decoder reconstructs -- never a second
6307/// implementation of the blend. `None` when the block has no overlappable
6308/// neighbour at all (the writer would then code no `motion_mode` symbol) or
6309/// when the plan cannot be built (a neighbour naming a reference this encode
6310/// does not hold).
6311#[allow(clippy::too_many_arguments)]
6312fn obmc_prediction(
6313 grid: &MiGrid,
6314 (mi_row, mi_col): (usize, usize),
6315 (mi_rows, mi_cols): (usize, usize),
6316 (x, y): (usize, usize),
6317 side: usize,
6318 mv: (i32, i32),
6319 refs: &[Option<&Picture>; 8],
6320 // This block's OWN reference planes, luma then both chroma, each as
6321 // (samples, stride, true width, true height).
6322 ref_planes: [(&[u16], usize, usize, usize); 3],
6323 frame_width: usize,
6324 fctx: &crate::decode::FrameCtx,
6325) -> Option<[Vec<u8>; 3]> {
6326 let n4 = side / 4;
6327 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
6328 return None;
6329 }
6330 let refpix = crate::decode::RefPix::ready(*refs);
6331 let plan = crate::decode::obmc_plan(
6332 grid,
6333 &[],
6334 &[],
6335 mi_row,
6336 mi_col,
6337 n4,
6338 n4,
6339 mi_rows,
6340 mi_cols,
6341 side,
6342 side,
6343 side,
6344 side / 2,
6345 x,
6346 y,
6347 x / 2,
6348 y / 2,
6349 &refpix,
6350 Some(fctx.interp_filter.get()),
6351 frame_width,
6352 )
6353 .ok()?;
6354 let mut pred = [
6355 vec![0u16; side * side],
6356 vec![0u16; side * side / 4],
6357 vec![0u16; side * side / 4],
6358 ];
6359 for (i, r) in ref_planes.into_iter().enumerate() {
6360 let luma_plane = i == 0;
6361 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
6362 let s = if luma_plane { side } else { side / 2 };
6363 mc::predict(
6364 r.0,
6365 r.1,
6366 r.2,
6367 r.3,
6368 mv_to_q4(px, mv.1, luma_plane),
6369 mv_to_q4(py, mv.0, luma_plane),
6370 s,
6371 s,
6372 &mut pred[i],
6373 fctx,
6374 );
6375 }
6376 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
6377 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
6378 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
6379 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
6380}
6381
6382fn code_square_inter(
6383 luma: &mut Plane,
6384 chroma: &mut [Plane; 2],
6385 (x, y): (usize, usize),
6386 side: usize,
6387 search: &Search,
6388 mode_bits: &[f64; 13],
6389 reference: &Picture,
6390 stack: &MvStack,
6391 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
6392 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
6393 // `reference_select`, and at the straddling call sites).
6394 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
6395 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
6396 // (`record_mi`, in the writer's own coding order) and this leaf's place in
6397 // it -- what the OBMC candidate's eligibility walk and neighbour plan
6398 // read, the same state the tile writer reads when it codes the leaf's
6399 // `motion_mode` symbol.
6400 grid: &MiGrid,
6401 (mi_row, mi_col): (usize, usize),
6402 (mi_rows, mi_cols): (usize, usize),
6403 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
6404 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
6405 refs: &[Option<&Picture>; 8],
6406 fctx: &crate::decode::FrameCtx,
6407) -> (BlockCoeffs, f64) {
6408 let (intra_block, intra_cost) =
6409 code_square(
6410 luma,
6411 chroma,
6412 (x, y),
6413 side,
6414 search,
6415 mode_bits,
6416 tx_select() && tx_select_inter(),
6417 None,
6418 false,
6419 fctx,
6420 );
6421 let luma_set = if side == 8 {
6422 TxbSet::Luma8Inter
6423 } else {
6424 TxbSet::Luma16Inter
6425 };
6426 let chroma_set = if side == 8 {
6427 TxbSet::Chroma4
6428 } else {
6429 TxbSet::Chroma8
6430 };
6431
6432 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
6433 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
6434 let single_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
6435 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
6436 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
6437 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
6438
6439 let mv = stack.nearest_mv;
6440 let ref_luma = (
6441 &reference.y,
6442 reference.width,
6443 luma.true_width,
6444 luma.true_height,
6445 );
6446 let ref_u = (
6447 &reference.u,
6448 reference.width / 2,
6449 chroma[0].true_width,
6450 chroma[0].true_height,
6451 );
6452 let ref_v = (
6453 &reference.v,
6454 reference.width / 2,
6455 chroma[1].true_width,
6456 chroma[1].true_height,
6457 );
6458 let luma_trial = mc_trial(
6459 luma,
6460 x,
6461 y,
6462 side,
6463 mv,
6464 true,
6465 ref_luma.0,
6466 ref_luma.1,
6467 ref_luma.2,
6468 ref_luma.3,
6469 false,
6470 search.base_q_idx,
6471 search.deadzone,
6472 luma_set, fctx,
6473 );
6474 let u = mc_trial(
6475 &chroma[0],
6476 x / 2,
6477 y / 2,
6478 side / 2,
6479 mv,
6480 false,
6481 ref_u.0,
6482 ref_u.1,
6483 ref_u.2,
6484 ref_u.3,
6485 false,
6486 search.base_q_idx,
6487 search.deadzone,
6488 chroma_set, fctx,
6489 );
6490 let v = mc_trial(
6491 &chroma[1],
6492 x / 2,
6493 y / 2,
6494 side / 2,
6495 mv,
6496 false,
6497 ref_v.0,
6498 ref_v.1,
6499 ref_v.2,
6500 ref_v.3,
6501 false,
6502 search.base_q_idx,
6503 search.deadzone,
6504 chroma_set, fctx,
6505 );
6506 let skip = luma_trial.levels.iter().all(|&l| l == 0)
6507 && u.levels.iter().all(|&l| l == 0)
6508 && v.levels.iter().all(|&l| l == 0);
6509 let inter_cost = luma_trial.sse
6510 + u.sse
6511 + v.sse
6512 + search.lambda
6513 * (skip_bits(skip)
6514 + intra_inter_bits(true)
6515 + single_ref_bits
6516 + mode_bits_inter
6517 + if skip {
6518 0.0
6519 } else {
6520 luma_trial.bits + u.bits + v.bits
6521 });
6522
6523 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
6524 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
6525 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
6526 // scan's own coverage already reached as far) but a real gap at 4-mi
6527 // leaf geometry. r3 ported the extended scan and, while proving it a
6528 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
6529 // `mvstack.rs`), found and fixed a second bug the extended scan's
6530 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
6531 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
6532 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
6533 // regardless of whether it also casts a ref-frame-matching vote) --
6534 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
6535 // branches), which is what made 8-mi geometry a true no-op instead of
6536 // one that only held when every neighbour happened to be inter.
6537 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
6538 // only ever took the stack's NEARESTMV candidate or went intra, so a
6539 // 32x32 block splitting because its four quarters MOVE differently could
6540 // not code the movement it split for. Same candidate `search_inter_block`
6541 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
6542 // a vector the residual syntax can name -- at this leaf's own side.
6543 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
6544 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
6545 // re-price below can hand it back as the winner's own mode info.
6546 let nearest_info = InterInfo {
6547 ref1: None,
6548 mv1: (0, 0),
6549 ref_frame: crate::mvstack::LAST_FRAME,
6550 mode: InterMode::NearestMv,
6551 mv,
6552 ref_mv_idx: 0,
6553 };
6554 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
6555 // syntax, apart from its residual: the OBMC candidate re-prices the same
6556 // syntax against a different prediction, so both sides of that comparison
6557 // carry it.
6558 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
6559 // This leaf's own `NEWMV` vector, kept whether or not it won the
6560 // single-reference comparison: it seeds the compound half-new candidate
6561 // below, exactly as `search_inter_block` seeds its own from the searches
6562 // it already ran.
6563 let mut searched_new: Option<(i32, i32)> = None;
6564 // What that search cost, kept for the second reference's own early-out
6565 // below (`None` when this leaf ran no search at all).
6566 let mut searched_new_cost: Option<f64> = None;
6567 let source_block = luma.source_block(x, y, side);
6568 if leaf_new_mv() {
6569 let (seeds, seed_n) = mv_seeds(stack);
6570 let found = motion::search(
6571 ref_luma.0,
6572 ref_luma.1,
6573 ref_luma.2,
6574 ref_luma.3,
6575 &source_block,
6576 x,
6577 y,
6578 side,
6579 side,
6580 stack.pred_mv,
6581 &seeds[..seed_n],
6582 search.lambda, fctx,
6583 1,
6584 );
6585 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
6586 searched_new_cost = Some(found.cost);
6587 let mv_residual = mv_residual_bits(new_mv, stack.pred_mv);
6588 if mv_residual.is_none() {
6589 // lane-newmv: a vector the writer cannot name never reaches RD.
6590 newmv_census_block(side, false, f64::INFINITY, best.0, new_mv, stack.nearest_mv, 0.0);
6591 }
6592 if let Some(mv_bits) = mv_residual {
6593 searched_new = Some(new_mv);
6594 // Same reuse as `search_inter_block`: a NEWMV equal to the
6595 // stack's NEARESTMV is the same three trials, already run above.
6596 let (luma_new, u_new, v_new) = if new_mv == mv {
6597 (luma_trial.clone(), u.clone(), v.clone())
6598 } else {
6599 (
6600 mc_trial(
6601 luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2,
6602 ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx,
6603 ),
6604 mc_trial(
6605 &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1,
6606 ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set,
6607 fctx,
6608 ),
6609 mc_trial(
6610 &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1,
6611 ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set,
6612 fctx,
6613 ),
6614 )
6615 };
6616 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
6617 && u_new.levels.iter().all(|&l| l == 0)
6618 && v_new.levels.iter().all(|&l| l == 0);
6619 let drl_bits = if stack.entries.len() > 1 {
6620 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
6621 } else {
6622 0.0
6623 };
6624 let cost_new = luma_new.sse
6625 + u_new.sse
6626 + v_new.sse
6627 + search.lambda
6628 * (skip_bits(skip_new)
6629 + intra_inter_bits(true)
6630 + single_ref_bits
6631 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
6632 + drl_bits
6633 + mv_bits
6634 + mv_rate_surcharge(mv_bits)
6635 + if skip_new {
6636 0.0
6637 } else {
6638 luma_new.bits + u_new.bits + v_new.bits
6639 });
6640 newmv_census_block(side, true, cost_new, best.0, new_mv, stack.nearest_mv, mv_bits);
6641 if cost_new < best.0 {
6642 single_syntax = intra_inter_bits(true)
6643 + single_ref_bits
6644 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
6645 + drl_bits
6646 + mv_bits;
6647 best = (
6648 cost_new,
6649 Some((
6650 luma_new,
6651 u_new,
6652 v_new,
6653 skip_new,
6654 InterInfo {
6655 ref1: None,
6656 mv1: (0, 0),
6657 ref_frame: crate::mvstack::LAST_FRAME,
6658 mode: InterMode::NewMv,
6659 mv: new_mv,
6660 ref_mv_idx: 0,
6661 },
6662 )),
6663 );
6664 }
6665 }
6666 }
6667
6668 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
6669 // `search_inter_block` prices for a whole 32x32 block:
6670 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
6671 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
6672 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
6673 // too. Priced with the same static-CDF approximation, plus the
6674 // compound-only syntax the writer emits.
6675 for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) {
6676 let (ref1, g) = (*ref1, *g);
6677 // The whole `comp_mode` + reference-pair tree at the writer's own
6678 // contexts, for THIS pair (lane-ctx).
6679 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
6680 let mode_ctx =
6681 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
6682 let mode_bits_of =
6683 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
6684 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
6685 (
6686 cstack.nearest_mv,
6687 mode_bits_of(0),
6688 InterInfo {
6689 ref_frame: crate::mvstack::LAST_FRAME,
6690 mode: InterMode::NearestNearestMv,
6691 mv: cstack.nearest_mv.0,
6692 mv1: cstack.nearest_mv.1,
6693 ref1: Some(ref1),
6694 ref_mv_idx: 0,
6695 },
6696 ),
6697 (
6698 ((0, 0), (0, 0)),
6699 mode_bits_of(6),
6700 InterInfo {
6701 ref_frame: crate::mvstack::LAST_FRAME,
6702 mode: InterMode::GlobalGlobalMv,
6703 mv: (0, 0),
6704 mv1: (0, 0),
6705 ref1: Some(ref1),
6706 ref_mv_idx: 0,
6707 },
6708 ),
6709 ];
6710 // Every compound MV residual here is priced against compound stack
6711 // entry 0, which is what `assign_compound_mv` predicts from at
6712 // `ref_mv_idx = 0` -- so it is also what the second-reference search
6713 // below seeds from and rounds to, and no candidate it finds can then
6714 // fail `mv_residual_bits`.
6715 let cbase = cstack
6716 .entries
6717 .first()
6718 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
6719 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
6720 // it a leaf could only name a stack vector for the second half, and
6721 // screen capture showed the consequence: every leaf compound block
6722 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
6723 // extra-reference `NEWMV`, when this reference's own
6724 // `NEAREST_NEARESTMV` vector already prices `margin` times better
6725 // than the `LAST` search of this same leaf did -- one candidate
6726 // evaluation standing in for a whole search.
6727 let margin = leaf_second_new_margin();
6728 let mut second_new: Option<(i32, i32)> = None;
6729 if leaf_second_new_mv() {
6730 newmv_census_global(2);
6731 let skip = margin > 0.0
6732 && searched_new_cost.is_some_and(|last| {
6733 motion::cost_at(
6734 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y,
6735 side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx,
6736 ) * margin
6737 <= last
6738 });
6739 if skip {
6740 newmv_census_global(3);
6741 }
6742 if !skip {
6743 let mut seeds = [(0, 0); 4];
6744 let mut seed_n = 1;
6745 for e in cstack.entries.iter().take(3) {
6746 seeds[seed_n] = e.mv1;
6747 seed_n += 1;
6748 }
6749 let found = motion::search(
6750 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side,
6751 side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1),
6752 );
6753 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
6754 }
6755 }
6756 if let Some(new_mv) = searched_new {
6757 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
6758 ccands.push((
6759 (new_mv, cstack.nearest_mv.1),
6760 mode_bits_of(3) + b0,
6761 InterInfo {
6762 ref_frame: crate::mvstack::LAST_FRAME,
6763 mode: InterMode::NewNearestMv,
6764 mv: new_mv,
6765 mv1: cstack.nearest_mv.1,
6766 ref1: Some(ref1),
6767 ref_mv_idx: 0,
6768 },
6769 ));
6770 }
6771 }
6772 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
6773 // searches this leaf ran, each residual priced against `cbase`.
6774 if let Some(mv1) = second_new {
6775 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
6776 ccands.push((
6777 (cstack.nearest_mv.0, mv1),
6778 mode_bits_of(2) + b1,
6779 InterInfo {
6780 ref_frame: crate::mvstack::LAST_FRAME,
6781 mode: InterMode::NearestNewMv,
6782 mv: cstack.nearest_mv.0,
6783 mv1,
6784 ref1: Some(ref1),
6785 ref_mv_idx: 0,
6786 },
6787 ));
6788 if let Some((new_mv, b0)) =
6789 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
6790 {
6791 ccands.push((
6792 (new_mv, mv1),
6793 mode_bits_of(7) + b0 + b1,
6794 InterInfo {
6795 ref_frame: crate::mvstack::LAST_FRAME,
6796 mode: InterMode::NewNewMv,
6797 mv: new_mv,
6798 mv1,
6799 ref1: Some(ref1),
6800 ref_mv_idx: 0,
6801 },
6802 ));
6803 }
6804 }
6805 }
6806 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
6807 ccands.dedup_by_key(|c| c.0);
6808 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
6809 let g_u = (
6810 g.u.as_slice(),
6811 g.width / 2,
6812 chroma[0].true_width,
6813 chroma[0].true_height,
6814 );
6815 let g_v = (
6816 g.v.as_slice(),
6817 g.width / 2,
6818 chroma[1].true_width,
6819 chroma[1].true_height,
6820 );
6821 for (mvs, bits, info) in ccands {
6822 let luma_c = mc_trial_compound(
6823 luma, x, y, side, mvs, true,
6824 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
6825 search.base_q_idx, search.deadzone, luma_set, fctx,
6826 );
6827 let u_c = mc_trial_compound(
6828 &chroma[0], x / 2, y / 2, side / 2, mvs, false,
6829 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
6830 search.base_q_idx, search.deadzone, chroma_set, fctx,
6831 );
6832 let v_c = mc_trial_compound(
6833 &chroma[1], x / 2, y / 2, side / 2, mvs, false,
6834 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
6835 search.base_q_idx, search.deadzone, chroma_set, fctx,
6836 );
6837 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
6838 && u_c.levels.iter().all(|&l| l == 0)
6839 && v_c.levels.iter().all(|&l| l == 0);
6840 let cost_c = luma_c.sse
6841 + u_c.sse
6842 + v_c.sse
6843 + search.lambda
6844 * (skip_bits(skip_c)
6845 + intra_inter_bits(true)
6846 + bits
6847 + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
6848 if cost_c < best.0 {
6849 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
6850 }
6851 }
6852 }
6853
6854 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
6855 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
6856 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
6857 // the writer codes no symbol for one. The prediction is the decoder's own
6858 // plan and blend over the neighbours this leaf's `grid` already carries
6859 // (published by `record_mi` in the writer's coding order), so the
6860 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
6861 // offered this only at 32x32, which is not where libaom cashes its OBMC
6862 // gain.
6863 let mut motion_won = 0u8;
6864 let single = match &best.1 {
6865 None => Some(nearest_info),
6866 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
6867 Some(_) => None,
6868 };
6869 if let Some(info) = single.filter(|i| {
6870 (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on())
6871 && i.ref_frame == crate::mvstack::LAST_FRAME
6872 }) {
6873 let planes = [
6874 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
6875 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
6876 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
6877 ];
6878 // Which alphabet this block's writer will code the symbol against
6879 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
6880 // 3-symbol one only under `allow_warped_motion` and at least one warp
6881 // sample. Mirrored here so the candidates are priced against the
6882 // table the tile really narrows.
6883 let warp_alphabet = warp_on()
6884 && crate::decode::num_proj_ref(
6885 grid,
6886 mi_row,
6887 mi_col,
6888 side / 4,
6889 side / 4,
6890 mi_cols,
6891 mi_rows,
6892 info.ref_frame,
6893 fctx,
6894 ) >= 1;
6895 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
6896 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
6897 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
6898 if let Some(pred) = obmc_prediction(
6899 grid,
6900 (mi_row, mi_col),
6901 (mi_rows, mi_cols),
6902 (x, y),
6903 side,
6904 info.mv,
6905 refs,
6906 planes,
6907 reference.width,
6908 fctx,
6909 ) {
6910 candidates.push((1, pred));
6911 }
6912 }
6913 if warp_alphabet {
6914 if let Some(pred) = warp_prediction(
6915 grid,
6916 (mi_row, mi_col),
6917 (mi_rows, mi_cols),
6918 (x, y),
6919 side,
6920 info.mv,
6921 info.ref_frame,
6922 planes,
6923 fctx,
6924 ) {
6925 candidates.push((2, pred));
6926 }
6927 }
6928 for (motion, pred) in candidates {
6929 let luma_o = luma.code_from_prediction(
6930 x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set,
6931 );
6932 let u_o = chroma[0].code_from_prediction(
6933 x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone,
6934 chroma_set,
6935 );
6936 let v_o = chroma[1].code_from_prediction(
6937 x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone,
6938 chroma_set,
6939 );
6940 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
6941 && u_o.levels.iter().all(|&l| l == 0)
6942 && v_o.levels.iter().all(|&l| l == 0);
6943 let cost_o = luma_o.sse
6944 + u_o.sse
6945 + v_o.sse
6946 + search.lambda
6947 * (skip_bits(skip_o)
6948 + single_syntax
6949 + mm(motion)
6950 + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits });
6951 // The incumbent pays the motion_mode symbol IT would code, so
6952 // both sides of the comparison carry that syntax.
6953 if cost_o < best.0 + search.lambda * mm(motion_won) {
6954 motion_won = motion;
6955 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
6956 }
6957 }
6958 }
6959
6960 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
6961 if cost < intra_cost {
6962 // A compound winner commits the flat trial it was priced from:
6963 // `commit_inter_luma`'s var-tx trial set is single-reference
6964 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
6965 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
6966 // predicting each half-side trial from BOTH references, verified
6967 // byte-identical to this when its split is disabled) and MEASURED
6968 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
6969 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
6970 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
6971 // compound block's residual is small enough that the four extra
6972 // per-unit txb_skip/eob symbols cost more ladder bytes than this
6973 // encoder's static-CDF estimate prices them at, so the local RD
6974 // win does not convert. lane-av1txbits REBUILT it on top of a
6975 // search that prices against the tables the frame is really
6976 // written with (`tile::arm_pricing_cdfs`, the estimate error on
6977 // these very blocks measured down from +31% to +3%) and measured
6978 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
6979 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
6980 // same build without it. The static-CDF estimate was NOT what
6981 // held the compound var-tx trial back. The flat trial stays.
6982 // An OBMC winner commits the flat trial too: `commit_inter_luma`
6983 // re-predicts each var-tx unit by plain translation, which is not
6984 // the prediction this candidate was priced from.
6985 // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
6986 // 0.05 (both rejections above were measured at 0.1, the weight
6987 // the lambda lane showed was 2x too heavy): a compound winner is
6988 // offered the same var-tx split, its units predicted from BOTH
6989 // references (`mc_trial_compound`). RE-MEASURED native: film
6990 // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
6991 // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
6992 // one row 0.2 down, two flat, short of the two-down-one-flat keep
6993 // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
6994 // rather than change the default on a single 0.2 row. It fires:
6995 // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
6996 // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
6997 // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
6998 // 1.3/1.2 down there, which is where the upgrade path is if this
6999 // is picked up again.
7000 let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
7001 refs[r as usize].map(|g| {
7002 (
7003 info.mv1,
7004 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
7005 )
7006 })
7007 });
7008 let (levels, tx_depth, dcost, luma_tx_types) = if motion_won != 0
7009 || (info.ref1.is_some() && second.is_none())
7010 {
7011 luma.commit(x, y, side, &luma_new);
7012 (luma_new.levels.clone(), 0, 0.0, Vec::new())
7013 } else {
7014 commit_inter_luma(
7015 luma, (x, y), side, info.mv,
7016 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7017 search, &luma_new, skip_new, second, fctx,
7018 )
7019 };
7020 // lane-txrd: chroma follows the luma type the search just chose.
7021 let [u_new, v_new] = match luma_tx_types.first().copied() {
7022 Some(t) => recode_inter_chroma(
7023 chroma, (x, y), side, info.mv,
7024 [
7025 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7026 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7027 ],
7028 info.ref1.filter(|_| motion_won == 0).and_then(|r| {
7029 refs[r as usize].map(|g| {
7030 (
7031 info.mv1,
7032 [
7033 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
7034 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
7035 ],
7036 )
7037 })
7038 }),
7039 search, chroma_set, t, fctx,
7040 )
7041 .unwrap_or([u_new, v_new]),
7042 None => [u_new, v_new],
7043 };
7044 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
7045 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
7046 return (
7047 BlockCoeffs {
7048 angle_delta_y: 0,
7049 cfl_alphas: None,
7050 filter_intra: None,
7051 luma: coeffs(&levels, side),
7052 u: coeffs(&u_new.levels, side / 2),
7053 v: coeffs(&v_new.levels, side / 2),
7054 mode: DC_PRED as u8,
7055 uv_mode: DC_PRED,
7056 skip: skip_new,
7057 eight: None,
7058 dv: None,
7059 palette: None,
7060 palette_uv: None,
7061 tx_depth,
7062 luma_tx_types,
7063 inter: Some(info),
7064 motion_mode: motion_won,
7065 },
7066 cost + dcost,
7067 );
7068 }
7069 }
7070
7071 census_add(8, 1);
7072 if skip {
7073 census_add(10, 1);
7074 }
7075 if inter_cost >= intra_cost {
7076 census_add(9, 1);
7077 }
7078 if inter_cost < intra_cost {
7079 let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma(
7080 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,
7081 );
7082 // lane-txrd: chroma follows the luma type (this tail's block is
7083 // single-reference `NEARESTMV`, so no compound second half).
7084 let [u, v] = match luma_tx_types.first().copied() {
7085 Some(t) => recode_inter_chroma(
7086 chroma, (x, y), side, mv,
7087 [
7088 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7089 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7090 ],
7091 None, search, chroma_set, t, fctx,
7092 )
7093 .unwrap_or([u, v]),
7094 None => [u, v],
7095 };
7096 chroma[0].commit(x / 2, y / 2, side / 2, &u);
7097 chroma[1].commit(x / 2, y / 2, side / 2, &v);
7098 (BlockCoeffs {
7099 luma_tx_types,
7100 angle_delta_y: 0,
7101 cfl_alphas: None,
7102 filter_intra: None,
7103 luma: coeffs(&levels, side),
7104 u: coeffs(&u.levels, side / 2),
7105 v: coeffs(&v.levels, side / 2),
7106 mode: DC_PRED as u8,
7107 uv_mode: DC_PRED,
7108 skip,
7109 eight: None,
7110 dv: None,
7111 palette: None,
7112 palette_uv: None,
7113 tx_depth,
7114 motion_mode: 0,
7115 inter: Some(InterInfo {
7116 ref1: None,
7117 mv1: (0, 0),
7118 ref_frame: crate::mvstack::LAST_FRAME,
7119 mode: InterMode::NearestMv,
7120 mv,
7121 ref_mv_idx: 0,
7122 }),
7123 }, inter_cost + dcost)
7124 } else {
7125 (intra_block, intra_cost)
7126 }
7127}
7128
7129/// Publishes one coded inter-frame block into the `mi` grid the next block's
7130/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
7131/// block casts no vote but is still a coded cell (see `code_square_inter`'s
7132/// note on `processed_rows`/`processed_cols`).
7133fn record_mi(
7134 grid: &mut MiGrid,
7135 mi_row: usize,
7136 mi_col: usize,
7137 size: u8,
7138 inter: Option<InterInfo>,
7139 // lane-ctx: the block's own `skip`, so the next block's MV stack can hand
7140 // the RD pricer the two cells the writer's `skip_ctx` sums.
7141 skip: bool,
7142) {
7143 let info = match inter {
7144 Some(info) => MiInfo {
7145 is_inter: true,
7146 ref_frame: info.ref_frame,
7147 // A COMPOUND block votes with BOTH of its references and both of
7148 // its vectors, exactly as the tile writer publishes it: recording
7149 // a compound block as a single-reference one here left the
7150 // encoder's own grid disagreeing with the writer's from the first
7151 // compound block on, so every later stack it searched against was
7152 // not the stack the decoder derives.
7153 ref_frame1: info.ref1.unwrap_or(NO_REF1),
7154 mv1: mv16(info.mv1),
7155 mv: mv16(info.mv),
7156 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
7157 // side, compound modes 2/3/7 on the other.
7158 is_new_mv: matches!(
7159 info.mode,
7160 InterMode::NewMv
7161 | InterMode::NewNewMv
7162 | InterMode::NearestNewMv
7163 | InterMode::NewNearestMv
7164 ),
7165 size,
7166 size_h: size,
7167 is_global_mv0: false,
7168 is_global_mv1: false,
7169 },
7170 None => MiInfo {
7171 is_inter: false,
7172 ref_frame: -1,
7173 ref_frame1: NO_REF1,
7174 mv1: (0, 0),
7175 mv: (0, 0),
7176 is_new_mv: false,
7177 size,
7178 size_h: size,
7179 is_global_mv0: false,
7180 is_global_mv1: false,
7181 },
7182 };
7183 for dr in 0..usize::from(size) {
7184 for dc in 0..usize::from(size) {
7185 grid.set(mi_row + dr, mi_col + dc, info);
7186 grid.set_skip(mi_row + dr, mi_col + dc, skip);
7187 }
7188 }
7189}
7190
7191/// The reconstructed samples one 32x32 square covers in all three planes, so
7192/// that a partition trial can be undone.
7193/// One square of a plane, row-major, the inverse of [`Plane::restore`].
7194///
7195/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
7196/// which allocated and freed a `Vec` per row of every block it copied --
7197/// `Plane::snapshot` runs once per partition trial.
7198fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
7199 let mut out = vec![0u8; side * side];
7200 for row in 0..side {
7201 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
7202 }
7203 out
7204}
7205
7206fn snapshot(
7207 luma: &Plane,
7208 chroma: &[Plane; 2],
7209 (x, y): (usize, usize),
7210 side: usize,
7211) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
7212 [
7213 luma.snapshot(x, y, side),
7214 chroma[0].snapshot(x / 2, y / 2, side / 2),
7215 chroma[1].snapshot(x / 2, y / 2, side / 2),
7216 ]
7217}
7218
7219/// Puts such a snapshot back.
7220fn restore(
7221 luma: &mut Plane,
7222 chroma: &mut [Plane; 2],
7223 (x, y): (usize, usize),
7224 side: usize,
7225 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
7226) {
7227 luma.restore(x, y, side, &saved[0]);
7228 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
7229 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
7230}
7231
7232/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
7233/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
7234/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
7235/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
7236/// rule shared with the key-frame path, not a second one that could diverge.
7237fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
7238 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
7239 let dc_entry = dc_pos.map(|i| scored.remove(i));
7240 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
7241 scored.truncate(if dc_entry.is_some() {
7242 top_k.saturating_sub(1)
7243 } else {
7244 top_k
7245 });
7246 if let Some(dc_entry) = dc_entry {
7247 scored.push(dc_entry);
7248 }
7249 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
7250 modes.iter().copied().filter(|m| keep.contains(m)).collect()
7251}
7252
7253fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
7254 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
7255 [INTRA_MODE_CTX[usize::from(left_mode)]];
7256 std::array::from_fn(|mode| {
7257 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
7258 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
7259 } else {
7260 0.0
7261 };
7262 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
7263 })
7264}
7265
7266/// What the luma mode search picks between, and under what terms.
7267#[derive(Clone, Copy)]
7268struct Search<'a> {
7269 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
7270 /// luma search then offers a palette candidate beside the intra modes.
7271 screen: bool,
7272 base_q_idx: u8,
7273 deadzone: f64,
7274 lambda: f64,
7275 modes: &'a [u8],
7276 /// How many of `modes` the full RD trial (forward transform, quantize,
7277 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
7278 /// pre-pass on the prediction residual alone plus DC (always kept, since
7279 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
7280 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
7281 /// mode through full RD, unchanged from before this lever.
7282 top_k: Option<usize>,
7283}
7284
7285/// [`Search::top_k`]'s value: `None` keeps every mode's search unchanged
7286/// (the default, until a lever's quality gate justifies pruning by default);
7287/// `EC_AV1_PRUNE_K` sweeps it in a test build without touching callers.
7288fn prune_top_k() -> Option<usize> {
7289 #[cfg(test)]
7290 {
7291 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
7292 return k;
7293 }
7294 }
7295 let swept = std::env::var("EC_AV1_PRUNE_K")
7296 .ok()
7297 .and_then(|v| v.parse::<usize>().ok());
7298 match swept {
7299 Some(k) if cfg!(test) => Some(k),
7300 _ => crate::speed::at(&crate::speed::PRUNE_K),
7301 }
7302}
7303
7304// A per-thread override [`prune_top_k`] checks first, so one test can sweep
7305// `top_k` in-process without mutating the environment (forbidden here --
7306// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
7307#[cfg(test)]
7308thread_local! {
7309 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
7310 const { std::cell::Cell::new(None) };
7311}
7312
7313#[cfg(test)]
7314fn set_test_top_k_override(value: Option<usize>) {
7315 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
7316}
7317
7318/// The default: unpruned, thirteen full trials per block, same as before this
7319/// lever. Set from the sweep in the lane report if the quality gate clears it.
7320pub(crate) const PRUNE_TOP_K: Option<usize> = None;
7321
7322/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
7323/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
7324/// quality gates were measured separately and may land on different
7325/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
7326/// [`EC_AV1_PRUNE_K`] or the key-frame path.
7327fn prune_top_k_inter() -> Option<usize> {
7328 #[cfg(test)]
7329 {
7330 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
7331 return k;
7332 }
7333 }
7334 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
7335 .ok()
7336 .and_then(|v| v.parse::<usize>().ok());
7337 match swept {
7338 Some(k) if cfg!(test) => Some(k),
7339 _ => crate::speed::at(&crate::speed::PRUNE_K_INTER),
7340 }
7341}
7342
7343// A per-thread override [`prune_top_k_inter`] checks first, same reason as
7344// [`TEST_TOP_K_OVERRIDE`].
7345#[cfg(test)]
7346thread_local! {
7347 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
7348 const { std::cell::Cell::new(None) };
7349}
7350
7351#[cfg(test)]
7352fn set_test_top_k_override_inter(value: Option<usize>) {
7353 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
7354}
7355
7356/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
7357/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
7358/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
7359/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
7360/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
7361/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
7362/// pruning them costs less quality here.
7363pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
7364
7365// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
7366// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
7367// inter frame's cost can be attributed to a bucket without changing what
7368// the search actually does. Index: 0 = whole-call time inside
7369// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
7370// [`crate::mc::predict`] (every call, from the motion search's own
7371// candidates and from a committed inter block's final prediction alike),
7372// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
7373#[cfg(test)]
7374thread_local! {
7375 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
7376 std::cell::Cell::new(0),
7377 std::cell::Cell::new(0),
7378 std::cell::Cell::new(0),
7379 std::cell::Cell::new(0),
7380 ];
7381}
7382
7383/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and
7384/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran
7385/// per transform trial and per `mc::predict` call whether or not anyone was
7386/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile).
7387/// The clock is now read only when [`crate::par::stage_times`] is on, which
7388/// is what prints the breakdown in the first place.
7389#[cfg(test)]
7390pub(crate) fn stage_start() -> Option<std::time::Instant> {
7391 crate::par::stage_times().then(std::time::Instant::now)
7392}
7393
7394#[cfg(test)]
7395pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) {
7396 if let Some(t) = t {
7397 stage_add(bucket, t.elapsed());
7398 }
7399}
7400
7401#[cfg(test)]
7402pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
7403 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
7404}
7405
7406#[cfg(test)]
7407fn stage_reset() {
7408 crate::par::set_stage_times(true);
7409 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
7410}
7411
7412#[cfg(test)]
7413fn stage_read() -> [std::time::Duration; 4] {
7414 crate::par::set_stage_times(false);
7415 STAGE_NS.with(|c| {
7416 c.each_ref()
7417 .map(|cell| std::time::Duration::from_nanos(cell.get()))
7418 })
7419}
7420
7421/// One mode's coding of one block, before it is committed.
7422#[derive(Clone)]
7423struct Trial {
7424 levels: Vec<i32>,
7425 reconstruction: Vec<u8>,
7426 sse: f64,
7427 bits: f64,
7428}
7429
7430/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part
7431/// of a 64-point transform that is actually coded (everything outside it is
7432/// zeroed by [`crate::transform::quantize`] already, so this only reshapes).
7433fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> {
7434 let mut out = vec![0i32; to * to];
7435 for row in 0..to {
7436 out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]);
7437 }
7438 out
7439}
7440
7441/// The non-zero levels of a block, as the tile writer takes them.
7442fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
7443 levels
7444 .iter()
7445 .enumerate()
7446 .filter(|&(_, &level)| level != 0)
7447 .map(|(i, &level)| Coeff {
7448 row: (i / side) as u8,
7449 col: (i % side) as u8,
7450 level,
7451 })
7452 .collect()
7453}
7454
7455thread_local! {
7456 /// The tile grid the next frame is coded with, as `(TileColsLog2,
7457 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
7458 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
7459 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
7460 /// one tile per frame, what every caller that never arms anything gets
7461 /// and what every stream this crate wrote before tiles existed carries.
7462 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
7463}
7464
7465/// Arms this thread's next frame encodes with a tile grid (log2 counts).
7466pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
7467 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
7468}
7469
7470fn armed_tiles() -> (u32, u32) {
7471 let armed = TILE_LOG2.with(std::cell::Cell::get);
7472 if armed != (0, 0) {
7473 return armed;
7474 }
7475 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
7476 // (which codes through `encode_sequence`, not the facade) can measure what
7477 // a tile grid costs without a knob of its own -- same shape as
7478 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
7479 match std::env::var("EC_AV1_TILES").ok() {
7480 Some(v) if cfg!(test) => {
7481 let mut f = v.split(':');
7482 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
7483 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
7484 (cols, rows)
7485 }
7486 _ => armed,
7487 }
7488}
7489
7490/// Codes a frame's `tiles` tiles, each entirely on its own (see
7491/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
7492/// the crate's own pool, and hands back their payloads in tile order plus
7493/// whatever `code` returned for tile `store` -- the CDF state
7494/// `context_update_tile_id` names. The result cannot depend on the thread
7495/// count: each job writes one tile from the frame's own starting tables into
7496/// its own slot.
7497fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
7498where
7499 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
7500{
7501 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
7502 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
7503 let threads = crate::par::tile_threads().min(tiles);
7504 let mut slots: Vec<Slot> = Vec::new();
7505 if threads <= 1 {
7506 for index in 0..tiles {
7507 slots.push(Some(code(index)));
7508 }
7509 } else {
7510 let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
7511 {
7512 let batch = crate::par::Batch::new("ec-av1-tile");
7513 for (from, to) in crate::par::bands(tiles, threads) {
7514 let done = &done;
7515 let code = &code;
7516 batch.submit(move || {
7517 for index in from..to {
7518 let coded = code(index);
7519 done.lock().expect("tile slots")[index] = Some(coded);
7520 }
7521 });
7522 }
7523 }
7524 slots = done.into_inner().expect("tile slots");
7525 }
7526 let mut out = Vec::with_capacity(tiles);
7527 let mut stored = None;
7528 for (index, slot) in slots.into_iter().enumerate() {
7529 let (bytes, cdfs) = slot.expect("every tile was coded")?;
7530 if index == store {
7531 stored = cdfs;
7532 }
7533 out.push(bytes);
7534 }
7535 Ok((out, stored))
7536}
7537
7538/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
7539/// workers, and returns the results in tile order. The counterpart of
7540/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
7541/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
7542/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
7543/// availability is already tile-relative (`clip_planes_to_tile`,
7544/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
7545/// other tiles have run -- gated by
7546/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
7547/// covers the search as well as the write.
7548///
7549/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
7550/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
7551/// does it for the decoder's filter bands.
7552fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
7553where
7554 T: Send,
7555 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
7556{
7557 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
7558 let threads = crate::par::tile_threads().min(tiles);
7559 if threads <= 1 {
7560 return (0..tiles).map(|index| job(index, fctx)).collect();
7561 }
7562 type Slot<T> = Option<Result<T>>;
7563 let done: std::sync::Mutex<Vec<Slot<T>>> =
7564 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
7565 {
7566 let batch = crate::par::Batch::new("ec-av1-tile-search");
7567 for (from, to) in crate::par::bands(tiles, threads) {
7568 let done = &done;
7569 let job = &job;
7570 let ctx = crate::decode::filter_ctx_copy(fctx);
7571 batch.submit(move || {
7572 for index in from..to {
7573 let searched = job(index, &ctx);
7574 done.lock().expect("tile slots")[index] = Some(searched);
7575 }
7576 });
7577 }
7578 }
7579 done.into_inner()
7580 .expect("tile slots")
7581 .into_iter()
7582 .map(|slot| slot.expect("every tile was searched"))
7583 .collect()
7584}
7585
7586/// One tile job's own copy of a plane: the frame's source, a blank
7587/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
7588/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
7589/// of the frame's reconstruction because a tile's prediction never reads a
7590/// sample outside its own rectangle, and every sample inside it is written
7591/// before it is read.
7592fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
7593 Plane {
7594 source,
7595 reconstruction: vec![128; source.len()],
7596 width,
7597 height,
7598 true_width,
7599 true_height,
7600 tile_x0: 0,
7601 tile_y0: 0,
7602 tile_x1: width,
7603 tile_y1: height,
7604 ctx: CoefCtxMap::default(),
7605 }
7606}
7607
7608/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
7609/// the frame's plane, through the [`crate::par::Shared`] every job holds.
7610///
7611/// corner-cut: the disjointness that makes the aliasing sound is the caller's
7612/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
7613/// rectangles partition it -- checked end-to-end by
7614/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
7615/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
7616/// row-range `split_at_mut` plumbing through `Plane`, which would have to
7617/// thread an origin offset through every prediction and transform call site
7618/// for the same bytes.
7619#[allow(unsafe_code)]
7620fn copy_rect(
7621 dst: crate::par::Shared<'_, Vec<u8>>,
7622 src: &[u8],
7623 stride: usize,
7624 x0: usize,
7625 y0: usize,
7626 x1: usize,
7627 y1: usize,
7628) {
7629 // SAFETY: this job touches only its own tile rectangle (see above).
7630 let dst = unsafe { dst.get() };
7631 for y in y0..y1 {
7632 let (a, b) = (y * stride + x0, y * stride + x1);
7633 dst[a..b].copy_from_slice(&src[a..b]);
7634 }
7635}
7636
7637/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
7638/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
7639/// tables the frame stores (spec 7.20), which is what
7640/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
7641/// below publish.
7642fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
7643 ec_av1_syntax::TileInfo {
7644 uniform_spacing: true,
7645 cols: layout.cols(),
7646 rows: layout.rows(),
7647 cols_log2: layout.cols_log2,
7648 rows_log2: layout.rows_log2,
7649 mi_col_starts: layout.mi_col_starts(),
7650 mi_row_starts: layout.mi_row_starts(),
7651 context_update_tile_id: layout.largest_tile() as u32,
7652 tile_size_bytes,
7653 }
7654}
7655
7656/// Clips the three planes' intra edge reads to `rect`, the tile the
7657/// superblock about to be searched belongs to (the encoder side of the
7658/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
7659/// raster order -- which is a linear extension of every tile's own coding
7660/// order, so a block still only ever predicts from samples already
7661/// reconstructed -- and only availability is tile-relative.
7662fn clip_planes_to_tile(
7663 luma: &mut Plane<'_>,
7664 chroma: &mut [Plane<'_>; 2],
7665 rect: crate::tile::TileRect,
7666) {
7667 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
7668 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
7669 luma.set_tile(x0, y0, x1, y1);
7670 for plane in chroma.iter_mut() {
7671 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
7672 }
7673}
7674
7675/// Encodes one picture as a key frame.
7676///
7677/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
7678/// picks its coefficient CDFs from one of four q contexts by that index.
7679/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
7680/// smaller values trade fidelity for rate.
7681///
7682/// The picture may be any even width and height: the encoder pads it by edge
7683/// replication to a whole number of 32x32 blocks internally, and the frame it
7684/// writes crops back to the picture's own size (`render_width`/
7685/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
7686/// own size, never the padded one.
7687///
7688/// # Errors
7689/// Returns an error when the picture's width or height is zero or odd, or
7690/// when its planes are not 4:2:0 of that size.
7691/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
7692/// stream. The per-frame decode state this needs lives for exactly this call.
7693///
7694/// # Errors
7695/// Returns an error under the same conditions
7696/// [`encode_key_frame_with_modes`] does.
7697pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
7698 encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder())
7699}
7700
7701/// [`encode_key_frame`] with the per-block intra modes given rather than
7702/// searched.
7703///
7704/// # Errors
7705/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
7706/// is empty, or when a block's coefficients do not fit the coded frame.
7707pub fn encode_key_frame_with_modes(
7708 picture: &Picture,
7709 base_q_idx: u8,
7710 deadzone: f64,
7711 modes: &[u8],
7712) -> Result<Encoded> {
7713 encode_key_frame_with_modes_with_ctx(
7714 picture,
7715 base_q_idx,
7716 deadzone,
7717 modes,
7718 &crate::decode::FrameCtx::for_encoder(),
7719 )
7720}
7721
7722/// Codes `pictures` as one key frame followed by inter frames.
7723///
7724/// Camera material is coded under [`crate::encoder::Pyramid::default`] since
7725/// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a
7726/// `show_existing_frame` header, so `stream` is in CODING order while
7727/// `frames` stays in display order (`EncodedSequence::coding_order` is the
7728/// map). Screen content codes flat, decided once per sequence by the same
7729/// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0`
7730/// puts every stream back on the flat path for an A/B.
7731///
7732/// # Errors
7733/// Returns an error under the same conditions [`encode_key_frame`] and the
7734/// inter frame path do.
7735pub fn encode_sequence(
7736 pictures: &[Picture],
7737 base_q_idx: u8,
7738 deadzone: f64,
7739) -> Result<EncodedSequence> {
7740 encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder())
7741}
7742
7743pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
7744 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
7745}
7746
7747/// Encodes one picture as a key frame, choosing each block's luma mode from
7748/// `modes` alone.
7749///
7750/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
7751/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
7752/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
7753/// uses.
7754///
7755/// # Errors
7756/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
7757/// names a mode [`crate::intra::predict`] does not predict.
7758pub(crate) fn encode_key_frame_with_modes_with_ctx(
7759 picture: &Picture,
7760 base_q_idx: u8,
7761 deadzone: f64,
7762 modes: &[u8], fctx: &crate::decode::FrameCtx,
7763) -> Result<Encoded> {
7764 picture.check_even()?;
7765 let padded = picture.padded_to(BLOCK);
7766 let encoded = encode_key_frame_inner(
7767 &padded,
7768 base_q_idx,
7769 deadzone,
7770 modes,
7771 split_blocks(),
7772 (picture.width, picture.height),
7773 unspecified_color_config(), fctx,
7774 )?;
7775 Ok(crop_encoded(&encoded, picture.width, picture.height))
7776}
7777
7778/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
7779/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
7780/// already padded to a whole number of 32x32 blocks; `render` is the real
7781/// (pre-pad) size the frame header tells a decoder to crop back to.
7782pub(crate) fn encode_key_frame_inner(
7783 picture: &Picture,
7784 base_q_idx: u8,
7785 deadzone: f64,
7786 modes: &[u8],
7787 split_blocks: bool,
7788 render: (usize, usize),
7789 color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
7790) -> Result<Encoded> {
7791 // lane-refs: an intra frame runs no motion compensation, and the
7792 // context is shared across the sequence -- put the kernel back to the
7793 // default so nothing reads the previous inter frame's.
7794 fctx.interp_filter.set(mc::InterpFilterKind::Regular);
7795 picture.check()?;
7796 if modes.is_empty() {
7797 return Err(Error::unsupported(
7798 "AV1 encode",
7799 "a mode search needs at least one mode to choose from",
7800 ));
7801 }
7802 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
7803 return Err(Error::unsupported(
7804 "AV1 encode",
7805 format!("intra mode {bad} is not one the encoder predicts"),
7806 ));
7807 }
7808 // The header carries the frame's true (unpadded) size as `frame_width`/
7809 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
7810 // `mi_rows` derived from that same true size (spec `compute_image_size`).
7811 // `render_width`/`render_height` come out equal to it too, so
7812 // `render_and_frame_size_different` is false and no render_size bits are
7813 // written, mirroring libaom/rav1e: the padded `picture` below is only the
7814 // internal coding surface, never what the header names.
7815 // Screen-content detection runs on the SOURCE luma, before any header is
7816 // built: it decides this sequence's `seq_force_screen_content_tools` (and
7817 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
7818 // this frame's own `allow_screen_content_tools`.
7819 let screen = screen_content(
7820 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
7821 picture.width,
7822 (picture.width).min(render.0),
7823 (picture.height).min(render.1),
7824 );
7825 arm_seq_screen(screen);
7826 // A key frame's writer really does start from the defaults, and a search
7827 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
7828 // disarm, or a key frame's bits would depend on which thread searched it.
7829 crate::tile::arm_pricing_cdfs(None, false);
7830 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
7831 // forces deblocking, CDEF and loop restoration OFF for this frame
7832 // (frame.rs:194/210/252/272), so it is only set when the source repeats
7833 // itself enough for the copied blocks to pay that back
7834 // ([`intrabc_worth_it`]).
7835 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
7836 // grid across every tile while this writer builds one per tile, so a
7837 // multi-tile allow_intrabc frame would predict its DVs off a different
7838 // grid than the decoder does. corner-cut, ceiling named: the upgrade
7839 // path is a frame-scoped grid shared by the tile writers.
7840 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
7841 intrabc_worth_it(
7842 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
7843 picture.width,
7844 picture.width.min(render.0),
7845 picture.height.min(render.1),
7846 )
7847 } else {
7848 (false, 0.0)
7849 };
7850 IBC_SHARE.with(|c| c.set(ibc_share));
7851 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
7852 header.allow_screen_content_tools = screen;
7853 // lane-txi: the wider `tx_type` alphabets, gated by the same content
7854 // rule the type search itself stands behind ([`wide_tx_set`]).
7855 header.reduced_tx_set = !wide_tx_set(screen);
7856 header.allow_intrabc = allow_intrabc;
7857 header.render_width = render.0 as u32;
7858 header.render_height = render.1 as u32;
7859 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
7860 // its luma transform below its own side (`crate::tile::write_luma_select`).
7861 // Set here rather than in `key_frame_headers_colour` so the header
7862 // builders' other callers -- the hand-built tile writers, which code no
7863 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
7864 let tx_select = tx_select();
7865 if tx_select {
7866 header.tx_mode = TxMode::Select;
7867 }
7868 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
7869
7870 // Prediction reads no further than this, in each plane's own units --
7871 // see `Plane::true_width`/`true_height`.
7872 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
7873 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
7874 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
7875 // design (see `intra_predict_u8`'s doc comment), so narrow the source
7876 // once here.
7877 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
7878 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
7879 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
7880 let mut luma = Plane {
7881 source: &picture_y8,
7882 reconstruction: vec![128; picture_y8.len()],
7883 width: picture.width,
7884 height: picture.height,
7885 true_width,
7886 true_height,
7887 tile_x0: 0,
7888 tile_y0: 0,
7889 tile_x1: picture.width,
7890 tile_y1: picture.height,
7891 ctx: CoefCtxMap::default(),
7892 };
7893 let mut chroma = [
7894 Plane {
7895 source: &picture_u8,
7896 reconstruction: vec![128; picture_u8.len()],
7897 width: picture.width / 2,
7898 height: picture.height / 2,
7899 true_width: true_width / 2,
7900 true_height: true_height / 2,
7901 tile_x0: 0,
7902 tile_y0: 0,
7903 tile_x1: picture.width / 2,
7904 tile_y1: picture.height / 2,
7905 ctx: CoefCtxMap::default(),
7906 },
7907 Plane {
7908 source: &picture_v8,
7909 reconstruction: vec![128; picture_v8.len()],
7910 width: picture.width / 2,
7911 height: picture.height / 2,
7912 true_width: true_width / 2,
7913 true_height: true_height / 2,
7914 tile_x0: 0,
7915 tile_y0: 0,
7916 tile_x1: picture.width / 2,
7917 tile_y1: picture.height / 2,
7918 ctx: CoefCtxMap::default(),
7919 },
7920 ];
7921
7922 // The search trades a bit for the squared error it saves, in the units the
7923 // reconstruction is measured in: one step of the quantizer, squared.
7924 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
7925 let search = Search {
7926 base_q_idx,
7927 deadzone,
7928 lambda: lambda_scale() * key_lambda_factor() * step * step,
7929 modes,
7930 top_k: prune_top_k(),
7931 screen,
7932 };
7933
7934 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
7935 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
7936 // which may be fewer columns/rows than the padded picture has room for
7937 // -- a block whose origin sits past the true bound is not coded at all,
7938 // matching what a decoder derives from `frame_width`/`frame_height` and
7939 // so never visits either.
7940 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
7941 let (cols, rows) = (cols as usize, rows as usize);
7942 // The luma mode of the block above and of the block to the left, which is
7943 // what picks the CDF the next block's mode is coded against -- the same
7944 // bookkeeping the tile writer keeps, so that the search is costing the
7945 // symbol the writer will actually write.
7946 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
7947 // because a 32x32 block may be split into four 16x16 ones.
7948 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
7949 // This frame's tile grid (one tile unless the facade armed more).
7950 let layout =
7951 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
7952 header.tile_info = tile_info_of(&layout, 1);
7953 // The filter search re-decodes this frame's tiles; the decoder derives
7954 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
7955 // `mi_row_starts`), which is what makes the writer's rects and the
7956 // reader's the same rects.
7957 let header_tile_info = header.tile_info.clone();
7958 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
7959 // once over the whole frame. Each tile job builds its own reconstruction
7960 // planes and its own `above_mode`/`left_mode` bands, which is also what
7961 // the tile writer reads -- a tile resets its neighbour contexts (spec
7962 // 5.11.1), so a block at a tile's left edge must cost its mode against
7963 // the default context, not against whatever the tile to its west left in
7964 // that row. At one tile the bands are the frame's, exactly as before.
7965 let (frame_width, frame_height) = (picture.width, picture.height);
7966 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
7967 let [cb, cr] = &mut chroma;
7968 let chroma_out = [
7969 crate::par::Shared::new(&mut cb.reconstruction),
7970 crate::par::Shared::new(&mut cr.reconstruction),
7971 ];
7972 let search_tile = |index: usize,
7973 fctx: &crate::decode::FrameCtx|
7974 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
7975 crate::tile::arm_pricing_cdfs(None, false);
7976 let rect = layout.rect(index);
7977 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
7978 let mut chroma = [
7979 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
7980 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
7981 ];
7982 clip_planes_to_tile(&mut luma, &mut chroma, rect);
7983 let mut above_mode = vec![DC_PRED; cols * 2];
7984 let mut left_mode = vec![DC_PRED; rows * 2];
7985 let mut ibc = allow_intrabc.then(|| {
7986 Ibc::new(
7987 (
7988 rect.mi_col0 as usize * 4,
7989 rect.mi_row0 as usize * 4,
7990 (rect.mi_col1 as usize * 4).min(true_width),
7991 (rect.mi_row1 as usize * 4).min(true_height),
7992 ),
7993 &picture_y8,
7994 frame_width,
7995 )
7996 });
7997 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
7998 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
7999 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
8000 let mut modes = Vec::with_capacity(4);
8001 // The quadrants of a superblock are coded in the order the decoder
8002 // walks them, which for a 64x64 split into 32x32 blocks is raster
8003 // order among the quadrants that are inside the frame.
8004 let mut blocks = Vec::with_capacity(4);
8005 // lane-i64: the whole superblock as ONE 64x64 intra block, tried
8006 // BEFORE its quadrants (so both start from the same
8007 // reconstruction) and compared against the four of them below --
8008 // the shape the inter frame's own 64 root takes
8009 // (`search_skip_64`). A frame that allows intrabc is refused
8010 // outright ([`I64_ROOT`]) because the quadrant searches below
8011 // carry DV state a discarded trial would desync.
8012 let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK);
8013 // lane-corner LIFTED the two guards this root shipped with: the
8014 // frame no longer has to be a whole number of superblocks, and
8015 // the superblock no longer has to be wholly inside the frame.
8016 // The desync the guards were written for (a 248x152 corner's
8017 // chroma disagreeing three ways) does NOT reproduce at this
8018 // revision -- see
8019 // `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`,
8020 // which pins all three planes of the encoder's reconstruction,
8021 // our decoder and ffmpeg on four straddling sizes, three of them
8022 // cut on BOTH axes, with the edge fire count asserted. What the
8023 // guards cost was every key-frame root on an arbitrary export
8024 // size (the `aligned` line switched the whole feature off on, for
8025 // instance, a 1920x792 frame).
8026 let whole_inside = x64 + SUPERBLOCK <= luma.true_width
8027 && y64 + SUPERBLOCK <= luma.true_height;
8028 // lane-corner: and the superblock the true frame edge CUTS
8029 // THROUGH with more than half of each axis still inside, which is
8030 // all AV1 asks of a `PARTITION_NONE` root (spec
8031 // `decode_partition`'s `has_cols`/`has_rows`, the same pair the
8032 // key writer's `Superblock::Whole` arm checks) -- the shape the
8033 // inter root already takes ([`b64_edge`]).
8034 let edge_inside = edge_root_enabled()
8035 && crate::tile::has_half(
8036 sb_col as u32 * crate::tile::SB_MI,
8037 crate::tile::SB_MI,
8038 header.mi_cols,
8039 )
8040 && crate::tile::has_half(
8041 sb_row as u32 * crate::tile::SB_MI,
8042 crate::tile::SB_MI,
8043 header.mi_rows,
8044 );
8045 let sb64_legal = i64_root()
8046 && ibc.is_none()
8047 && sb_row * 2 + 1 < rows
8048 && sb_col * 2 + 1 < cols
8049 && (whole_inside || edge_inside);
8050 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
8051 if sb64_legal {
8052 I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8053 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
8054 let (c64, r64) = (sb_col * 4, sb_row * 4);
8055 let (block, cost) = code_square(
8056 &mut luma,
8057 &mut chroma,
8058 (x64, y64),
8059 SUPERBLOCK,
8060 &search,
8061 &mode_bits(above_mode[c64], left_mode[r64]),
8062 tx_select,
8063 None,
8064 true,
8065 fctx,
8066 );
8067 let cost = cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
8068 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
8069 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
8070 sb64 = Some((cost, block, after));
8071 }
8072 // A superblock whose 64x64 trial already codes almost nothing per
8073 // pixel is taken outright and its quadrants are never searched --
8074 // `split_rd_breakout` one size up, at the threshold the inter
8075 // root clamps to ([`b64_breakout_threshold`]), where this lever
8076 // BUYS wall instead of spending it.
8077 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
8078 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda)
8079 });
8080 // What the four quadrants cost together, including the split
8081 // partition symbol at the superblock level, so the two arms are
8082 // one comparable number.
8083 let mut sb_cost = match sb64 {
8084 Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true),
8085 None => 0.0,
8086 };
8087 for quadrant in 0..if early64 { 0 } else { 4 } {
8088 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
8089 if col >= cols || row >= rows {
8090 continue;
8091 }
8092 let (x, y) = (col * BLOCK, row * BLOCK);
8093 let (c0, r0) = (col * 2, row * 2);
8094 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
8095
8096 // spec `decode_partition`'s hasRows/hasCols recomputed at this
8097 // 32x32 block's own half (see `crate::tile::has_half`): the
8098 // true frame edge can fall inside a quadrant a superblock-level
8099 // check already let through. A quadrant that fails either may
8100 // not be left whole; a 16x16 sub-block that fails either (once
8101 // split) is a leaf this writer has no rectangular transform
8102 // for, so the search must not pick a split that would need one.
8103 let (has_cols32, has_rows32) = (
8104 crate::tile::has_half(
8105 col as u32 * crate::tile::BLOCK_MI,
8106 crate::tile::BLOCK_MI,
8107 header.mi_cols,
8108 ),
8109 crate::tile::has_half(
8110 row as u32 * crate::tile::BLOCK_MI,
8111 crate::tile::BLOCK_MI,
8112 header.mi_rows,
8113 ),
8114 );
8115 let whole_legal = has_cols32 && has_rows32;
8116 // A 16x16 sub-block's own hasCols/hasRows (spec
8117 // `decode_partition`, recomputed at this leaf's own half):
8118 // either axis false is a straddling leaf this writer codes as
8119 // the 8x8 leaves that are inside it
8120 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
8121 // false is the same split with the partition symbol inferred
8122 // rather than coded -- no rectangular transform is needed
8123 // (lane-av1rect).
8124 let sub_half = |sr: usize, sc: usize| {
8125 (
8126 crate::tile::has_half(
8127 sc as u32 * crate::tile::SUB_MI,
8128 crate::tile::SUB_MI,
8129 header.mi_cols,
8130 ),
8131 crate::tile::has_half(
8132 sr as u32 * crate::tile::SUB_MI,
8133 crate::tile::SUB_MI,
8134 header.mi_rows,
8135 ),
8136 )
8137 };
8138 // What the whole 32x32 costs, including the partition symbol
8139 // that says it is not split.
8140 let (whole, mut cost_whole) = code_square(
8141 &mut luma,
8142 &mut chroma,
8143 (x, y),
8144 BLOCK,
8145 &search,
8146 &mode_bits(above_mode[c0], left_mode[r0]),
8147 tx_select,
8148 ibc.as_mut(),
8149 true,
8150 fctx,
8151 );
8152 cost_whole += search.lambda * partition_bits(BLOCK, false);
8153 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
8154
8155 // What four 16x16 blocks cost instead, each searched against
8156 // the reconstruction the ones before it left.
8157 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
8158 let mut split = Vec::with_capacity(4);
8159 let mut cost_split = search.lambda
8160 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
8161 let mut split_modes = Vec::with_capacity(4);
8162 for sub in 0..4 {
8163 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
8164 // Same filter as the writer's `sub_positions` (spec
8165 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
8166 // return): a sub-block whose own origin sits past the
8167 // true frame is never coded, so it must not be searched
8168 // or pushed onto `split` either, or the writer's block
8169 // count will not match what it is prepared to name.
8170 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
8171 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
8172 {
8173 continue;
8174 }
8175 let (has_cols16, has_rows16) = sub_half(sr, sc);
8176 if has_cols16 && has_rows16 {
8177 let (block, cost) = code_square(
8178 &mut luma,
8179 &mut chroma,
8180 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
8181 SUB,
8182 &search,
8183 &mode_bits(above_mode[sc], left_mode[sr]),
8184 tx_select,
8185 ibc.as_mut(),
8186 true,
8187 fctx,
8188 );
8189 cost_split += cost;
8190 split_modes.push(block.mode);
8191 above_mode[sc] = block.mode;
8192 left_mode[sr] = block.mode;
8193 split.push(block);
8194 } else {
8195 // A straddling 16x16: two (or, at a true corner, one)
8196 // 8x8 leaves, in the raster order `write_leaf8`'s
8197 // caller expects. Both leaves cost against the SAME
8198 // enclosing-slot mode context (see
8199 // `crate::tile::write_leaf8`'s doc), and neither
8200 // updates `above_mode`/`left_mode` at this SUB slot --
8201 // the writer never does either, so the search must
8202 // not diverge from what it will actually read next.
8203 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
8204 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
8205 let mut leaves = Vec::with_capacity(2);
8206 for i in 0..4 {
8207 let leaf_x = x_sub + (i % 2) * 8;
8208 let leaf_y = y_sub + (i / 2) * 8;
8209 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
8210 continue;
8211 }
8212 let (leaf, cost) = code_square(
8213 &mut luma,
8214 &mut chroma,
8215 (leaf_x, leaf_y),
8216 8,
8217 &search,
8218 &leaf_mode_bits,
8219 tx_select,
8220 None,
8221 true,
8222 fctx,
8223 );
8224 cost_split += cost;
8225 split_modes.push(leaf.mode);
8226 leaves.push(leaf);
8227 }
8228 split.push(BlockCoeffs {
8229 eight: Some(leaves),
8230 ..BlockCoeffs::default()
8231 });
8232 }
8233 }
8234
8235 // A split whose subs are all whole 16x16 is a real quality
8236 // alternative to `whole`, exactly as before. Through r14, a
8237 // split carrying an 8x8-leaf sub was only ever forced
8238 // (`!whole_legal`), never chosen on cost, because the leaf
8239 // path was not yet proven against a real decoder; r15 proved
8240 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
8241 // the read path (`decode_leaf8`), so leaf8 can now win on
8242 // cost anywhere, same as any other split.
8243 if !whole_legal || (split_blocks && cost_split < cost_whole) {
8244 sb_cost += cost_split;
8245 modes.extend_from_slice(&split_modes);
8246 blocks.push(Quadrant::Split(split));
8247 } else {
8248 sb_cost += cost_whole;
8249 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
8250 for cell in 0..2 {
8251 above_mode[c0 + cell] = whole.mode;
8252 left_mode[r0 + cell] = whole.mode;
8253 }
8254 modes.push(whole.mode);
8255 blocks.push(Quadrant::Whole(whole));
8256 }
8257 }
8258 let index = sb_row * sb_cols + sb_col;
8259 match sb64 {
8260 Some((cost64, block, after)) if early64 || cost64 < sb_cost => {
8261 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
8262 for cell in 0..4 {
8263 above_mode[sb_col * 4 + cell] = block.mode;
8264 left_mode[sb_row * 4 + cell] = block.mode;
8265 }
8266 I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8267 if !whole_inside {
8268 I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8269 }
8270 let mode = block.mode;
8271 coded.push((index, Superblock::Whole(block), vec![mode]));
8272 }
8273 _ => coded.push((index, Superblock::Split(blocks), modes)),
8274 }
8275 }
8276 }
8277 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8278 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8279 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
8280 for (&out, tile) in chroma_out.iter().zip(&chroma) {
8281 copy_rect(
8282 out,
8283 &tile.reconstruction,
8284 frame_width / 2,
8285 x0 / 2,
8286 y0 / 2,
8287 x1.div_ceil(2),
8288 y1.div_ceil(2),
8289 );
8290 }
8291 Ok(coded)
8292 };
8293 let searched = search_tiles(layout.count(), fctx, search_tile)?;
8294 // Back into frame raster order: the tile writer indexes `superblocks` by
8295 // the frame's own superblock index, and `modes` is the coding order the
8296 // ablation drivers read.
8297 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
8298 for (at, superblock, block_modes) in searched.into_iter().flatten() {
8299 in_order[at] = Some((superblock, block_modes));
8300 }
8301 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
8302 let mut modes = Vec::with_capacity(cols * rows);
8303 for slot in in_order {
8304 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
8305 superblocks.push(superblock);
8306 modes.extend_from_slice(&block_modes);
8307 }
8308
8309 #[cfg(test)]
8310 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
8311 // A key frame always starts from the defaults (`primary_ref_frame` is
8312 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
8313 // set, so what it stores into the slots it refreshes is exactly those
8314 // defaults again (spec 7.20's `started_from` arm) -- the first inter
8315 // frame after it therefore starts from the defaults too.
8316 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
8317 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
8318 // lane-txi: the ONE place the writer reads the frame's `reduced_tx_set`
8319 // from -- `Cdfs::txb` widens every luma set under it.
8320 cdfs.reduced_tx_set = header.reduced_tx_set;
8321 let start_cdfs = CdfSnapshot(cdfs);
8322 // The luma restoration-unit grid this frame's `lr_params` implies
8323 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
8324 // swallowed by the one before it), for the tile writer's own per-unit
8325 // walk.
8326 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
8327 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
8328 // Every tile is coded from this frame's OWN starting tables and leaves
8329 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
8330 // loop-restoration reference and its neighbour contexts), so the tiles
8331 // are independent of each other and of the order they are written in.
8332 let code_tiles = |bits: u8,
8333 sb_cols: usize,
8334 grid: &[u8],
8335 units: &[Option<crate::restoration::WienerInfo>]|
8336 -> Result<Vec<Vec<u8>>> {
8337 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
8338 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
8339 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
8340 crate::tile::arm_sb128(sb128_on());
8341 let mut cdfs = start_cdfs.0.clone();
8342 crate::tile::arm_screen(screen);
8343 crate::tile::arm_filter_intra(filter_intra_on());
8344 crate::tile::arm_intrabc(allow_intrabc);
8345 crate::tile::arm_pricing_cdfs(None, false);
8346 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
8347 mi_cols,
8348 mi_rows,
8349 base_q_idx,
8350 &superblocks,
8351 tx_select,
8352 &mut cdfs,
8353 layout.rect(index),
8354 )?;
8355 Ok((bytes, None))
8356 })?;
8357 Ok(out)
8358 };
8359 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
8360 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
8361 // the tile just coded back to the decoder under each candidate (see
8362 // `crate::filter_search`), and keep the filtered picture that wins as
8363 // the reconstruction -- what a decoder outputs, and what the next
8364 // frame predicts from.
8365 pick_and_apply_filters(
8366 &mut header,
8367 &mut luma,
8368 &mut chroma,
8369 [&picture_y8, &picture_u8, &picture_v8],
8370 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
8371 // and loop restoration off and codes none of their parameters
8372 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
8373 // the encoder's reconstruction is already what a decoder produces.
8374 !allow_intrabc,
8375 &mut tiles,
8376 search.lambda,
8377 fctx,
8378 // Every re-code starts from this frame's OWN starting tables, never
8379 // from where the first write left them: the second tile is the same
8380 // symbol sequence plus new ones, so it must adapt from the same
8381 // point the decoder will.
8382 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
8383 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
8384 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
8385 crate::decode::decode_key_frame_tiles_lr(
8386 &payloads,
8387 &header_tile_info,
8388 h.mi_cols,
8389 h.mi_rows,
8390 base_q_idx,
8391 h.frame_width,
8392 h.frame_height,
8393 seq.enable_filter_intra,
8394 cdef,
8395 lf,
8396 tx_select,
8397 h.reduced_tx_set,
8398 h.allow_screen_content_tools,
8399 h.allow_intrabc,
8400 lr,
8401 fctx,
8402 )
8403 },
8404 )?;
8405 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
8406 header.tile_info.tile_size_bytes = tile_size_bytes;
8407 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
8408 let mut stream = temporal_delimiter();
8409 stream.extend_from_slice(&sequence_header_obu(&seq)?);
8410 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
8411
8412 let [u, v] = chroma;
8413 Ok(Encoded {
8414 stream,
8415 modes,
8416 inter_block_share: 0.0,
8417 reconstruction: Picture {
8418 width: luma.width,
8419 height: luma.height,
8420 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
8421 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
8422 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
8423 },
8424 tile,
8425 mi_cols: header.mi_cols,
8426 mi_rows: header.mi_rows,
8427 base_q_idx,
8428 tx_select,
8429 // A key frame codes no inter block, so no motion_mode symbol.
8430 switchable_motion_mode: false,
8431 screen,
8432 next_cdfs: start_cdfs.clone(),
8433 start_cdfs,
8434 loop_filter: header.loop_filter,
8435 cdef: header.cdef,
8436 loop_restoration: header.loop_restoration,
8437 allow_intrabc,
8438 delta: header.delta.clone(),
8439 })
8440}
8441
8442/// Chooses this frame's deblocking levels and CDEF strengths, writes them
8443/// into `header` and
8444/// replaces the frame's own region of the encoder's reconstruction with the
8445/// filtered picture the decoder produced under them
8446/// ([`crate::filter_search::pick_deblock`]).
8447///
8448/// `search == false` leaves the header at level 0 (deblocking off) and the
8449/// reconstruction untouched: the caller's stream is one this crate's own
8450/// decoder cannot read back, so there is nothing to search against.
8451///
8452/// # Errors
8453/// The decoder's own error, when it refuses the tile the encoder just wrote
8454/// -- that is an encoder defect, not a filter one, so it is propagated
8455/// rather than swallowed into "no deblocking".
8456fn pick_and_apply_filters(
8457 header: &mut FrameHeader,
8458 luma: &mut Plane<'_>,
8459 chroma: &mut [Plane<'_>; 2],
8460 source: [&[u8]; 3],
8461 search: bool,
8462 // The coded tiles, one payload per tile of the frame's grid, replaced in
8463 // place when the search chooses a per-64x64 `cdef_idx` list
8464 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
8465 // tile is written a second time under `recode` and the winner
8466 // re-decoded from them.
8467 tiles: &mut Vec<Vec<u8>>,
8468 lambda: f64,
8469 fctx: &crate::decode::FrameCtx,
8470 recode: impl Fn(
8471 u8,
8472 usize,
8473 &[u8],
8474 &[Option<crate::restoration::WienerInfo>],
8475 ) -> Result<Vec<Vec<u8>>>,
8476 decode: impl Fn(
8477 &LoopFilterParams,
8478 &CdefParams,
8479 &FrameHeader,
8480 &[Vec<u8>],
8481 &LoopRestorationParams,
8482 ) -> Result<Picture>,
8483) -> Result<()> {
8484 if !search {
8485 return Ok(());
8486 }
8487 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
8488 let hdr = header.clone();
8489 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
8490 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
8491 let damping = 3 + (header.quantization.base_q_idx >> 6);
8492 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
8493 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
8494 let none_lr = LoopRestorationParams::default();
8495 // Every candidate scores the same coded tile: decode it once and re-run
8496 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
8497 // the encoder's profile before this). The per-64x64 error the CDEF
8498 // preset search reads comes off the REPLAYED picture, which is the same
8499 // picture a decode produces -- that is what the replay is pinned on.
8500 crate::decode::clear_filter_replay();
8501 // lane-av1fpar: the per-tile search is over, so every core is idle from
8502 // here to the end of the frame -- band each candidate's deblock/CDEF
8503 // replay, the capture decode's own filter chain and the loop-restoration
8504 // passes across the same workers the search used.
8505 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
8506 let ft = crate::par::timer(crate::par::S_FILTER);
8507 let search_result = crate::filter_search::pick_filters(
8508 |lf, cdef| {
8509 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
8510 return Ok(picture);
8511 }
8512 crate::decode::arm_filter_replay();
8513 let _t = crate::par::timer(crate::par::S_FIRST);
8514 decode(lf, cdef, &hdr, tiles, &none_lr)
8515 },
8516 source,
8517 luma.width,
8518 (fw, fh),
8519 damping,
8520 (sb_cols, sb_rows),
8521 lambda,
8522 );
8523 drop(ft);
8524 let (lf, cdef, idx_grid, picture) = search_result?;
8525 header.loop_filter = lf;
8526 header.cdef = cdef;
8527 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
8528 // in the frame header, so a re-decode under candidate parameters cannot
8529 // search them the way deblocking and CDEF are searched above. What the
8530 // decoder hands back instead is its own filter chain's intermediates
8531 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
8532 // those, through the decoder's own Wiener kernel.
8533 //
8534 // The capture rides the decode this stage was already going to do: the
8535 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
8536 // decode of the tile as it stands. That decode's header still says
8537 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
8538 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
8539 // an approximation inside the SEARCH only; the reconstruction this
8540 // function ends up splicing is always a real decode of the real tile.
8541 let lr_on = restoration_enabled();
8542 // The `cdef_idx` literals live in the tile payload, so a frame that
8543 // chose a per-64x64 preset list codes its tiles a second time.
8544 if !idx_grid.is_empty() {
8545 *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
8546 }
8547 // lane-av1cap: that re-coded tile used to be DECODED here as well --
8548 // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop
8549 // restoration search reads (`crate::decode::FrameCtx::capture_stages`)
8550 // and the picture this function splices. Both come out of ONE more
8551 // replay of the winning parameters on the same captured pre-filter
8552 // planes every candidate was scored on: the same two filter kernels, on
8553 // the same input, in the same order, so the same bytes. Re-coding the
8554 // tile does not move the reconstruction the replay holds -- `cdef_idx`
8555 // is an equiprobable literal, so it adapts no CDF and changes no
8556 // residual.
8557 let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx);
8558 #[cfg(test)]
8559 let replay_was_used = replayed.is_some();
8560 let (mut filtered, mut stages) = match replayed {
8561 Some((picture, stages)) => (picture, stages),
8562 // Nothing captured (the shapes [`crate::decode::FilterReplay`]
8563 // refuses): every candidate was a full decode, so the winner's own
8564 // picture stands, and the stages still need a capturing decode.
8565 None => {
8566 fctx.capture_stages.set(lr_on);
8567 let picture = if idx_grid.is_empty() && !lr_on {
8568 picture
8569 } else {
8570 let _t = crate::par::timer(crate::par::S_CAPTURE);
8571 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
8572 };
8573 fctx.capture_stages.set(false);
8574 (picture, crate::decode::take_filter_stages(fctx))
8575 }
8576 };
8577 #[cfg(test)]
8578 if crate::decode::verify_final_replay() && replay_was_used {
8579 fctx.capture_stages.set(lr_on);
8580 let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?;
8581 fctx.capture_stages.set(false);
8582 let want_stages = crate::decode::take_filter_stages(fctx);
8583 assert!(
8584 (want.width, want.height) == (filtered.width, filtered.height)
8585 && want.y == filtered.y
8586 && want.u == filtered.u
8587 && want.v == filtered.v,
8588 "the final filter replay is not the capture decode it stands in for",
8589 );
8590 // Only the frame's own cropped region: the plane is padded to the
8591 // superblock grid and the columns past the mi extent are written by
8592 // nothing (the decoder's plane pool leaves whatever the last frame
8593 // put there), while the restoration search reads strictly inside
8594 // `fw x fh` -- `restoration::lr_sample` clamps its column to
8595 // `plane_w - 1` and its row to the frame's, and
8596 // `filter_search::pick_restoration`'s own SSE walk never leaves the
8597 // crop either.
8598 let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| {
8599 for row in 0..h {
8600 let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]);
8601 assert!(
8602 x == y,
8603 "{what}: the replayed filter stages are not the ones the capture \
8604 decode returns (row {row} of {h}, width {w}, stride {stride})",
8605 );
8606 }
8607 };
8608 match (&want_stages, &stages) {
8609 (Some(a), Some(b)) => {
8610 assert_eq!(a.stride, b.stride, "the captured plane strides moved");
8611 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
8612 for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() {
8613 region(&a.deblocked[i], &b.deblocked[i], a.stride[i], w, h, "deblocked");
8614 region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed");
8615 }
8616 }
8617 (None, None) => {}
8618 _ => panic!("one path captured filter stages and the other did not"),
8619 }
8620 }
8621 // lane-av1cap2: the capture stays live past the restoration search --
8622 // `crate::decode::replay_restoration` filters the same post-CDEF plane
8623 // rather than decoding the re-coded tile. Cleared at the end instead.
8624 let mut lr = LoopRestorationParams::default();
8625 if lr_on {
8626 let unit = lr_unit();
8627 let mut want = LoopRestorationParams {
8628 loop_restoration_size: [unit, unit, unit],
8629 uses_lr: true,
8630 // spec `lr_params`: `RESTORATION_TILESIZE_MAX >> (2 - shift)`, so
8631 // 0 is the 64 unit and 1 the 128 one a 128 superblock forces.
8632 lr_unit_shift: u8::from(unit == 128),
8633 ..LoopRestorationParams::default()
8634 };
8635 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
8636 let lrt = crate::par::timer(crate::par::S_LR);
8637 let units = match stages.take() {
8638 Some(stages) => crate::filter_search::pick_restoration(
8639 &stages,
8640 source[0],
8641 luma.width,
8642 (fw, fh),
8643 &want,
8644 lambda,
8645 fctx,
8646 ),
8647 None => Vec::new(),
8648 };
8649 // A frame no unit restores keeps `RESTORE_NONE` on every plane
8650 // rather than paying ~1 bit per 64x64 for a tile full of
8651 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
8652 // clip whose units never take a filter).
8653 drop(lrt);
8654 if units.iter().any(Option::is_some) {
8655 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
8656 let _t = crate::par::timer(crate::par::S_CAPTURE);
8657 // lane-av1cap2: that re-coded tile used to be DECODED here to
8658 // reach the restored reference frame -- 5.6% of a 4K frame,
8659 // for a filter that reads nothing of the tile but the per-unit
8660 // Wiener filters this stage just chose. Run the decoder's own
8661 // restoration kernel on the replay's post-CDEF plane instead
8662 // (`crate::decode::replay_restoration`), with the real
8663 // post-deblock stripe borders.
8664 match crate::decode::replay_restoration(&want, &units, fctx) {
8665 Some(y) => {
8666 #[cfg(test)]
8667 let margin = fctx
8668 .last_frame_wide_margin
8669 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()));
8670 #[cfg(test)]
8671 if crate::decode::verify_final_replay() {
8672 let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?;
8673 assert!(
8674 (want_pic.width, want_pic.height) == (filtered.width, filtered.height)
8675 && want_pic.u == filtered.u
8676 && want_pic.v == filtered.v,
8677 "the restoration replay moved a chroma plane or the picture size",
8678 );
8679 assert!(
8680 want_pic.y == y,
8681 "the restoration replay is not the decode of the re-coded tile",
8682 );
8683 assert!(
8684 fctx.last_frame_wide_margin
8685 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()))
8686 == margin,
8687 "the restoration replay's wide-margin luma is not the decode's",
8688 );
8689 }
8690 filtered.y = y;
8691 }
8692 // Nothing captured: the winner came out of a full decode,
8693 // so this one does too.
8694 None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?,
8695 }
8696 *tiles = coded;
8697 lr = want;
8698 }
8699 }
8700 crate::decode::clear_filter_replay();
8701 header.loop_restoration = lr;
8702 let dec_cw = filtered.width.div_ceil(2);
8703 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
8704 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
8705 crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
8706 crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
8707 Ok(())
8708}
8709
8710/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
8711/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
8712/// since every block this crate's inter tile writer codes is 32x32.
8713const SIZE_GROUP_32: usize = 3;
8714
8715/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
8716/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
8717/// stack this encoder builds is ever asked to predict against.
8718const LAST_FRAME: i8 = 1;
8719
8720/// What an inter frame's intra branch spends to name each of the thirteen
8721/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
8722/// context, since an inter frame's intra blocks do not read their
8723/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
8724/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
8725/// state, so it is built once per frame.
8726fn inter_mode_bits() -> [f64; 13] {
8727 std::array::from_fn(|mode| {
8728 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
8729 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
8730 } else {
8731 0.0
8732 };
8733 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
8734 + angle
8735 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
8736 })
8737}
8738
8739/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
8740/// [`mc::predict`] takes, in the units of the plane it predicts into.
8741///
8742/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
8743/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
8744/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
8745/// domain. `luma` picks which.
8746fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
8747 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
8748}
8749
8750/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
8751/// that module): the magnitude an `MV_CLASS_n` component's own bits start
8752/// counting from.
8753fn mv_class_base(class: usize) -> i32 {
8754 if class == 0 { 0 } else { 2i32 << (class + 2) }
8755}
8756
8757/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
8758/// `tile::mv_class_of`.
8759fn mv_class_of(z: i32) -> usize {
8760 let mut class = 0;
8761 while class < 10 && mv_class_base(class + 1) <= z {
8762 class += 1;
8763 }
8764 class
8765}
8766
8767/// What [`crate::tile::write_mv_component`] (private to that module) would
8768/// spend coding one non-zero motion vector component, against the same
8769/// static default CDFs the writer starts a frame from — the same
8770/// static-table approximation [`mode_bits`] costs the luma mode symbol
8771/// through, not the tile writer's own adapting state, which this encoder has
8772/// no way to read without duplicating it block for block.
8773///
8774/// Returns `None` when `diff` needs the eighth-pel precision this crate's
8775/// frames never carry (`allow_high_precision_mv` is always off), which is
8776/// what [`round_to_valid_mv`] exists to avoid ever happening.
8777fn mv_component_bits(diff: i32) -> Option<f64> {
8778 let mag = diff.unsigned_abs() as i32;
8779 let z = mag - 1;
8780 if z & 1 == 0 {
8781 return None;
8782 }
8783 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
8784 let class = mv_class_of(z);
8785 bits += symbol_bits(&cdf::MV_CLASS, class);
8786 let local = z - mv_class_base(class);
8787 if class == 0 {
8788 let bit = (local >> 3) & 1;
8789 let fr = (local >> 1) & 3;
8790 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
8791 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
8792 } else {
8793 let d = local >> 3;
8794 let fr = (local >> 1) & 3;
8795 for i in 0..class {
8796 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
8797 }
8798 bits += symbol_bits(&cdf::MV_FR, fr as usize);
8799 }
8800 Some(bits)
8801}
8802
8803/// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the
8804/// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch,
8805/// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's
8806/// value without the second motion search's wall.
8807fn last2_new_mv() -> bool {
8808 match std::env::var("EC_AV1_LAST2_NEW").ok() {
8809 Some(v) => v != "0",
8810 None => true,
8811 }
8812}
8813
8814/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
8815/// own -- a second motion search per block against that reference's picture,
8816/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
8817/// off in a test build (what the lane measured both arms with).
8818fn extra_ref_new_mv() -> bool {
8819 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
8820 Some(v) if cfg!(test) => v != "0",
8821 _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW),
8822 }
8823}
8824
8825/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
8826/// flat slot plan (`inter_frame_headers_slots`): every reference but
8827/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
8828/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
8829/// frame two back when there is one (otherwise it, too, names the key frame's
8830/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
8831pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
8832 let last = order_hint.wrapping_sub(1) & 0x7f;
8833 let alt = if has_altref {
8834 order_hint.wrapping_sub(2) & 0x7f
8835 } else {
8836 key_hint
8837 };
8838 [last, last, last, key_hint, last, last, alt]
8839}
8840
8841/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
8842/// header bit that lets each block choose between a single and a compound
8843/// reference. Off by default until compound prediction is measured to pay;
8844/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
8845/// runs as), and every block still codes SINGLE, so the only cost is one
8846/// `comp_mode` symbol per inter block.
8847pub(crate) const REFERENCE_SELECT: bool = true;
8848
8849/// [`REFERENCE_SELECT`], with the test-build environment override.
8850pub(crate) fn reference_select() -> bool {
8851 match std::env::var("EC_AV1_COMPOUND").ok() {
8852 Some(v) if cfg!(test) => v != "0",
8853 _ => crate::speed::at(&crate::speed::COMPOUND),
8854 }
8855}
8856
8857/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
8858/// per entry past `start`, `1` to advance and `0` to stop, at most two.
8859fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
8860 let mut bits = 0.0;
8861 let mut idx = start;
8862 while idx < start + 2 && stack.entries.len() > idx + 1 {
8863 let advance = idx < target;
8864 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
8865 if !advance {
8866 break;
8867 }
8868 idx += 1;
8869 }
8870 bits
8871}
8872
8873/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
8874/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
8875/// `assign_mv`), so the same vector costs a different residual from each.
8876fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
8877 let mut best: Option<(f64, u8)> = None;
8878 for idx in 0..3usize {
8879 if idx > 0 && stack.entries.len() <= idx {
8880 break;
8881 }
8882 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
8883 if let Some(b) = mv_residual_bits(mv, base) {
8884 let total = b + drl_bits_for(stack, 0, idx);
8885 if best.is_none_or(|(t, _)| total < t) {
8886 best = Some((total, idx as u8));
8887 }
8888 }
8889 }
8890 best
8891}
8892
8893/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
8894/// zero vector and the stack's own candidates. A neighbour block's vector is
8895/// where this block's motion most often already is, which is what pays for
8896/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
8897/// vs libaom for 0.2 s off a 6 s ladder).
8898fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
8899 let mut seeds = [(0, 0); 4];
8900 let mut n = 1;
8901 for e in stack.entries.iter().take(3) {
8902 seeds[n] = e.mv;
8903 n += 1;
8904 }
8905 (seeds, n)
8906}
8907
8908/// What [`crate::tile::write_mv`] (private to that module) would spend
8909/// coding `mv` as a residual against `pred`: the joint symbol naming which
8910/// components differ, then each differing component. `None` under the same
8911/// condition [`mv_component_bits`] returns `None`.
8912/// How many frames back `ref_frame` sits from the frame being coded, off the
8913/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
8914/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
8915/// what [`crate::motion::search`] scales its starting step by.
8916fn ref_distance(ref_frame: i8) -> u32 {
8917 let (bits, order_hint, hints) = crate::tile::order_hints();
8918 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
8919 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
8920 .unsigned_abs()
8921 .max(1);
8922 if crate::envflags::env_flag!("EC_TRACE_DIST") {
8923 eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]);
8924 }
8925 d
8926}
8927
8928fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
8929 let diff = (mv.0 - pred.0, mv.1 - pred.1);
8930 let joint = match (diff.0 != 0, diff.1 != 0) {
8931 (false, false) => 0,
8932 (false, true) => 1,
8933 (true, false) => 2,
8934 (true, true) => 3,
8935 };
8936 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
8937 for d in [diff.0, diff.1] {
8938 if d != 0 {
8939 bits += mv_component_bits(d)?;
8940 }
8941 }
8942 Some(bits)
8943}
8944
8945/// Rounds `mv` so that its residual against `pred` is one
8946/// [`crate::tile::write_mv_component`] can actually code: each component's
8947/// difference is either zero or has an even magnitude (the eighth-pel bit
8948/// `allow_high_precision_mv` off always infers as one forces the coded
8949/// magnitude odd one step further in, which comes out even here since this
8950/// crate's motion search works in whole units of that same step). Rounding
8951/// down keeps every coded MV — and so every `nearest_mv` a later block's
8952/// stack votes with — built from an even displacement from `(0, 0)`, so the
8953/// invariant holds without this function seeing the whole stack.
8954fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
8955 let round = |m: i32, p: i32| {
8956 let diff = m - p;
8957 let mag = diff.unsigned_abs() as i32;
8958 let even = mag - mag % 2;
8959 if even == 0 {
8960 p
8961 } else {
8962 p + even * diff.signum()
8963 }
8964 };
8965 (round(mv.0, pred.0), round(mv.1, pred.1))
8966}
8967
8968/// Predicts one `side`-square block by motion compensation from `reference`
8969/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
8970#[allow(clippy::too_many_arguments)]
8971fn mc_trial(
8972 plane: &Plane,
8973 x: usize,
8974 y: usize,
8975 side: usize,
8976 mv: (i32, i32),
8977 luma: bool,
8978 reference: &[u16],
8979 stride: usize,
8980 ref_width: usize,
8981 ref_height: usize,
8982 skip: bool,
8983 base_q_idx: u8,
8984 deadzone: f64,
8985 set: TxbSet,
8986 fctx: &crate::decode::FrameCtx,
8987) -> Trial {
8988 mc_trial_typed(
8989 plane, x, y, side, mv, luma, reference, stride, ref_width, ref_height, skip, base_q_idx,
8990 deadzone, set, TxType::DctDct, fctx,
8991 )
8992}
8993
8994/// [`mc_trial`] coding its residual with a named transform type (lane-txset2).
8995#[allow(clippy::too_many_arguments)]
8996fn mc_trial_typed(
8997 plane: &Plane,
8998 x: usize,
8999 y: usize,
9000 side: usize,
9001 mv: (i32, i32),
9002 luma: bool,
9003 reference: &[u16],
9004 stride: usize,
9005 ref_width: usize,
9006 ref_height: usize,
9007 skip: bool,
9008 base_q_idx: u8,
9009 deadzone: f64,
9010 set: TxbSet,
9011 tx_type: TxType,
9012 fctx: &crate::decode::FrameCtx,
9013) -> Trial {
9014 let x_q4 = mv_to_q4(x, mv.1, luma);
9015 let y_q4 = mv_to_q4(y, mv.0, luma);
9016 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
9017 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
9018 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
9019 // lane-av1speed: both buffers are per-candidate scratch on the hottest
9020 // path in the encoder, so they live on the stack -- `side` is at most
9021 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
9022 // per motion-compensated trial otherwise.
9023 let mut prediction16 = [0u16; BLOCK * BLOCK];
9024 let prediction16 = &mut prediction16[..side * side];
9025 mc::predict(
9026 reference,
9027 stride,
9028 ref_width,
9029 ref_height,
9030 x_q4,
9031 y_q4,
9032 side,
9033 side,
9034 prediction16, fctx,
9035 );
9036 let mut prediction = [0u8; BLOCK * BLOCK];
9037 let prediction = &mut prediction[..side * side];
9038 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
9039 *dst = src as u8;
9040 }
9041 plane.code_from_prediction_typed(
9042 x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type,
9043 )
9044}
9045
9046/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
9047/// references predict into the `CONV_BUF` intermediate domain
9048/// ([`mc::predict_compound_intermediate`]) and are blended by
9049/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
9050/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
9051/// block, so the encoder's reconstruction is the decoder's.
9052#[allow(clippy::too_many_arguments)]
9053fn mc_trial_compound(
9054 plane: &Plane,
9055 x: usize,
9056 y: usize,
9057 side: usize,
9058 mvs: ((i32, i32), (i32, i32)),
9059 luma: bool,
9060 ref0: (&[u16], usize, usize, usize),
9061 ref1: (&[u16], usize, usize, usize),
9062 base_q_idx: u8,
9063 deadzone: f64,
9064 set: TxbSet,
9065 fctx: &crate::decode::FrameCtx,
9066) -> Trial {
9067 mc_trial_compound_typed(
9068 plane, x, y, side, mvs, luma, ref0, ref1, base_q_idx, deadzone, set, TxType::DctDct, fctx,
9069 )
9070}
9071
9072/// [`mc_trial_compound`] coding its residual with a named transform type
9073/// (lane-txset2).
9074#[allow(clippy::too_many_arguments)]
9075fn mc_trial_compound_typed(
9076 plane: &Plane,
9077 x: usize,
9078 y: usize,
9079 side: usize,
9080 (mv0, mv1): ((i32, i32), (i32, i32)),
9081 luma: bool,
9082 ref0: (&[u16], usize, usize, usize),
9083 ref1: (&[u16], usize, usize, usize),
9084 base_q_idx: u8,
9085 deadzone: f64,
9086 set: TxbSet,
9087 tx_type: TxType,
9088 fctx: &crate::decode::FrameCtx,
9089) -> Trial {
9090 let mut inter0 = [0i32; BLOCK * BLOCK];
9091 let mut inter1 = [0i32; BLOCK * BLOCK];
9092 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
9093 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
9094 mc::predict_compound_intermediate(
9095 r.0,
9096 r.1,
9097 r.2,
9098 r.3,
9099 mv_to_q4(x, mv.1, luma),
9100 mv_to_q4(y, mv.0, luma),
9101 mc::REF_NO_SCALE,
9102 side,
9103 side,
9104 fctx.interp_filter.get(),
9105 fctx.interp_filter.get(),
9106 dst,
9107 );
9108 }
9109 let mut blended16 = [0u16; BLOCK * BLOCK];
9110 let blended16 = &mut blended16[..side * side];
9111 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
9112 let mut prediction = [0u8; BLOCK * BLOCK];
9113 let prediction = &mut prediction[..side * side];
9114 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
9115 *dst = src as u8;
9116 }
9117 plane.code_from_prediction_typed(
9118 x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type,
9119 )
9120}
9121
9122/// Codes one 32x32 block of an inter frame as whichever costs least of: each
9123/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
9124/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
9125/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
9126/// coding a real residual (`skip: false`) whenever one prices out cheaper
9127/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
9128/// missing inter `tx_type` symbol (the desync this function's candidates
9129/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
9130/// fixed.
9131///
9132/// The symbol costs this ranks candidates by use fixed contexts (0) for
9133/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
9134/// contexts for those come from its own neighbour bookkeeping
9135/// (`tile::Neighbours`), which is private to that module and not worth
9136/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
9137/// `drl_mode` contexts come straight from `stack`, which is exact, because
9138/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
9139/// the tile writer derives from the same grid state.
9140#[allow(clippy::too_many_arguments)]
9141/// One prediction of `side` x `side` samples from `reference`, as `u8` --
9142/// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is
9143/// four times the stack scratch that function sizes for [`BLOCK`].
9144fn predict_u8(
9145 reference: &[u16],
9146 stride: usize,
9147 ref_width: usize,
9148 ref_height: usize,
9149 (x, y): (usize, usize),
9150 side: usize,
9151 mv: (i32, i32),
9152 luma: bool,
9153 fctx: &crate::decode::FrameCtx,
9154) -> Vec<u8> {
9155 let mut prediction = vec![0u16; side * side];
9156 mc::predict(
9157 reference,
9158 stride,
9159 ref_width,
9160 ref_height,
9161 mv_to_q4(x, mv.1, luma),
9162 mv_to_q4(y, mv.0, luma),
9163 side,
9164 side,
9165 &mut prediction,
9166 fctx,
9167 );
9168 prediction.iter().map(|&v| v as u8).collect()
9169}
9170
9171/// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's
9172/// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both
9173/// references predict into the `CONV_BUF` intermediate domain and are blended
9174/// at the simple-average split `(8, 8)`, the same path (and so the same
9175/// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes.
9176fn predict_compound_u8(
9177 ref0: (&[u16], usize, usize, usize),
9178 ref1: (&[u16], usize, usize, usize),
9179 (x, y): (usize, usize),
9180 side: usize,
9181 (mv0, mv1): ((i32, i32), (i32, i32)),
9182 luma: bool,
9183 fctx: &crate::decode::FrameCtx,
9184) -> Vec<u8> {
9185 let mut inter = [vec![0i32; side * side], vec![0i32; side * side]];
9186 for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) {
9187 mc::predict_compound_intermediate(
9188 r.0,
9189 r.1,
9190 r.2,
9191 r.3,
9192 mv_to_q4(x, mv.1, luma),
9193 mv_to_q4(y, mv.0, luma),
9194 mc::REF_NO_SCALE,
9195 side,
9196 side,
9197 fctx.interp_filter.get(),
9198 fctx.interp_filter.get(),
9199 dst,
9200 );
9201 }
9202 let mut blended = vec![0u16; side * side];
9203 mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx);
9204 blended.iter().map(|&v| v as u8).collect()
9205}
9206
9207/// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
9208/// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
9209/// SKIP, priced through the same `symbol_bits` path every other candidate
9210/// uses. The winner's prediction is committed to the planes (it IS the
9211/// reconstruction -- a skip block has no residual); the caller restores them
9212/// if the four quadrants come out cheaper.
9213///
9214/// `None` when no candidate could be coded at all (a `NEWMV` residual the
9215/// writer cannot name is simply not offered, and the other modes always are,
9216/// so this only happens if every candidate is refused).
9217fn search_skip_64(
9218 luma: &mut Plane,
9219 chroma: &mut [Plane; 2],
9220 (x, y): (usize, usize),
9221 search: &Search,
9222 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
9223 // screen content -- see that function's doc).
9224 residual: bool,
9225 reference: &Picture,
9226 stack: &MvStack,
9227 // The COMPOUND stack of each `LAST` + extra-reference pair at THIS
9228 // superblock's 16x16-mi window, built off the same grid the tile writer
9229 // rebuilds it from (empty unless the frame carries `reference_select`).
9230 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
9231 fctx: &crate::decode::FrameCtx,
9232) -> Option<(f64, BlockCoeffs)> {
9233 let side = SUPERBLOCK;
9234 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
9235 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
9236 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
9237 // What every candidate pays whatever its vector: `skip` coded 1, then
9238 // `is_inter` coded 1, then the LAST chain above.
9239 let fixed = skip_bits_at(stack, true) + intra_inter_bits_at(stack, true) + ref_bits;
9240 let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo {
9241 ref1: None,
9242 mv1: (0, 0),
9243 ref_frame: crate::mvstack::LAST_FRAME,
9244 mode,
9245 mv,
9246 ref_mv_idx,
9247 };
9248 let mut cands: Vec<(f64, InterInfo)> = vec![
9249 (
9250 not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
9251 info_of(InterMode::NearestMv, stack.nearest_mv, 0),
9252 ),
9253 (
9254 not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
9255 info_of(InterMode::GlobalMv, (0, 0), 0),
9256 ),
9257 ];
9258 let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
9259 for idx in 1..=2usize {
9260 if let Some(e) = stack.entries.get(idx) {
9261 cands.push((
9262 near_bits + drl_bits_for(stack, 1, idx),
9263 info_of(InterMode::NearMv, e.mv, idx as u8),
9264 ));
9265 }
9266 }
9267 // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV`
9268 // candidate below to pair with the second reference's NEAREST half.
9269 let mut last_new_mv: Option<(i32, i32)> = None;
9270 if leaf_new_mv() {
9271 let source_block = luma.source_block(x, y, side);
9272 let (seeds, seed_n) = mv_seeds(stack);
9273 let found = motion::search(
9274 &reference.y,
9275 reference.width,
9276 luma.true_width,
9277 luma.true_height,
9278 &source_block,
9279 x,
9280 y,
9281 side,
9282 side,
9283 stack.pred_mv,
9284 &seeds[..seed_n],
9285 search.lambda,
9286 fctx,
9287 1,
9288 );
9289 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
9290 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
9291 last_new_mv = Some(mv);
9292 cands.push((
9293 symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits),
9294 info_of(InterMode::NewMv, mv, ref_mv_idx),
9295 ));
9296 }
9297 }
9298
9299 let mut best: Option<(f64, f64, InterInfo, [Trial; 3])> = None;
9300 for (bits, info) in cands {
9301 let trials = [
9302 (0usize, x, y, side, true),
9303 (1, x / 2, y / 2, side / 2, false),
9304 (2, x / 2, y / 2, side / 2, false),
9305 ]
9306 .map(|(plane, px, py, s, is_luma)| {
9307 let (samples, stride, w, h) = match plane {
9308 0 => (&reference.y, reference.width, luma.true_width, luma.true_height),
9309 1 => (
9310 &reference.u,
9311 reference.width / 2,
9312 chroma[0].true_width,
9313 chroma[0].true_height,
9314 ),
9315 _ => (
9316 &reference.v,
9317 reference.width / 2,
9318 chroma[1].true_width,
9319 chroma[1].true_height,
9320 ),
9321 };
9322 let prediction = predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx);
9323 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
9324 // `skip` true: the trial is the prediction itself plus its SSE,
9325 // so no transform of any size is involved (the reason a 64x64
9326 // root can be coded at all before a forward TX_64X64 exists).
9327 target.code_from_prediction(
9328 px,
9329 py,
9330 s,
9331 &prediction,
9332 true,
9333 search.base_q_idx,
9334 search.deadzone,
9335 TxbSet::Luma32Inter,
9336 )
9337 });
9338 let cost = trials[0].sse
9339 + trials[1].sse
9340 + trials[2].sse
9341 + search.lambda * (fixed + bits);
9342 if best.as_ref().is_none_or(|b| cost < b.0) {
9343 best = Some((cost, fixed + bits, info, trials));
9344 }
9345 }
9346
9347 // lane-b64b: the COMPOUND candidates at the 64 root, the same three a
9348 // superblock can form without a second motion search ([`b64_compound`]),
9349 // priced through the same `symbol_bits` path -- `fixed` minus the single
9350 // reference's tree, plus the pair tree and the compound mode.
9351 for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) {
9352 let (ref1, g) = (*ref1, *g);
9353 // The whole `comp_mode` + reference-pair tree at the writer's own
9354 // contexts, for THIS pair (lane-ctx).
9355 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
9356 let mode_ctx =
9357 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
9358 let mode_bits_of =
9359 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
9360 let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo {
9361 ref1: Some(ref1),
9362 mv1: mvs.1,
9363 ref_frame: crate::mvstack::LAST_FRAME,
9364 mode,
9365 mv: mvs.0,
9366 ref_mv_idx: 0,
9367 };
9368 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
9369 (
9370 cstack.nearest_mv,
9371 mode_bits_of(0),
9372 compound_info(InterMode::NearestNearestMv, cstack.nearest_mv),
9373 ),
9374 (
9375 ((0, 0), (0, 0)),
9376 mode_bits_of(6),
9377 compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))),
9378 ),
9379 ];
9380 // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search
9381 // above, its residual priced against compound stack entry 0 -- what
9382 // `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
9383 let cbase = cstack
9384 .entries
9385 .first()
9386 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
9387 if let Some(new_mv) = last_new_mv
9388 && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
9389 {
9390 let mvs = (new_mv, cstack.nearest_mv.1);
9391 ccands.push((
9392 mvs,
9393 mode_bits_of(3) + b0,
9394 compound_info(InterMode::NewNearestMv, mvs),
9395 ));
9396 }
9397 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
9398 ccands.dedup_by_key(|c| c.0);
9399 for (mvs, bits, info) in ccands {
9400 let trials = [
9401 (0usize, x, y, side, true),
9402 (1, x / 2, y / 2, side / 2, false),
9403 (2, x / 2, y / 2, side / 2, false),
9404 ]
9405 .map(|(plane, px, py, s, is_luma)| {
9406 let (r0, r1) = match plane {
9407 0 => (
9408 (reference.y.as_slice(), reference.width, luma.true_width, luma.true_height),
9409 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
9410 ),
9411 1 => (
9412 (
9413 reference.u.as_slice(),
9414 reference.width / 2,
9415 chroma[0].true_width,
9416 chroma[0].true_height,
9417 ),
9418 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
9419 ),
9420 _ => (
9421 (
9422 reference.v.as_slice(),
9423 reference.width / 2,
9424 chroma[1].true_width,
9425 chroma[1].true_height,
9426 ),
9427 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
9428 ),
9429 };
9430 let prediction =
9431 predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx);
9432 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
9433 target.code_from_prediction(
9434 px,
9435 py,
9436 s,
9437 &prediction,
9438 true,
9439 search.base_q_idx,
9440 search.deadzone,
9441 TxbSet::Luma32Inter,
9442 )
9443 });
9444 let syntax = fixed - ref_bits + bits;
9445 let cost =
9446 trials[0].sse + trials[1].sse + trials[2].sse + search.lambda * syntax;
9447 if best.as_ref().is_none_or(|b| cost < b.0) {
9448 best = Some((cost, syntax, info, trials));
9449 }
9450 }
9451 }
9452
9453 let (skip_cost, syntax, info, skip_trials) = best?;
9454
9455 // The winner's prediction coded with a REAL residual (lane-tx64): one
9456 // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the
9457 // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per
9458 // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv
9459 // the skip arm already chose is re-coded: the prediction with the lowest
9460 // SSE is also the cheapest residual to code, and a second 64x64 motion
9461 // search per superblock is the wall this root was taken to SAVE.
9462 //
9463 // Priced against the skip arm through the same `symbol_bits` path, so the
9464 // two numbers are comparable: `fixed` charged `skip` coded 1, and this
9465 // arm charges 0 instead and adds its three planes' coefficient bits.
9466 let mut chosen = (skip_cost, true, skip_trials);
9467 // Set when [`commit_inter_luma`] already wrote the residual arm's luma
9468 // into the plane, so the tail below does not commit over its units.
9469 let mut luma_committed = false;
9470 // The residual arm's luma levels and the `txfm_split` depth the writer
9471 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is
9472 // four TX_32X32 units in 64x64 ones.
9473 let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None;
9474 if residual {
9475 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
9476 let residual_trials = [0usize, 1, 2].map(|plane| {
9477 let (target, px, py, s) = if plane == 0 {
9478 (&*luma, x, y, side)
9479 } else {
9480 (&chroma[plane - 1], x / 2, y / 2, side / 2)
9481 };
9482 target.code_from_prediction(
9483 px,
9484 py,
9485 s,
9486 &chosen.2[plane].reconstruction,
9487 false,
9488 search.base_q_idx,
9489 search.deadzone,
9490 sets[plane],
9491 )
9492 });
9493 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
9494 let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum();
9495 // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the
9496 // four TX_32X32 units of `txfm_split = 1`, taken by the same
9497 // `commit_inter_luma` every other inter block's is (it commits the
9498 // winner and hands back the cost it took off the flat arm).
9499 let (levels, depth, gain, tx_types) = if b64_var_tx() {
9500 let second = info.ref1.and_then(|r1| {
9501 compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| {
9502 (
9503 info.mv1,
9504 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
9505 )
9506 })
9507 });
9508 luma_committed = true;
9509 commit_inter_luma(
9510 luma,
9511 (x, y),
9512 side,
9513 info.mv,
9514 (&reference.y, reference.width, luma.true_width, luma.true_height),
9515 search,
9516 &residual_trials[0],
9517 false,
9518 second,
9519 fctx,
9520 )
9521 } else {
9522 (residual_trials[0].levels.clone(), 0, 0.0, Vec::new())
9523 };
9524 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
9525 + search.lambda * (syntax + unskip + coeff_bits)
9526 + gain;
9527 if cost < skip_cost {
9528 B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9529 if depth == 1 {
9530 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9531 }
9532 luma_levels = Some((levels, depth, tx_types));
9533 chosen = (cost, false, residual_trials);
9534 }
9535 }
9536
9537 let (cost, skip, trials) = chosen;
9538 // `commit_inter_luma` already wrote the residual arm's luma (its four
9539 // split units are not one 64-sided trial); a skip winner overwrites it.
9540 if skip || !luma_committed {
9541 luma.commit(x, y, side, &trials[0]);
9542 }
9543 chroma[0].commit(x / 2, y / 2, side / 2, &trials[1]);
9544 chroma[1].commit(x / 2, y / 2, side / 2, &trials[2]);
9545 Some((
9546 cost,
9547 BlockCoeffs {
9548 skip,
9549 inter: Some(info),
9550 // The chroma grids are whole TX_32X32; the luma one is the
9551 // 64-point transform's coded 32x32 corner at depth 0 and the
9552 // whole 64-sided block at depth 1 (lane-b64b).
9553 tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d),
9554 luma_tx_types: match (skip, &luma_levels) {
9555 (false, Some((_, _, types))) => types.clone(),
9556 _ => Vec::new(),
9557 },
9558 luma: match (skip, &luma_levels) {
9559 (true, _) => Vec::new(),
9560 (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK),
9561 (false, Some((levels, _, _))) => coeffs(levels, BLOCK),
9562 (false, None) => coeffs(&trials[0].levels, BLOCK),
9563 },
9564 u: if skip { Vec::new() } else { coeffs(&trials[1].levels, side / 2) },
9565 v: if skip { Vec::new() } else { coeffs(&trials[2].levels, side / 2) },
9566 ..BlockCoeffs::default()
9567 },
9568 ))
9569}
9570
9571fn search_inter_block(
9572 luma: &mut Plane,
9573 chroma: &mut [Plane; 2],
9574 (x, y): (usize, usize),
9575 search: &Search,
9576 mode_bits: &[f64; 13],
9577 reference: &Picture,
9578 stack: &MvStack,
9579 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
9580 // for the whole GOP, with the stack this block derives against it. Only
9581 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
9582 // second motion search would double the wall of the stage that already
9583 // owns most of it.
9584 extra: &[(i8, &Picture, &MvStack)],
9585 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
9586 // the caller off the same MI grid the tile writer will (empty unless the
9587 // frame carries `reference_select`).
9588 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
9589 // lane-av1obmc: the mi grid this search's neighbours were published into
9590 // (`record_mi`) and this block's own place in it -- what the OBMC
9591 // candidate's eligibility walk and neighbour plan read, the same state
9592 // the tile writer will read when it codes the `motion_mode` symbol.
9593 grid: &MiGrid,
9594 (mi_row, mi_col): (usize, usize),
9595 (mi_rows, mi_cols): (usize, usize),
9596 fctx: &crate::decode::FrameCtx,
9597) -> (BlockCoeffs, f64) {
9598 // `luma_set` is the INTRA candidates' table; the two inter candidates
9599 // below price their coefficients through `TxbSet::Luma32Inter`, which is
9600 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
9601 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
9602 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
9603 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
9604
9605 // skip / intra_inter symbol costs at a fixed context -- see this
9606 // function's doc comment.
9607 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
9608 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
9609
9610 struct Candidate {
9611 cost: f64,
9612 luma: Trial,
9613 u: Trial,
9614 v: Trial,
9615 mode: u8,
9616 skip: bool,
9617 inter: Option<InterInfo>,
9618 /// The mode/mv syntax this candidate pays for, apart from its
9619 /// residual -- what the OBMC candidate below has to re-pay when it
9620 /// re-prices the winner's prediction.
9621 mode_bits: f64,
9622 }
9623 let mut best: Option<Candidate> = None;
9624 let mut consider = |candidate: Candidate| {
9625 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
9626 best = Some(candidate);
9627 }
9628 };
9629
9630 // The chroma trial an intra candidate prices does not depend on `mode`
9631 // at all -- both planes always code `DC_PRED` here (a coding choice this
9632 // search inherited, not this loop's to second-guess) at the same `reach:
9633 // Reach::none()` -- so it is the same call with the same inputs on every
9634 // one of the thirteen iterations below; run it once and reuse the result
9635 // rather than repeat an already-priced transform/quantize/entropy call
9636 // twelve times for nothing (bit-identical: the value each iteration
9637 // reads back is exactly what it used to recompute).
9638 let u_trial = chroma[0].trial(
9639 At {
9640 x: x / 2,
9641 y: y / 2,
9642 side: BLOCK / 2,
9643 reach: Reach::none(),
9644 set: chroma_set,
9645 },
9646 DC_PRED,
9647 0,
9648 search.base_q_idx,
9649 search.deadzone, fctx,
9650 );
9651 let v_trial = chroma[1].trial(
9652 At {
9653 x: x / 2,
9654 y: y / 2,
9655 side: BLOCK / 2,
9656 reach: Reach::none(),
9657 set: chroma_set,
9658 },
9659 DC_PRED,
9660 0,
9661 search.base_q_idx,
9662 search.deadzone, fctx,
9663 );
9664
9665 let intra_modes: Vec<u8> = match search.top_k {
9666 Some(k) if k < search.modes.len() => {
9667 let scored = luma.intra_scores(
9668 At {
9669 x,
9670 y,
9671 side: BLOCK,
9672 reach,
9673 set: luma_set,
9674 },
9675 search.modes,
9676 mode_bits,
9677 search.lambda, fctx,
9678 );
9679 prune_by_sad(search.modes, scored, k)
9680 }
9681 _ => search.modes.to_vec(),
9682 };
9683 census_add(5, 1);
9684 census_add(6, intra_modes.len());
9685 for &mode in &intra_modes {
9686 let luma_trial = luma.trial(
9687 At {
9688 x,
9689 y,
9690 side: BLOCK,
9691 reach,
9692 set: luma_set,
9693 },
9694 mode,
9695 0,
9696 search.base_q_idx,
9697 search.deadzone, fctx,
9698 );
9699 let u = u_trial.clone();
9700 let v = v_trial.clone();
9701 let cost = luma_trial.sse
9702 + u.sse
9703 + v.sse
9704 + search.lambda
9705 * (luma_trial.bits
9706 + u.bits
9707 + v.bits
9708 + mode_bits[usize::from(mode)]
9709 + skip_bits(false)
9710 + intra_inter_bits(false));
9711 consider(Candidate {
9712 cost,
9713 luma: luma_trial,
9714 u,
9715 v,
9716 mode,
9717 skip: false,
9718 inter: None,
9719 mode_bits: mode_bits[usize::from(mode)],
9720 });
9721 }
9722
9723 // The reference frame buffer a spec decoder holds is exactly the true
9724 // (unpadded) coded extent -- a superblock whose partition stops early at
9725 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
9726 // beyond it, so those samples are never part of the decoded picture.
9727 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
9728 // reference sample position clamp), not to this crate's own
9729 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
9730 // here would let a fractional-pel read past the true edge pick up this
9731 // encoder's own uncoded padding instead of the true edge's replicated
9732 // value a decoder computes.
9733 let ref_luma = (
9734 &reference.y,
9735 reference.width,
9736 luma.true_width,
9737 luma.true_height,
9738 );
9739 let ref_u = (
9740 &reference.u,
9741 reference.width / 2,
9742 chroma[0].true_width,
9743 chroma[0].true_height,
9744 );
9745 let ref_v = (
9746 &reference.v,
9747 reference.width / 2,
9748 chroma[1].true_width,
9749 chroma[1].true_height,
9750 );
9751 // Every single-reference mode the writer can code (spec 5.11.24's symbol
9752 // chain, mirrored by `tile::write_inter_mode`), priced with the static
9753 // CDFs at this block's own stack contexts. A candidate is a motion
9754 // vector plus the cheapest syntax that reaches it, so two modes landing
9755 // on the same vector share one set of trials: the added modes cost
9756 // mode-bit arithmetic, not another motion compensation.
9757 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
9758 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
9759 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
9760 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
9761 // the loop cannot reach is never offered below -- every candidate's
9762 // index is one this same loop walks to.
9763 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
9764 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
9765 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
9766 (
9767 stack.nearest_mv,
9768 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
9769 InterInfo {
9770 ref1: None,
9771 mv1: (0, 0),
9772 ref_frame: crate::mvstack::LAST_FRAME,
9773 mode: InterMode::NearestMv,
9774 mv: stack.nearest_mv,
9775 ref_mv_idx: 0,
9776 },
9777 ),
9778 // GLOBALMV is the identity model's zero vector -- this encoder writes
9779 // no `gm_params` -- and the cheapest syntax of the four on the static
9780 // content where that vector is also the right one.
9781 (
9782 (0, 0),
9783 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
9784 InterInfo {
9785 ref1: None,
9786 mv1: (0, 0),
9787 ref_frame: crate::mvstack::LAST_FRAME,
9788 mode: InterMode::GlobalMv,
9789 mv: (0, 0),
9790 ref_mv_idx: 0,
9791 },
9792 ),
9793 ];
9794 let near_bits =
9795 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
9796 for idx in 1..=2usize {
9797 if let Some(e) = stack.entries.get(idx) {
9798 cands.push((
9799 e.mv,
9800 near_bits + drl_bits(1, idx),
9801 InterInfo {
9802 ref1: None,
9803 mv1: (0, 0),
9804 ref_frame: crate::mvstack::LAST_FRAME,
9805 mode: InterMode::NearMv,
9806 mv: e.mv,
9807 ref_mv_idx: idx as u8,
9808 },
9809 ));
9810 }
9811 }
9812
9813 let source_block = luma.source_block(x, y, BLOCK);
9814 let (seeds, seed_n) = mv_seeds(stack);
9815 #[cfg(test)]
9816 let t = stage_start();
9817 let found = motion::search(
9818 ref_luma.0,
9819 ref_luma.1,
9820 ref_luma.2,
9821 ref_luma.3,
9822 &source_block,
9823 x,
9824 y,
9825 BLOCK,
9826 BLOCK,
9827 stack.pred_mv,
9828 &seeds[..seed_n],
9829 search.lambda, fctx,
9830 1,
9831 );
9832 #[cfg(test)]
9833 stage_since(0, t);
9834 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
9835 // lane-newmv: this block's own `NEWMV` vector and what its mv syntax
9836 // costs, for the census below (`None` when the writer cannot name it).
9837 let mut newmv_syntax: Option<((i32, i32), f64)> = None;
9838 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
9839 // the same vector costs a different residual from each: take the index
9840 // whose residual plus DRL bits is cheapest, not entry 0 by default.
9841 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
9842 newmv_syntax = Some((mv, bits));
9843 cands.push((
9844 mv,
9845 last_ref_bits
9846 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
9847 + bits
9848 + mv_rate_surcharge(bits),
9849 InterInfo {
9850 ref1: None,
9851 mv1: (0, 0),
9852 ref_frame: crate::mvstack::LAST_FRAME,
9853 mode: InterMode::NewMv,
9854 mv,
9855 ref_mv_idx,
9856 },
9857 ));
9858 }
9859
9860 // Each extra reference's own `NEWMV` vector, for the compound
9861 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
9862 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
9863 for &(ref_frame, g, gstack) in extra {
9864 let g_ref_bits = single_ref_bits(ref_frame, gstack);
9865 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
9866 cands.push((
9867 gstack.nearest_mv,
9868 g_ref_bits
9869 + g_not_new
9870 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
9871 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
9872 InterInfo {
9873 ref1: None,
9874 mv1: (0, 0),
9875 ref_frame,
9876 mode: InterMode::NearestMv,
9877 mv: gstack.nearest_mv,
9878 ref_mv_idx: 0,
9879 },
9880 ));
9881 cands.push((
9882 (0, 0),
9883 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
9884 InterInfo {
9885 ref1: None,
9886 mv1: (0, 0),
9887 ref_frame,
9888 mode: InterMode::GlobalMv,
9889 mv: (0, 0),
9890 ref_mv_idx: 0,
9891 },
9892 ));
9893 // A motion search of this reference's own: without it, GOLDEN/ALTREF
9894 // can only be coded at a vector some neighbour already found, which
9895 // is why they carried a third of the inter blocks at their two
9896 // search-free modes alone.
9897 // The search is skipped when this reference's own NEARESTMV already
9898 // prices out `margin` times better than LAST's best vector does --
9899 // one candidate evaluation (`motion::cost_at`) standing in for a
9900 // whole search of ~50.
9901 // lane-last2: the SEARCH-FREE arm for the second past leaf picture
9902 // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some
9903 // neighbour already found, which is how GOLDEN/ALTREF were offered
9904 // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's
9905 // own value from the second motion search's wall.
9906 let searched = extra_ref_new_mv()
9907 && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());
9908 let margin = extra_new_skip_margin();
9909 if searched {
9910 newmv_census_global(0);
9911 }
9912 let skip_search = searched
9913 && margin > 0.0
9914 && motion::cost_at(
9915 &g.y,
9916 g.width,
9917 luma.true_width,
9918 luma.true_height,
9919 &source_block,
9920 x,
9921 y,
9922 BLOCK,
9923 BLOCK,
9924 gstack.nearest_mv,
9925 gstack.pred_mv,
9926 search.lambda,
9927 fctx,
9928 ) * margin
9929 <= found.cost;
9930 if skip_search {
9931 newmv_census_global(1);
9932 }
9933 if searched && !skip_search {
9934 let (gseeds, gn) = mv_seeds(gstack);
9935 #[cfg(test)]
9936 let t = stage_start();
9937 let gfound = motion::search(
9938 &g.y,
9939 g.width,
9940 luma.true_width,
9941 luma.true_height,
9942 &source_block,
9943 x,
9944 y,
9945 BLOCK,
9946 BLOCK,
9947 gstack.pred_mv,
9948 &gseeds[..gn],
9949 search.lambda, fctx,
9950 ref_distance(ref_frame),
9951 );
9952 #[cfg(test)]
9953 stage_since(0, t);
9954 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
9955 extra_new_mvs.push((ref_frame, gmv));
9956 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
9957 cands.push((
9958 gmv,
9959 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
9960 InterInfo {
9961 ref1: None,
9962 mv1: (0, 0),
9963 ref_frame,
9964 mode: InterMode::NewMv,
9965 mv: gmv,
9966 ref_mv_idx,
9967 },
9968 ));
9969 }
9970 }
9971 }
9972
9973 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
9974 // trial set each: both references predict the block and the two
9975 // predictions are averaged, which is what pays on content where neither
9976 // reference alone is right. Priced with the same static-CDF approximation
9977 // the single-reference candidates use, plus the compound-only symbols
9978 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
9979 // The two compound-mode arms, each measured alone on the BD gate before
9980 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
9981 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
9982 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
9983 // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on:
9984 // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5,
9985 // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of
9986 // the keep rule. Still behind the knob.
9987 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
9988 let half_new = true;
9989 for (ref1, g, cstack) in compound {
9990 let (ref1, g) = (*ref1, *g);
9991 // The whole `comp_mode` + reference-pair tree at the writer's own
9992 // contexts, for THIS pair (lane-ctx).
9993 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
9994 let mode_ctx =
9995 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
9996 let mode_bits_of =
9997 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
9998 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
9999 (
10000 cstack.nearest_mv,
10001 mode_bits_of(0),
10002 InterInfo {
10003 ref_frame: crate::mvstack::LAST_FRAME,
10004 mode: InterMode::NearestNearestMv,
10005 mv: cstack.nearest_mv.0,
10006 mv1: cstack.nearest_mv.1,
10007 ref1: Some(ref1),
10008 ref_mv_idx: 0,
10009 },
10010 ),
10011 (
10012 ((0, 0), (0, 0)),
10013 mode_bits_of(6),
10014 InterInfo {
10015 ref_frame: crate::mvstack::LAST_FRAME,
10016 mode: InterMode::GlobalGlobalMv,
10017 mv: (0, 0),
10018 mv1: (0, 0),
10019 ref1: Some(ref1),
10020 ref_mv_idx: 0,
10021 },
10022 ),
10023 ];
10024 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
10025 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
10026 // the stack is deep enough for that walk to read one.
10027 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
10028 let drl = if cstack.entries.len() > 2 {
10029 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
10030 } else {
10031 0.0
10032 };
10033 ccands.push((
10034 (e.mv0, e.mv1),
10035 mode_bits_of(1) + drl,
10036 InterInfo {
10037 ref_frame: crate::mvstack::LAST_FRAME,
10038 mode: InterMode::NearNearMv,
10039 mv: e.mv0,
10040 mv1: e.mv1,
10041 ref1: Some(ref1),
10042 ref_mv_idx: 0,
10043 },
10044 ));
10045 }
10046 // The half-new modes and `NEW_NEWMV`, all seeded from the two
10047 // single-reference searches this block already ran -- no joint search
10048 // of its own. Every residual is priced against stack entry 0, which
10049 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
10050 let cbase = cstack
10051 .entries
10052 .first()
10053 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
10054 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
10055 ccands.push((
10056 (mv, cstack.nearest_mv.1),
10057 mode_bits_of(3) + b0,
10058 InterInfo {
10059 ref_frame: crate::mvstack::LAST_FRAME,
10060 mode: InterMode::NewNearestMv,
10061 mv,
10062 mv1: cstack.nearest_mv.1,
10063 ref1: Some(ref1),
10064 ref_mv_idx: 0,
10065 },
10066 ));
10067 }
10068 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
10069 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
10070 ccands.push((
10071 (cstack.nearest_mv.0, mv1),
10072 mode_bits_of(2) + b1,
10073 InterInfo {
10074 ref_frame: crate::mvstack::LAST_FRAME,
10075 mode: InterMode::NearestNewMv,
10076 mv: cstack.nearest_mv.0,
10077 mv1,
10078 ref1: Some(ref1),
10079 ref_mv_idx: 0,
10080 },
10081 ));
10082 }
10083 let base = cbase;
10084 if let (Some(b0), Some(b1)) = (
10085 mv_residual_bits(mv, base.0),
10086 mv_residual_bits(mv1, base.1),
10087 ) {
10088 ccands.push((
10089 (mv, mv1),
10090 mode_bits_of(7) + b0 + b1,
10091 InterInfo {
10092 ref_frame: crate::mvstack::LAST_FRAME,
10093 mode: InterMode::NewNewMv,
10094 mv,
10095 mv1,
10096 ref1: Some(ref1),
10097 ref_mv_idx: 0,
10098 },
10099 ));
10100 }
10101 }
10102 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
10103 ccands.dedup_by_key(|c| c.0);
10104 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
10105 let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height);
10106 let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height);
10107 for (mvs, bits, info) in ccands {
10108 let luma_trial = mc_trial_compound(
10109 luma, x, y, BLOCK, mvs, true,
10110 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
10111 search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx,
10112 );
10113 let u = mc_trial_compound(
10114 &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false,
10115 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
10116 search.base_q_idx, search.deadzone, chroma_set, fctx,
10117 );
10118 let v = mc_trial_compound(
10119 &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false,
10120 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
10121 search.base_q_idx, search.deadzone, chroma_set, fctx,
10122 );
10123 let skip = luma_trial.levels.iter().all(|&l| l == 0)
10124 && u.levels.iter().all(|&l| l == 0)
10125 && v.levels.iter().all(|&l| l == 0);
10126 let cost = luma_trial.sse
10127 + u.sse
10128 + v.sse
10129 + search.lambda
10130 * (skip_bits(skip)
10131 + intra_inter_bits(true)
10132 + bits
10133 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
10134 consider(Candidate {
10135 cost,
10136 luma: luma_trial,
10137 u,
10138 v,
10139 mode: DC_PRED,
10140 skip,
10141 mode_bits: bits,
10142 inter: Some(info),
10143 });
10144 }
10145 }
10146
10147 // One trial set per distinct (reference, vector) pair: sort, cheapest
10148 // syntax first, and drop the rest of each pair's run.
10149 cands.sort_by(|a, b| {
10150 (a.2.ref_frame, a.0)
10151 .cmp(&(b.2.ref_frame, b.0))
10152 .then(a.1.total_cmp(&b.1))
10153 });
10154 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
10155 census_add(7, cands.len());
10156 // lane-newmv: the NEWMV candidate's own RD cost against the best cost
10157 // this block reaches WITHOUT it, taken inside the one loop that prices
10158 // them all (a second pricing pass would be a second oracle).
10159 let (mut new_cost, mut other_cost) = (f64::INFINITY, f64::INFINITY);
10160 {
10161 for (mv, mode_bits_inter, info) in cands {
10162 let (ref_luma, ref_u, ref_v) = match extra
10163 .iter()
10164 .find(|(r, _, _)| *r == info.ref_frame)
10165 {
10166 Some(&(_, g, _)) => (
10167 (&g.y, g.width, luma.true_width, luma.true_height),
10168 (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
10169 (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
10170 ),
10171 None => (ref_luma, ref_u, ref_v),
10172 };
10173 let luma_trial = mc_trial(
10174 luma,
10175 x,
10176 y,
10177 BLOCK,
10178 mv,
10179 true,
10180 ref_luma.0,
10181 ref_luma.1,
10182 ref_luma.2,
10183 ref_luma.3,
10184 false,
10185 search.base_q_idx,
10186 search.deadzone,
10187 TxbSet::Luma32Inter, fctx,
10188 );
10189 let u = mc_trial(
10190 &chroma[0],
10191 x / 2,
10192 y / 2,
10193 BLOCK / 2,
10194 mv,
10195 false,
10196 ref_u.0,
10197 ref_u.1,
10198 ref_u.2,
10199 ref_u.3,
10200 false,
10201 search.base_q_idx,
10202 search.deadzone,
10203 chroma_set, fctx,
10204 );
10205 let v = mc_trial(
10206 &chroma[1],
10207 x / 2,
10208 y / 2,
10209 BLOCK / 2,
10210 mv,
10211 false,
10212 ref_v.0,
10213 ref_v.1,
10214 ref_v.2,
10215 ref_v.3,
10216 false,
10217 search.base_q_idx,
10218 search.deadzone,
10219 chroma_set, fctx,
10220 );
10221 let skip = luma_trial.levels.iter().all(|&l| l == 0)
10222 && u.levels.iter().all(|&l| l == 0)
10223 && v.levels.iter().all(|&l| l == 0);
10224 let cost = luma_trial.sse
10225 + u.sse
10226 + v.sse
10227 + search.lambda
10228 * (skip_bits(skip)
10229 + intra_inter_bits(true)
10230 + mode_bits_inter
10231 + if skip {
10232 0.0
10233 } else {
10234 luma_trial.bits + u.bits + v.bits
10235 });
10236 consider(Candidate {
10237 cost,
10238 luma: luma_trial,
10239 u,
10240 v,
10241 mode: DC_PRED,
10242 skip,
10243 mode_bits: mode_bits_inter,
10244 inter: Some(info),
10245 });
10246 if newmv_census_on() {
10247 if info.mode == InterMode::NewMv
10248 && info.ref1.is_none()
10249 && info.ref_frame == crate::mvstack::LAST_FRAME
10250 {
10251 new_cost = cost;
10252 } else {
10253 other_cost = other_cost.min(cost);
10254 }
10255 }
10256 }
10257 }
10258 if let Some((new_mv, bits)) = newmv_syntax {
10259 newmv_census_block(BLOCK, true, new_cost, other_cost, new_mv, stack.nearest_mv, bits);
10260 } else {
10261 newmv_census_block(BLOCK, false, f64::INFINITY, other_cost, mv, stack.nearest_mv, 0.0);
10262 }
10263
10264 let best = best.expect("the search offers at least the intra modes");
10265 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
10266 // offered to the SINGLE-REFERENCE winner only -- libaom's
10267 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
10268 // compound block, so the writer codes no symbol for one. The prediction
10269 // is built by the DECODER's own plan and blend
10270 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
10271 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
10272 // this search's `grid` already carries, so what is priced here is what a
10273 // decoder reconstructs -- never a second implementation of the blend.
10274 //
10275 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
10276 // on). Native crop BD, the standing recipe, with it on against the same
10277 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
10278 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
10279 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
10280 // one UP -- the keep rule wants two down and one flat, so it stays off.
10281 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
10282 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
10283 // things bound it and are the upgrade path: only the 32x32 winner is
10284 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
10285 // that is where libaom cashes most of its OBMC gain), and the symbol/
10286 // residual price here is the static-CDF estimate.
10287 let mut best = best;
10288 let mut motion_won = 0u8;
10289 if let Some(info) = best.inter.filter(|i| {
10290 i.ref1.is_none()
10291 && (crate::envflags::env_flag!("EC_AV1_OBMC")
10292 || warp_on())
10293 }) {
10294 let mut refs: [Option<&Picture>; 8] = [None; 8];
10295 refs[LAST_FRAME as usize] = Some(reference);
10296 for &(r, p, _) in extra {
10297 refs[r as usize] = Some(p);
10298 }
10299 // This block's OWN reference planes: the single-reference winner may
10300 // be one of the extra references, not LAST.
10301 let planes: [(&[u16], usize, usize, usize); 3] =
10302 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
10303 Some(&(_, g, _)) => [
10304 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
10305 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
10306 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
10307 ],
10308 None => [
10309 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
10310 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
10311 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
10312 ],
10313 };
10314 // The alphabet `tile::write_motion_mode` will code this block's
10315 // symbol against, mirrored term for term (libaom
10316 // `motion_mode_allowed`).
10317 let warp_alphabet = warp_on()
10318 && crate::decode::num_proj_ref(
10319 grid,
10320 mi_row,
10321 mi_col,
10322 8,
10323 8,
10324 mi_cols,
10325 mi_rows,
10326 info.ref_frame,
10327 fctx,
10328 ) >= 1;
10329 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
10330 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
10331 if crate::envflags::env_flag!("EC_AV1_OBMC") {
10332 if let Some(pred) = obmc_prediction(
10333 grid,
10334 (mi_row, mi_col),
10335 (mi_rows, mi_cols),
10336 (x, y),
10337 BLOCK,
10338 info.mv,
10339 &refs,
10340 planes,
10341 reference.width,
10342 fctx,
10343 ) {
10344 candidates.push((1, pred));
10345 }
10346 }
10347 if warp_alphabet {
10348 if let Some(pred) = warp_prediction(
10349 grid,
10350 (mi_row, mi_col),
10351 (mi_rows, mi_cols),
10352 (x, y),
10353 BLOCK,
10354 info.mv,
10355 info.ref_frame,
10356 planes,
10357 fctx,
10358 ) {
10359 candidates.push((2, pred));
10360 }
10361 }
10362 for (motion, pred) in candidates {
10363 let luma_trial = luma.code_from_prediction(
10364 x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone,
10365 TxbSet::Luma32Inter,
10366 );
10367 let u = chroma[0].code_from_prediction(
10368 x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone,
10369 chroma_set,
10370 );
10371 let v = chroma[1].code_from_prediction(
10372 x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone,
10373 chroma_set,
10374 );
10375 let skip = luma_trial.levels.iter().all(|&l| l == 0)
10376 && u.levels.iter().all(|&l| l == 0)
10377 && v.levels.iter().all(|&l| l == 0);
10378 let cost = luma_trial.sse
10379 + u.sse
10380 + v.sse
10381 + search.lambda
10382 * (skip_bits(skip)
10383 + intra_inter_bits(true)
10384 + best.mode_bits
10385 + mm(motion)
10386 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
10387 if cost < best.cost + search.lambda * mm(motion_won) {
10388 motion_won = motion;
10389 best = Candidate {
10390 cost,
10391 luma: luma_trial,
10392 u,
10393 v,
10394 mode: DC_PRED,
10395 skip,
10396 mode_bits: best.mode_bits,
10397 inter: best.inter,
10398 };
10399 }
10400 }
10401 }
10402 // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`,
10403 // default OFF): the four 16x16 units of `commit_inter_luma` against the
10404 // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured
10405 // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and
10406 // RE-MEASURED it at 0.05, where the rate weight is half of what rejected
10407 // it, and it is worse again on the deciding native table: film 1080p
10408 // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the
10409 // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off --
10410 // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1
10411 // up against rav1e. (640x384 reads it slightly the other way, +70.0/
10412 // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and
10413 // +28.4/+47.4/-4.0 -- the native table decides.)
10414 //
10415 // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks,
10416 // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing
10417 // either, and the census names the row: the split units' own set
10418 // `Luma16Inter` is priced within 1.4% of what it is written at in every
10419 // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced
10420 // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting,
10421 // so a perfect pricer would split even more, and more splitting is what
10422 // measured worse. The four extra txb_skip/eob symbols simply cost more
10423 // ladder bytes than the local RD saves. The flat 32x32 transform stays.
10424 // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection
10425 // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the
10426 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
10427 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
10428 // plain translation, which is not the prediction it was priced from.
10429 let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) {
10430 Some(info) => {
10431 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
10432 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
10433 None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
10434 };
10435 let second = info.ref1.and_then(|r| {
10436 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
10437 (
10438 info.mv1,
10439 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
10440 )
10441 })
10442 });
10443 match info.ref1.is_some() && second.is_none() {
10444 true => {
10445 luma.commit(x, y, BLOCK, &best.luma);
10446 (best.luma.levels.clone(), 0, 0.0, Vec::new())
10447 }
10448 false => commit_inter_luma(
10449 luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second,
10450 fctx,
10451 ),
10452 }
10453 }
10454 None => {
10455 luma.commit(x, y, BLOCK, &best.luma);
10456 (best.luma.levels.clone(), 0, 0.0, Vec::new())
10457 }
10458 };
10459 // lane-txrd: chroma follows the luma type the var-tx/type search chose.
10460 let [bu, bv] = match (best.inter.filter(|_| motion_won == 0), luma_tx_types.first().copied()) {
10461 (Some(info), Some(t)) => {
10462 let (ou, ov) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
10463 Some(&(_, g, _)) => (
10464 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
10465 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
10466 ),
10467 None => (
10468 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
10469 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
10470 ),
10471 };
10472 let sec = info.ref1.and_then(|r| {
10473 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
10474 (
10475 info.mv1,
10476 [
10477 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
10478 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
10479 ],
10480 )
10481 })
10482 });
10483 recode_inter_chroma(
10484 chroma, (x, y), BLOCK, info.mv, [ou, ov], sec, search, chroma_set, t, fctx,
10485 )
10486 .unwrap_or([best.u, best.v])
10487 }
10488 _ => [best.u, best.v],
10489 };
10490 let best = Candidate { u: bu, v: bv, ..best };
10491 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
10492 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
10493 (
10494 BlockCoeffs {
10495 luma_tx_types,
10496 angle_delta_y: 0,
10497 cfl_alphas: None,
10498 filter_intra: None,
10499 luma: coeffs(&levels, BLOCK),
10500 u: coeffs(&best.u.levels, BLOCK / 2),
10501 v: coeffs(&best.v.levels, BLOCK / 2),
10502 mode: best.mode,
10503 uv_mode: DC_PRED,
10504 skip: best.skip,
10505 inter: best.inter,
10506 motion_mode: motion_won,
10507 eight: None,
10508 dv: None,
10509 palette: None,
10510 palette_uv: None,
10511 tx_depth,
10512 },
10513 best.cost + dcost,
10514 )
10515}
10516
10517/// lane-av1tpl: the strength `k` of the temporal lambda weighting
10518/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
10519/// is what every measurement before this lane was taken on. Swept by
10520/// `EC_AV1_TPL=<k>`.
10521///
10522/// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs
10523/// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane
10524/// baseline exactly, which is the control the rest of the table is read
10525/// against:
10526///
10527/// | k | film 1080p | film 2160p | screen |
10528/// |---|---|---|---|
10529/// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 |
10530/// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 |
10531/// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** |
10532/// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 |
10533/// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 |
10534///
10535/// 0.5 is the only arm that is at least flat on every row and down on five of
10536/// the six columns, so it ships as the default. The lookahead pass that feeds
10537/// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
10538const TPL_STRENGTH: f64 = 0.5;
10539
10540/// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec
10541/// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then
10542/// byte-identical to the pre-lane one); anything else is the `delta_q_res`
10543/// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off.
10544///
10545/// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has
10546/// nothing to vary the quantizer BY and codes no delta syntax at all.
10547fn deltaq_res_log2() -> Option<u8> {
10548 match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
10549 u8::MAX => {}
10550 4 => return None,
10551 r => return Some(r),
10552 }
10553 match crate::envflags::var("EC_AV1_DELTAQ").ok().as_deref().map(str::trim) {
10554 Some("0") => None,
10555 Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3),
10556 None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4),
10557 }
10558}
10559
10560/// A PROCESS-GLOBAL [`deltaq_res_log2`] override that wins over both the
10561/// environment and the preset -- `u8::MAX` = unset, `4` = off. The gate that
10562/// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
10563/// speed presets take, because the streams every other test pins move under
10564/// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).
10565static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 =
10566 std::sync::atomic::AtomicU8::new(u8::MAX);
10567
10568/// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
10569#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
10570pub(crate) fn set_deltaq_res(res_log2: Option<u8>) {
10571 DELTAQ_OVERRIDE.store(
10572 res_log2.unwrap_or(u8::MAX),
10573 std::sync::atomic::Ordering::Relaxed,
10574 );
10575}
10576
10577/// How much of the derived qindex step is actually taken
10578/// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation).
10579fn deltaq_k() -> f64 {
10580 crate::envflags::var("EC_AV1_DELTAQ_K")
10581 .ok()
10582 .and_then(|v| v.trim().parse::<f64>().ok())
10583 .filter(|k| k.is_finite() && *k >= 0.0)
10584 .unwrap_or(1.0)
10585}
10586
10587/// The largest qindex the map may move a superblock by, either way
10588/// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective
10589/// deltaq around a quarter of the base qindex).
10590fn deltaq_clamp() -> i32 {
10591 crate::envflags::var("EC_AV1_DELTAQ_CLAMP")
10592 .ok()
10593 .and_then(|v| v.trim().parse::<i32>().ok())
10594 .filter(|c| (0..=63).contains(c))
10595 .unwrap_or(16)
10596}
10597
10598/// The qindex a lambda factor `f` asks for, derived rather than fitted.
10599///
10600/// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the
10601/// square of the quantizer step (`encode_inter_frame`'s own
10602/// `lambda = .. * step * step`), so the step this superblock wants is
10603/// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the
10604/// step ratio is inverted through the table itself -- the index whose `ac_q`
10605/// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted
10606/// constant. `k` scales the resulting step (1.0 takes all of it), `clamp`
10607/// bounds it, and the answer is snapped onto the `res` grid so that every
10608/// superblock's qindex is congruent to `base` and the coded delta is a whole
10609/// number of steps.
10610fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 {
10611 let base_ac = f64::from(ac_q(8, i32::from(base)));
10612 let target = base_ac * f.max(1e-6).sqrt();
10613 let exact = (1..=255)
10614 .min_by(|&a, &b| {
10615 let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs();
10616 d(a).partial_cmp(&d(b)).expect("ac_q is finite")
10617 })
10618 .expect("the qindex range is not empty")
10619 - i32::from(base);
10620 let want = (exact as f64 * k).round() as i32;
10621 // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound
10622 // and need not be a whole number of steps, and clamping afterwards would
10623 // hand back a qindex that is not congruent to `base`.
10624 let max_steps = clamp / res;
10625 let steps = (want as f64 / f64::from(res)).round() as i32;
10626 let delta = steps.clamp(-max_steps, max_steps) * res;
10627 (i32::from(base) + delta).clamp(1, 255) as u8
10628}
10629
10630/// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1`
10631/// objective would, from the SAME tpl dependence ratio our own map already
10632/// carries (`EC_AV1_DQ_TPL=1`).
10633///
10634/// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a
10635/// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the
10636/// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very
10637/// same expression at frame scope) by it, and asks
10638/// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose
10639/// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and
10640/// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`,
10641/// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way
10642/// libaom reads `r0`. The offset is clamped to libaom's own
10643/// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than
10644/// twice the +-16 qindex [`deltaq_for_factor`] allows.
10645///
10646/// Two things differ from [`deltaq_for_factor`] and both are the point of the
10647/// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw
10648/// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed,
10649/// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is
10650/// much stronger for the same map. `strength` scales the offset.
10651fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 {
10652 let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6);
10653 let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt();
10654 let exact = (1..=255)
10655 .min_by(|&a, &b| {
10656 let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs();
10657 d(a).partial_cmp(&d(b)).expect("dc_q is finite")
10658 })
10659 .expect("the qindex range is not empty")
10660 - i32::from(base);
10661 let want = exact as f64 * strength;
10662 // Snapped onto the `res` grid first, so the coded delta is a whole number
10663 // of steps, then bounded by libaom's own `res * 9 - 1`.
10664 let max_steps = (res * 9 - 1) / res;
10665 let steps = (want / f64::from(res)).round() as i32;
10666 let delta = steps.clamp(-max_steps, max_steps) * res;
10667 (i32::from(base) + delta).clamp(1, 255) as u8
10668}
10669
10670/// The frame-level `r0` libaom's objective divides by: the log-mean of
10671/// `1 + r` over the frame's cells, minus 1.
10672fn tpl_frame_ratio(ratio: &[f64]) -> f64 {
10673 if ratio.is_empty() {
10674 return 0.0;
10675 }
10676 let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64;
10677 m.exp() - 1.0
10678}
10679
10680/// The [`deltaq_libaom`] strength, or `None` to keep the shipped
10681/// [`deltaq_for_factor`] derivation.
10682///
10683/// `EC_AV1_DQ_TPL=0`/`1` forces the mapping either way and `EC_AV1_DQ_TPL_K`
10684/// the strength (default 1.0 = libaom's own offset when the flag armed it);
10685/// with neither set the preset decides, see [`crate::speed::DQ_TPL_K`].
10686fn dq_tpl_strength() -> Option<f64> {
10687 let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K")
10688 .ok()
10689 .and_then(|v| v.trim().parse::<f64>().ok())
10690 .filter(|k| k.is_finite() && *k >= 0.0);
10691 match crate::envflags::var("EC_AV1_DQ_TPL").ok().as_deref().map(str::trim) {
10692 Some("0") => return None,
10693 Some(_) => return Some(env_k.unwrap_or(1.0)),
10694 None => {}
10695 }
10696 env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))).filter(|k| *k > 0.0)
10697}
10698
10699/// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the
10700/// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones
10701/// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and
10702/// the same tpl map -- and which of the two the frame actually coded.
10703fn dq_census() -> bool {
10704 crate::envflags::var("EC_AV1_DQ_CENSUS").ok().as_deref().map(str::trim) == Some("1")
10705}
10706
10707/// The histogram/extent summary [`dq_census`] prints for one set of offsets.
10708fn dq_summary(offsets: &[i32]) -> String {
10709 let n = offsets.len().max(1);
10710 let (lo, hi) = offsets.iter().fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o)));
10711 let nz = offsets.iter().filter(|&&o| o != 0).count();
10712 let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64;
10713 let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64;
10714 let mut levels: Vec<i32> = offsets.to_vec();
10715 levels.sort_unstable();
10716 levels.dedup();
10717 format!(
10718 "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}",
10719 offsets.len(),
10720 levels.len()
10721 )
10722}
10723
10724/// How many DISTINCT per-superblock quantizer levels the last inter frame's
10725/// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter
10726/// (class `gate-blind-to-feature`: every exactness assert below passes on a
10727/// grid that is one flat value, i.e. on no delta_q at all). Process-global
10728/// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
10729/// keeps the LARGEST count seen since the last read.
10730static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
10731
10732/// [`DELTAQ_LEVELS`], reset to 0.
10733#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
10734pub(crate) fn take_deltaq_levels() -> usize {
10735 DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
10736}
10737
10738/// This superblock's search state: the quantizer it is coded at, and the
10739/// lambda that quantizer implies. RD lambda goes as the square of the step,
10740/// which is exactly the relation [`deltaq_for_factor`] inverted, so with no
10741/// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour
10742/// before lane-deltaq).
10743fn sb_q_search<'m>(
10744 sb_q: &[u8],
10745 sb_cols: usize,
10746 base_q_idx: u8,
10747 (sb_r, sb_c): (usize, usize),
10748 base: Search<'m>,
10749) -> Search<'m> {
10750 let q = sb_q[sb_r * sb_cols + sb_c];
10751 let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx)));
10752 Search { base_q_idx: q, lambda: base.lambda * ratio * ratio, ..base }
10753}
10754
10755fn tpl_strength() -> f64 {
10756 std::env::var("EC_AV1_TPL")
10757 .ok()
10758 .and_then(|v| v.parse::<f64>().ok())
10759 .filter(|k| k.is_finite() && *k >= 0.0)
10760 .unwrap_or(TPL_STRENGTH)
10761}
10762
10763/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
10764/// the frame being coded. 1 turns the weighting off; 2 is the shipped
10765/// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under
10766/// [`tpl_propagating`], which is the map that can actually use them and is
10767/// the default since lane-av1tpl3, so the default window is 8. Swept by
10768/// `EC_AV1_TPL_D=<d>`.
10769///
10770/// The streaming facade holds `depth - 1` pictures back so it feeds
10771/// `encode_inter_frame` the same window `encode_sequence` does; both read
10772/// THIS function, so the two paths cannot disagree about the window.
10773pub(crate) const TPL_DEPTH: usize = 8;
10774
10775/// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
10776/// 0.5 is libaom's own square-root compression of its dependence ratio.
10777const TPL_POWER: f64 = 0.5;
10778
10779/// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the
10780/// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`.
10781///
10782/// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom
10783/// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map
10784/// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]:
10785///
10786/// | k | D | p | film 1080p | film 2160p | screen |
10787/// |---|---|---|---|---|---|
10788/// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 |
10789/// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 |
10790/// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 |
10791/// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 |
10792/// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 |
10793/// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 |
10794/// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 |
10795/// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 |
10796/// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 |
10797/// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** |
10798/// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 |
10799/// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 |
10800///
10801/// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of
10802/// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside
10803/// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p
10804/// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was
10805/// 0.1..0.4 UP on film 2160p, so it shipped off.
10806///
10807/// lane-av1tpl3 found why and turned it on. The denominator is the cell's own
10808/// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour
10809/// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of
10810/// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1
10811/// wherever the window leans on a flat bar, which is exactly where coding is
10812/// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio
10813/// (libaom's own granularity) puts a busy cell's denominator next to the flat
10814/// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed
10815/// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on
10816/// the same native gate (baseline = the shipped one-frame map):
10817///
10818/// | arm | film 1080p | film 2160p | screen |
10819/// |---|---|---|---|
10820/// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 |
10821/// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 |
10822/// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 |
10823/// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 |
10824/// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 |
10825/// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 |
10826/// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 |
10827/// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 |
10828/// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 |
10829/// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** |
10830///
10831/// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4,
10832/// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships
10833/// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The
10834/// floor is a real effect on the ratio and never a win once the aggregation
10835/// is in -- the aggregation is the same fix, done where libaom does it.
10836fn tpl_propagating() -> bool {
10837 std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0")
10838}
10839
10840pub(crate) fn tpl_depth() -> usize {
10841 std::env::var("EC_AV1_TPL_D")
10842 .ok()
10843 .and_then(|v| v.parse::<usize>().ok())
10844 .filter(|d| *d >= 1)
10845 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH))
10846 .max(1)
10847}
10848
10849/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
10850/// process, so the gate can price it against the encode it rides on.
10851static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
10852
10853/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
10854/// the winning displacement and its SAD.
10855///
10856/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
10857/// the left/above winners, first-best tie-break. Built once on the frame's
10858/// own thread and read-only afterwards, so it cannot make a tile's bytes
10859/// depend on the thread count.
10860fn tpl_coarse_pass(
10861 cur: &[u8],
10862 next: &[u8],
10863 width: usize,
10864 height: usize,
10865) -> Vec<((i32, i32), u32)> {
10866 let (cells_x, cells_y) = (width / 16, height / 16);
10867 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
10868 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
10869 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
10870 return u32::MAX;
10871 }
10872 let (sx, sy) = (sx as usize, sy as usize);
10873 let mut sum = 0u32;
10874 for r in 0..16 {
10875 let a = &next[(by + r) * width + bx..][..16];
10876 let b = &cur[(sy + r) * width + sx..][..16];
10877 sum += a.iter().zip(b).map(|(&p, &q)| u32::from(p.abs_diff(q))).sum::<u32>();
10878 }
10879 sum
10880 };
10881 let mut out = Vec::with_capacity(cells_x * cells_y);
10882 let mut above = vec![(0i32, 0i32); cells_x];
10883 for cy in 0..cells_y {
10884 let mut left = (0i32, 0i32);
10885 for cx in 0..cells_x {
10886 let (bx, by) = (cx * 16, cy * 16);
10887 let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
10888 for cand in [left, above[cx]] {
10889 if cand != (0, 0) {
10890 let s = sad(bx, by, cand);
10891 if s < best.0 {
10892 best = (s, cand);
10893 }
10894 }
10895 }
10896 for step in [8i32, 4, 2, 1] {
10897 let centre = best.1;
10898 for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
10899 let mv = (centre.0 + dx, centre.1 + dy);
10900 if mv.0.abs() > 32 || mv.1.abs() > 32 {
10901 continue;
10902 }
10903 let s = sad(bx, by, mv);
10904 if s < best.0 {
10905 best = (s, mv);
10906 }
10907 }
10908 }
10909 left = best.1;
10910 above[cx] = best.1;
10911 out.push((best.1, best.0));
10912 }
10913 }
10914 out
10915}
10916
10917/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
10918/// transform: here, the mean absolute deviation of the cell from its own DC.
10919/// It is the denominator every propagated cost is read against, so only its
10920/// SHAPE across the frame matters, not its scale.
10921fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
10922 let (cells_x, cells_y) = (width / 16, height / 16);
10923 let mut out = Vec::with_capacity(cells_x * cells_y);
10924 for cy in 0..cells_y {
10925 for cx in 0..cells_x {
10926 let (bx, by) = (cx * 16, cy * 16);
10927 let mut sum = 0u32;
10928 for r in 0..16 {
10929 sum += frame[(by + r) * width + bx..][..16].iter().map(|&p| u32::from(p)).sum::<u32>();
10930 }
10931 let dc = ((sum + 128) / 256) as u8;
10932 let mut cost = 0u32;
10933 for r in 0..16 {
10934 cost += frame[(by + r) * width + bx..][..16]
10935 .iter()
10936 .map(|&p| u32::from(p.abs_diff(dc)))
10937 .sum::<u32>();
10938 }
10939 out.push(cost);
10940 }
10941 }
10942 out
10943}
10944
10945/// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS
10946/// frame the next one predicts from, per 16x16 cell -- each cell of `next`
10947/// splats its own area, at its winning displacement, onto the (at most four)
10948/// cells of `cur` it lands on. 1.0 is "referenced exactly once".
10949fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
10950 let start = std::time::Instant::now();
10951 let (cells_x, cells_y) = (width / 16, height / 16);
10952 let pass = tpl_coarse_pass(cur, next, width, height);
10953 let mut area = vec![0.0f64; cells_x * cells_y];
10954 for cy in 0..cells_y {
10955 for cx in 0..cells_x {
10956 let (mv, _) = pass[cy * cells_x + cx];
10957 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
10958 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
10959 for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
10960 let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
10961 for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
10962 let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
10963 area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
10964 }
10965 }
10966 }
10967 }
10968 TPL_NANOS.fetch_add(
10969 start.elapsed().as_nanos() as u64,
10970 std::sync::atomic::Ordering::Relaxed,
10971 );
10972 area
10973}
10974
10975/// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda
10976/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
10977/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
10978/// Decreasing in referenced-ness (a block the next frame leans on is coded
10979/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
10980/// total lambda scale is only redistributed, never moved -- a global move is
10981/// the thing lane-av1lambda already measured inert.
10982fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
10983 let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
10984 let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
10985 let mut out = Vec::with_capacity(sb_cols * sb_rows);
10986 for sr in 0..sb_rows {
10987 for sc in 0..sb_cols {
10988 let mut sum = 0.0;
10989 for r in 0..4 {
10990 for c in 0..4 {
10991 sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
10992 }
10993 }
10994 let w_rel = sum / 16.0 / mean;
10995 out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
10996 }
10997 }
10998 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
10999 let mut hist = [0usize; 8];
11000 for w in map {
11001 hist[((w / mean * 2.0) as usize).min(7)] += 1;
11002 }
11003 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
11004 eprintln!(
11005 "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
11006 sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
11007 map.len(),
11008 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
11009 );
11010 }
11011 out
11012}
11013
11014/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
11015/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
11016/// much of the WHOLE lookahead window leans on that cell.
11017///
11018/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
11019/// coarse pass gives a displacement and an inter cost; a cell's own
11020/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
11021/// cell well saves the frames that predict from it -- and it is splatted,
11022/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
11023/// displacement lands on. Walking `f` from the far end of the window back to
11024/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
11025/// area map could not do at all.
11026///
11027/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
11028/// factor over the frame is exactly 1: a cell the window leans on is coded
11029/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
11030/// scale only moves around, never up or down -- a global move is what
11031/// lane-av1lambda already measured inert.
11032/// Returns the per-cell lambda factors AND the per-cell dependence ratio
11033/// `mc_dep / intra` they were derived from -- the second half is what
11034/// [`deltaq_libaom`] needs, since the factor alone has been through a
11035/// mean normalisation the raw ratio cannot be recovered across.
11036fn tpl_lambda_factors(
11037 frames: &[&[u8]],
11038 width: usize,
11039 height: usize,
11040 k: f64,
11041) -> (Vec<f64>, Vec<f64>) {
11042 let start = std::time::Instant::now();
11043 let (cells_x, cells_y) = (width / 16, height / 16);
11044 let cells = cells_x * cells_y;
11045 let levels = frames.len();
11046 let intra: Vec<Vec<u32>> = frames.iter().map(|f| tpl_intra_costs(f, width, height)).collect();
11047 let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
11048 .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
11049 .collect();
11050 let mut mc_dep = vec![vec![0.0f64; cells]; levels];
11051 for f in (1..levels).rev() {
11052 for cy in 0..cells_y {
11053 for cx in 0..cells_x {
11054 let ci = cy * cells_x + cx;
11055 let (mv, inter) = passes[f - 1][ci];
11056 let saved = f64::from(intra[f][ci].saturating_sub(inter));
11057 let propagate = saved + mc_dep[f][ci];
11058 if propagate <= 0.0 {
11059 continue;
11060 }
11061 // The 16x16 window of the PREVIOUS frame this cell predicted
11062 // from, spread over the cells it overlaps.
11063 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
11064 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
11065 for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
11066 let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
11067 for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
11068 let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
11069 mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
11070 }
11071 }
11072 }
11073 }
11074 }
11075 // The tail compression `p`: `mc_dep/intra` is a ratio with a very long
11076 // tail (a nearly flat cell the window leans on has a tiny denominator),
11077 // and at p = 1 that tail slams into the clamp. libaom reads its own
11078 // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P`
11079 // sweeps the exponent, 1 being the raw ratio.
11080 let power = std::env::var("EC_AV1_TPL_P")
11081 .ok()
11082 .and_then(|v| v.parse::<f64>().ok())
11083 .filter(|p| p.is_finite() && *p > 0.0)
11084 .unwrap_or(TPL_POWER);
11085 // lane-av1tpl3, the three shape fixes, each its own knob so the gate can
11086 // read them apart. `SB` and `LOG` are the shipped shape (set the knob to
11087 // `0` to take either back out); `FLOOR` defaults to off.
11088 //
11089 // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the
11090 // frame's own mean intra cost. A cell of flat content has a near-zero
11091 // MAD, so its ratio explodes exactly where coding is cheap.
11092 // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra
11093 // and mc_dep are summed over the 64x64 superblock first -- libaom's
11094 // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not
11095 // per-16x16 numbers), which is also what makes the ratio survive one
11096 // flat cell next to a busy one.
11097 // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through
11098 // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail
11099 // harder than the `p` exponent alone can.
11100 let floor_frac = std::env::var("EC_AV1_TPL_FLOOR")
11101 .ok()
11102 .and_then(|v| v.parse::<f64>().ok())
11103 .filter(|f| f.is_finite() && *f >= 0.0)
11104 .unwrap_or(0.0);
11105 let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0");
11106 let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0");
11107 let intra_mean =
11108 intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64;
11109 let floor = floor_frac * intra_mean;
11110 let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0);
11111 // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by
11112 // every cell under it. The edge groups are partial and summed as they are.
11113 let ratio: Vec<f64> = if sb_agg {
11114 let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4));
11115 let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows];
11116 for cy in 0..cells_y {
11117 for cx in 0..cells_x {
11118 let e = &mut sb[(cy / 4) * sb_cols + cx / 4];
11119 e.0 += mc_dep[0][cy * cells_x + cx];
11120 e.1 += denom(cy * cells_x + cx);
11121 }
11122 }
11123 (0..cells)
11124 .map(|c| {
11125 let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4];
11126 dep / den.max(1.0)
11127 })
11128 .collect()
11129 } else {
11130 (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect()
11131 };
11132 let mut out: Vec<f64> = ratio
11133 .iter()
11134 .map(|&r| {
11135 let r = if log_beta { (1.0 + r).log2() } else { r };
11136 (1.0 + k * r).powf(-power)
11137 })
11138 .collect();
11139 let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
11140 for f in &mut out {
11141 *f = (*f / mean).clamp(0.25, 4.0);
11142 }
11143 TPL_NANOS.fetch_add(
11144 start.elapsed().as_nanos() as u64,
11145 std::sync::atomic::Ordering::Relaxed,
11146 );
11147 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
11148 let mut hist = [0usize; 8];
11149 for &f in &out {
11150 hist[((f * 4.0) as usize).min(7)] += 1;
11151 }
11152 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
11153 let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
11154 eprintln!(
11155 "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
11156 range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
11157 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
11158 );
11159 }
11160 (out, ratio)
11161}
11162
11163/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
11164/// references name, which slot it refreshes, whether it is shown when it is
11165/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
11166/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
11167/// 0/2 alternation, every frame shown, every reference in the past).
11168///
11169/// The sign bias is carried rather than derived here because only the caller
11170/// knows what order hint each slot holds; it is armed onto the tile writer
11171/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
11172/// the writer scans the same stacks the decoder will.
11173#[derive(Debug, Clone, Copy)]
11174pub(crate) struct PyramidFrame {
11175 /// The slot `LAST_FRAME` (and every reference this encoder does not name
11176 /// apart) reads.
11177 pub last_slot: u8,
11178 /// The single slot `refresh_frame_flags` sets.
11179 pub self_slot: u8,
11180 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
11181 /// pyramid, which is what makes `sign_bias`'s last entry true.
11182 pub altref_slot: u8,
11183 /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past
11184 /// picture (the leaf chain alternates its refresh between two slots, so
11185 /// the frame before `LAST` is still intact). `None` leaves
11186 /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder
11187 /// wrote before, and the caller then passes no `last2` picture either.
11188 pub last2_slot: Option<u8>,
11189 /// `show_frame`: false for a hidden frame, output later by a
11190 /// `show_existing_frame` header.
11191 pub show_frame: bool,
11192 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
11193 pub sign_bias: crate::mvstack::SignBiasTable,
11194}
11195
11196/// Encodes one picture as an inter frame predicting from `reference`'s
11197/// reconstruction, which the caller decoded (or, for the frame right after
11198/// the key frame, is the key frame's own reconstruction).
11199pub(crate) fn encode_inter_frame(
11200 picture: &Picture,
11201 reference: &Picture,
11202 base_q_idx: u8,
11203 deadzone: f64,
11204 order_hint: u32,
11205 // The order hint each of the seven `ref_frame_idx` entries names, which a
11206 // decoder reads out of its own reference state -- only spec 5.9.22's
11207 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
11208 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
11209 // callers that follow this crate's own flat slot plan.
11210 order_hints: [u32; 7],
11211 render: (usize, usize),
11212 // The tables this frame's writer starts from: what the previous frame
11213 // stored into the slot this one's `primary_ref_frame` names. `None`
11214 // starts from the defaults, which is right only for the frame straight
11215 // after a key frame.
11216 start_cdfs: Option<&crate::cdf_state::Cdfs>,
11217 // The key frame's own (padded) reconstruction, which every frame of the
11218 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
11219 // with `LAST_FRAME` alone, exactly as before.
11220 golden: Option<&Picture>,
11221 // The frame two back, held in the slot this frame is about to refresh
11222 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
11223 // inter frames of a GOP, where the frame two back IS the key frame.
11224 altref: Option<&Picture>,
11225 // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown
11226 // frame BEFORE `reference` on the leaf chain, offered to the 32x32
11227 // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF`
11228 // take. `None` (every caller but the pyramid leaves) codes the frame
11229 // with the reference set unchanged.
11230 last2: Option<&Picture>,
11231 fctx: &crate::decode::FrameCtx,
11232 // Where this frame sits in the coding-order pyramid; `None` is the flat
11233 // one-shown-frame-per-picture stream this encoder wrote before.
11234 pyramid: Option<PyramidFrame>,
11235 // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
11236 // them), padded like this one -- the lookahead window the per-block
11237 // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
11238 // EMPTY slice codes the frame at one lambda, as before.
11239 lookahead: &[Picture],
11240) -> Result<Encoded> {
11241 picture.check()?;
11242 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
11243 return Err(Error::unsupported(
11244 "AV1 encode",
11245 "an inter frame is coded only for a picture that is a whole number \
11246 of 64x64 superblocks -- the inter tile writer never splits a \
11247 superblock's partition below that",
11248 ));
11249 }
11250 if reference.width != picture.width || reference.height != picture.height {
11251 return Err(Error::unsupported(
11252 "AV1 encode",
11253 "the reference picture must be the same size as the one being coded",
11254 ));
11255 }
11256
11257 // The single slot this crate's inter frames ever predict from or
11258 // refresh (`inter_frame_headers`'s contract): every frame both reads and
11259 // overwrites slot 0, so the frame just coded is always what the next one
11260 // predicts against.
11261 const LAST_SLOT: u8 = 0;
11262 // Slot 0 and slot 2 alternate so the frame two back survives one more
11263 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
11264 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
11265 // in the very slot it will overwrite.
11266 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
11267 let last_slot = pyramid.map_or(
11268 if order_hint <= 1 {
11269 LAST_SLOT
11270 } else if (order_hint - 1) % 2 == 1 {
11271 0
11272 } else {
11273 2
11274 },
11275 |p| p.last_slot,
11276 );
11277 // `render`, not `picture.width`/`picture.height`: `picture` here is
11278 // already padded to a whole number of superblocks (`encode_sequence`'s
11279 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
11280 // every true-edge clamp downstream) must come from the frame's real,
11281 // unpadded size, same as `key_frame_headers_colour` takes `render` and
11282 // not the padded picture in `encode_key_frame_inner`.
11283 let (seq, mut header) = inter_frame_headers_slots(
11284 render.0,
11285 render.1,
11286 base_q_idx,
11287 order_hint,
11288 last_slot,
11289 self_slot,
11290 match pyramid {
11291 Some(p) => p.altref_slot,
11292 None if altref.is_some() => self_slot,
11293 None => GOLDEN_SLOT,
11294 },
11295 )?;
11296 header.render_width = render.0 as u32;
11297 header.render_height = render.1 as u32;
11298 // lane-refs: this frame's motion-compensation kernel, written into the
11299 // header AND armed on the context every prediction reads, in one place so
11300 // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched
11301 // tile decodes to different pixels than the encoder scored).
11302 header.interpolation_filter = frame_interp_filter();
11303 fctx.interp_filter.set(mc::InterpFilterKind::from_header(header.interpolation_filter));
11304 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
11305 // The order hint behind each `ref_frame_idx` entry. The flat path's own
11306 // slot plan (`inter_frame_headers_slots`) is: every reference but
11307 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
11308 // `ALTREF_FRAME`, which reads the frame two back when there is one;
11309 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
11310 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
11311 header.order_hints = order_hints;
11312 // lane-last2: `inter_frame_headers_slots` points every un-named
11313 // reference at `last_slot`; the pyramid's leaf chain retains a second,
11314 // older picture and names it here. The caller's `sign_bias` /
11315 // `order_hints` entry 1 is derived from this same slot, so the stack
11316 // scans and `skipModeAllowed` read what the decoder will.
11317 if let Some(slot) = pyramid.and_then(|p| p.last2_slot) {
11318 header.ref_frame_idx[1] = slot;
11319 }
11320 header.reference_select = reference_select();
11321 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
11322 // per-reference order-hint distance is read by the block SEARCH, which
11323 // runs long before the writer arms these (the distance-scaled search step
11324 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
11325 // never reached the tool).
11326 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
11327 if let Some(p) = pyramid {
11328 header.show_frame = p.show_frame;
11329 header.showable_frame = !p.show_frame;
11330 header.ref_frame_sign_bias = p.sign_bias;
11331 }
11332 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
11333 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
11334 // block inside this frame codes and searches its own `tx_depth`, the same
11335 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
11336 let tx_select = tx_select() && tx_select_inter();
11337 if tx_select {
11338 header.tx_mode = TxMode::Select;
11339 }
11340
11341 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
11342 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
11343 // here (see `encode_key_frame_inner`).
11344 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
11345 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
11346 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
11347 // This frame's own `allow_screen_content_tools`. It can only be set when
11348 // the SEQUENCE offers the bit at all, which is the key frame's decision
11349 // ([`SEQ_SCREEN`]): a frame header that contradicts
11350 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
11351 // encode.
11352 let screen = seq_screen()
11353 && screen_content(&picture_y8, picture.width, true_width, true_height);
11354 header.allow_screen_content_tools = screen;
11355 // lane-txi, as on the key frame: the header bit the writer's own
11356 // `Cdfs` then reads for every luma `tx_type` symbol.
11357 header.reduced_tx_set = !wide_tx_set(screen);
11358 // The search prices coefficients against the tables this frame's writer
11359 // starts from, not against the defaults (lane-av1txbits) -- but only on a
11360 // frame the screen detector said no to (lane-av1price2): armed HERE, after
11361 // `screen` exists, and again on every search/tile worker below.
11362 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
11363 let mut luma = Plane {
11364 source: &picture_y8,
11365 reconstruction: vec![128; picture_y8.len()],
11366 width: picture.width,
11367 height: picture.height,
11368 true_width,
11369 true_height,
11370 tile_x0: 0,
11371 tile_y0: 0,
11372 tile_x1: picture.width,
11373 tile_y1: picture.height,
11374 ctx: CoefCtxMap::default(),
11375 };
11376 let mut chroma = [
11377 Plane {
11378 source: &picture_u8,
11379 reconstruction: vec![128; picture_u8.len()],
11380 width: picture.width / 2,
11381 height: picture.height / 2,
11382 true_width: true_width / 2,
11383 true_height: true_height / 2,
11384 tile_x0: 0,
11385 tile_y0: 0,
11386 tile_x1: picture.width / 2,
11387 tile_y1: picture.height / 2,
11388 ctx: CoefCtxMap::default(),
11389 },
11390 Plane {
11391 source: &picture_v8,
11392 reconstruction: vec![128; picture_v8.len()],
11393 width: picture.width / 2,
11394 height: picture.height / 2,
11395 true_width: true_width / 2,
11396 true_height: true_height / 2,
11397 tile_x0: 0,
11398 tile_y0: 0,
11399 tile_x1: picture.width / 2,
11400 tile_y1: picture.height / 2,
11401 ctx: CoefCtxMap::default(),
11402 },
11403 ];
11404
11405 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
11406 let search = Search {
11407 base_q_idx,
11408 deadzone,
11409 lambda: lambda_scale()
11410 * match pyramid {
11411 Some(p) if !p.show_frame => hidden_lambda_factor(),
11412 _ => 1.0,
11413 }
11414 * step
11415 * step,
11416 modes: &KEY_FRAME_MODES,
11417 top_k: prune_top_k_inter(),
11418 screen,
11419 };
11420 let mode_bits_table = inter_mode_bits();
11421 // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
11422 // this frame the NEXT one predicts from. Off (`None`) without a
11423 // lookahead picture or at strength 0.
11424 let tpl_k = tpl_strength();
11425 let window: Vec<&Picture> = lookahead
11426 .iter()
11427 .take_while(|n| n.width == picture.width && n.height == picture.height)
11428 .collect();
11429 let tpl_sources: Vec<Vec<u8>> =
11430 window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect();
11431 let tpl_cells_x = picture.width / 16;
11432 // `.1` is the propagating map's raw per-cell dependence ratio, which only
11433 // [`deltaq_libaom`] reads; the one-frame area map has no such ratio.
11434 let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> =
11435 (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| {
11436 if tpl_propagating() {
11437 let mut frames: Vec<&[u8]> = vec![&picture_y8];
11438 frames.extend(tpl_sources.iter().map(Vec::as_slice));
11439 let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k);
11440 (f, Some(r))
11441 } else {
11442 // The shipped map is one factor per 64x64; it is spread over that
11443 // superblock's own 16 cells so the application site below (which
11444 // averages the four cells of a 32x32 block) reads exactly the
11445 // superblock factor, whichever map fed it.
11446 let map =
11447 tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height);
11448 let cells_y = picture.height / 16;
11449 let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k);
11450 let f: Vec<f64> = (0..tpl_cells_x * cells_y)
11451 .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4])
11452 .collect();
11453 (f, None)
11454 }
11455 });
11456 let (tpl_factors, tpl_ratio) = match tpl_both {
11457 Some((f, r)) => (Some(f), r),
11458 None => (None, None),
11459 };
11460
11461 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
11462 // coding surface's: `blocks` carries one entry per 32x32 block the tile
11463 // writer will actually visit, same count it checks `blocks.len()`
11464 // against, which is fewer than the padded surface's own block count
11465 // whenever the true size is not a 64x64 multiple.
11466 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
11467 let (cols, rows) = (cols as usize, rows as usize);
11468 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
11469 // lane-deltaq: one absolute qindex per 64x64 superblock, from the same
11470 // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present
11471 // only when the map is, and `delta_q_res` follows straight into the frame
11472 // header (`write_delta_q_params`) and into the tile writer's own plan.
11473 // Not on a screen frame ([`b64_residual`]'s content gate): lane-dq3
11474 // measured the per-superblock quantizer as a win on both films and a
11475 // 0.5 loss vs libaom on the desktop capture, so a frame that set
11476 // `allow_screen_content_tools` codes no delta syntax at all and stays
11477 // byte-identical to the pre-lane encoder.
11478 let deltaq_res: Option<i32> = tpl_factors
11479 .as_ref()
11480 .filter(|_| !screen)
11481 .and(deltaq_res_log2().map(|r| 1i32 << r));
11482 // The same 16-cell mean the superblock's own lambda takes, clamped to the
11483 // map the frame actually has -- read over the factors or over the raw
11484 // dependence ratios, whichever mapping is asking.
11485 let sb_mean = |m: &[f64], sb: usize| {
11486 let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols);
11487 (0..16)
11488 .map(|i| {
11489 let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4);
11490 m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)]
11491 })
11492 .sum::<f64>()
11493 / 16.0
11494 };
11495 // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the
11496 // raw dependence ratio; without it (and always without a ratio map, i.e.
11497 // on the one-frame area map) the shipped derivation stands.
11498 let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio);
11499 let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option<f64>| -> u8 {
11500 match (libaom, tpl_ratio.as_deref(), r_frame) {
11501 (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res),
11502 _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res),
11503 }
11504 };
11505 let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
11506 (Some(f), Some(res)) => {
11507 let libaom = dq_tpl_strength();
11508 Some((0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect())
11509 }
11510 _ => None,
11511 };
11512 // lane-dq census: both mappings on the SAME superblocks, whether or not
11513 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever
11514 // off, and the census then prices the default `res = 4` grid).
11515 if dq_census() {
11516 if let Some(f) = &tpl_factors {
11517 let res = deltaq_res.unwrap_or(4);
11518 let off = |libaom: Option<f64>| -> Vec<i32> {
11519 (0..sb_cols * _sb_rows)
11520 .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
11521 .collect()
11522 };
11523 let strength = dq_tpl_strength();
11524 let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
11525 let coded = match (deltaq_res.is_some(), strength) {
11526 (false, _) => "none".to_string(),
11527 (true, None) => "ours".to_string(),
11528 (true, Some(k)) => format!("libaom k={k}"),
11529 };
11530 eprintln!(
11531 "dq census: base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
11532 sb_cols * _sb_rows,
11533 r_frame.unwrap_or(f64::NAN),
11534 dq_summary(&ours),
11535 dq_summary(&aom),
11536 );
11537 }
11538 }
11539 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
11540 header.delta.q_present = true;
11541 header.delta.q_res = res.trailing_zeros() as u8;
11542 }
11543 if let Some(g) = &sb_q {
11544 let mut levels: Vec<u8> = g.clone();
11545 levels.sort_unstable();
11546 levels.dedup();
11547 DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed);
11548 }
11549 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
11550 // This frame's tile grid, as in `encode_key_frame_inner`.
11551 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
11552 let layout =
11553 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
11554 header.tile_info = tile_info_of(&layout, 1);
11555 let header_tile_info = header.tile_info.clone();
11556 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
11557 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
11558 // once per frame (lane-av1rd2), not once per block, which is a whole
11559 // plane's map per 32x32 block and now per leaf too.
11560 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
11561 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
11562 // availability -- intra edges and the MV stack's scans alike -- already
11563 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
11564 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
11565 // giving each job its own planes and its own `MiGrid` therefore leaves
11566 // every decision, and so every coded bit, exactly where the whole-frame
11567 // loop left it, at any tile count and any thread count.
11568 let (frame_width, frame_height) = (picture.width, picture.height);
11569 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
11570 let [cb, cr] = &mut chroma;
11571 let chroma_out = [
11572 crate::par::Shared::new(&mut cb.reconstruction),
11573 crate::par::Shared::new(&mut cr.reconstruction),
11574 ];
11575 let search_tile = |index: usize,
11576 fctx: &crate::decode::FrameCtx|
11577 -> Result<Vec<(usize, Quadrant)>> {
11578 // Thread-local, and this job may be running on a `search_tiles`
11579 // worker: `ref_distance`'s order-hint distance (the scaled motion
11580 // search step) is read by the SEARCH, so every worker arms it or the
11581 // tile's bits depend on the thread count.
11582 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
11583 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
11584 let rect = layout.rect(index);
11585 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
11586 let mut chroma = [
11587 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
11588 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
11589 ];
11590 clip_planes_to_tile(&mut luma, &mut chroma, rect);
11591 let mut grid = MiGrid::new(mi_cols, mi_rows);
11592 grid.set_sign_bias(sign_bias);
11593 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
11594 // built once per tile job (`obmc_prediction`).
11595 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
11596 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
11597 obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2;
11598 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
11599 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
11600 grid.set_tile_bounds(
11601 rect.mi_row0 as usize,
11602 rect.mi_col0 as usize,
11603 rect.mi_row1 as usize,
11604 rect.mi_col1 as usize,
11605 );
11606 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
11607 for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {
11608 for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {
11609 // lane-b64: the whole superblock as ONE 64x64 block, tried before
11610 // its quadrants are (`search_skip_64`) and compared against the
11611 // four of them below. Only a superblock wholly inside the true
11612 // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the
11613 // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask
11614 // only that the block's half is inside, and the trial is ranked
11615 // over the inside part alone ([`Plane::block_sse`]).
11616 let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK);
11617 let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols
11618 && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows
11619 && x64 + SUPERBLOCK <= luma.true_width
11620 && y64 + SUPERBLOCK <= luma.true_height;
11621 let edge_inside = b64_edge()
11622 && crate::tile::has_half(
11623 sb_c as u32 * crate::tile::SB_MI,
11624 crate::tile::SB_MI,
11625 header.mi_cols,
11626 )
11627 && crate::tile::has_half(
11628 sb_r as u32 * crate::tile::SB_MI,
11629 crate::tile::SB_MI,
11630 header.mi_rows,
11631 );
11632 let sb64_legal = b64_root()
11633 && sb_r * 2 + 1 < rows
11634 && sb_c * 2 + 1 < cols
11635 && (whole_inside || edge_inside);
11636 // One lambda for the whole superblock, the same mean the 32x32
11637 // level takes over its own four tpl cells: the 64-vs-four-32
11638 // comparison below weighs one cost against four, so both sides
11639 // have to be priced at the same lambda.
11640 let sb_search = match &tpl_factors {
11641 // lane-deltaq: with a per-superblock quantizer the lambda
11642 // comes from that quantizer, not from the raw map factor --
11643 // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped.
11644 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),
11645 Some(f) if sb64_legal => {
11646 let mean = (0..16)
11647 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
11648 .sum::<f64>()
11649 / 16.0;
11650 Search { lambda: search.lambda * mean, ..search }
11651 }
11652 _ => search,
11653 };
11654 let mark = blocks.len();
11655 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
11656 let mut sb_cost = 0.0f64;
11657 if sb64_legal {
11658 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
11659 let (mi_row, mi_col) = (sb_r * 16, sb_c * 16);
11660 let stack =
11661 find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows);
11662 // lane-b64b: the `LAST` + extra-reference pairs at this
11663 // superblock's own 16x16-mi window, the same stacks the tile
11664 // writer's `Whole64` arm rebuilds. Empty unless the frame
11665 // codes `reference_select`, which is what gates the syntax.
11666 // `!screen` for the same reason the residual arm is gated
11667 // there ([`b64_residual`]): a desktop capture's superblocks
11668 // are flat runs the skip arm already codes for nothing, and
11669 // MEASURED, compound at the root cost it +33.4/-23.8 ->
11670 // +33.7/-23.6 while both film rows gained (step 1's table).
11671 let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
11672 if header.reference_select && b64_compound() && !screen {
11673 [
11674 (crate::mvstack::GOLDEN_FRAME, golden),
11675 (crate::mvstack::ALTREF_FRAME, altref),
11676 ]
11677 .into_iter()
11678 .filter_map(|(r, pic)| {
11679 pic.map(|p| {
11680 (
11681 r,
11682 p,
11683 crate::mvstack::find_mv_stack_compound(
11684 &grid,
11685 mi_row,
11686 mi_col,
11687 16,
11688 16,
11689 (crate::mvstack::LAST_FRAME, r),
11690 mi_cols,
11691 mi_rows,
11692 grid.sign_bias_table(),
11693 &[(0, 0); 7],
11694 None,
11695 ),
11696 )
11697 })
11698 })
11699 .collect()
11700 } else {
11701 Vec::new()
11702 };
11703 if let Some((cost, block)) = search_skip_64(
11704 &mut luma,
11705 &mut chroma,
11706 (x64, y64),
11707 &sb_search,
11708 b64_residual() && !screen,
11709 reference,
11710 &stack,
11711 &sb_compound,
11712 fctx,
11713 ) {
11714 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
11715 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
11716 let cost = cost
11717 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
11718 sb64 = Some((cost, block, after));
11719 }
11720 }
11721 // A superblock whose 64x64 trial already codes almost nothing per
11722 // pixel is taken outright and its quadrants are never searched --
11723 // the same `split_rd_breakout` shape the 32x32 level uses one
11724 // size up, and where this lever BUYS wall instead of spending it.
11725 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
11726 split_rd_breakout_at(
11727 b64_breakout_threshold(),
11728 *c,
11729 SUPERBLOCK,
11730 sb_search.lambda,
11731 )
11732 });
11733 for quadrant in 0..if early64 { 0 } else { 4 } {
11734 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
11735 // lane-av1tpl2: this 32x32 block's own lambda -- every RD
11736 // decision under it (partition, mode, tx, motion) reads
11737 // `search.lambda`, so scaling the one field here scales all
11738 // of them. 32x32 and not the 16x16 the map is built at
11739 // because the whole-vs-split comparison right below weighs
11740 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
11741 // would make those two numbers incomparable.
11742 let search = match &tpl_factors {
11743 // lane-deltaq: the quantizer is a SUPERBLOCK-level
11744 // symbol, so all four quadrants take their superblock's
11745 // own qindex and the lambda it implies. No granularity is
11746 // lost: the shipped map (`EC_AV1_TPL_SB`) is already one
11747 // factor per superblock, shared by its sixteen cells.
11748 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),
11749 Some(f) => {
11750 let mean = (0..4)
11751 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
11752 .sum::<f64>()
11753 / 4.0;
11754 Search { lambda: search.lambda * mean, ..search }
11755 }
11756 None => search,
11757 };
11758 // Same filter as the tile writer's: a quadrant whose own mi
11759 // origin is not inside the true frame is never coded.
11760 if r32 >= rows || c32 >= cols {
11761 continue;
11762 }
11763 // spec `decode_partition`'s hasRows/hasCols recomputed at this
11764 // 32x32 block's own half (`crate::tile::has_half`), same as
11765 // the key frame search: the true frame edge can fall inside a
11766 // quadrant a superblock-level check already let through, and
11767 // such a quadrant cannot be left whole -- it must split into
11768 // the 16x16 leaves that are actually inside the true frame
11769 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
11770 // arm).
11771 let (has_cols32, has_rows32) = (
11772 crate::tile::has_half(
11773 c32 as u32 * crate::tile::BLOCK_MI,
11774 crate::tile::BLOCK_MI,
11775 header.mi_cols,
11776 ),
11777 crate::tile::has_half(
11778 r32 as u32 * crate::tile::BLOCK_MI,
11779 crate::tile::BLOCK_MI,
11780 header.mi_rows,
11781 ),
11782 );
11783 if has_cols32 && has_rows32 {
11784 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
11785 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
11786 let stack =
11787 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
11788 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
11789 (crate::mvstack::LAST2_FRAME, last2),
11790 (crate::mvstack::GOLDEN_FRAME, golden),
11791 (crate::mvstack::ALTREF_FRAME, altref),
11792 ]
11793 .into_iter()
11794 .filter_map(|(r, pic)| {
11795 pic.map(|p| {
11796 (
11797 r,
11798 p,
11799 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
11800 )
11801 })
11802 })
11803 .collect();
11804 let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
11805 .iter()
11806 .map(|(r, p, st)| (*r, *p, st))
11807 .collect();
11808 // The COMPOUND stack of each `LAST` + extra pair, off the
11809 // same grid (and the same armed sign bias) the tile writer
11810 // rebuilds it from. Empty unless this frame codes
11811 // `reference_select`, which is what gates the syntax.
11812 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
11813 if header.reference_select {
11814 extra_stacks
11815 .iter()
11816 .map(|&(r, p, _)| {
11817 (
11818 r,
11819 p,
11820 crate::mvstack::find_mv_stack_compound(
11821 &grid,
11822 mi_row,
11823 mi_col,
11824 8,
11825 8,
11826 (crate::mvstack::LAST_FRAME, r),
11827 mi_cols,
11828 mi_rows,
11829 grid.sign_bias_table(),
11830 &[(0, 0); 7],
11831 None,
11832 ),
11833 )
11834 })
11835 .collect()
11836 } else {
11837 Vec::new()
11838 };
11839
11840 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
11841 let (block, mut cost_whole) = search_inter_block(
11842 &mut luma,
11843 &mut chroma,
11844 (x, y),
11845 &search,
11846 &mode_bits_table,
11847 reference,
11848 &stack,
11849 &extra,
11850 &compound,
11851 &grid,
11852 (mi_row, mi_col),
11853 (mi_rows, mi_cols),
11854 fctx,
11855 );
11856 cost_whole += search.lambda * partition_bits(BLOCK, false);
11857 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
11858
11859 // What four 16x16 leaves cost instead (spec
11860 // PARTITION_SPLIT at BLOCK_32X32, which
11861 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
11862 // already writes for a straddling quadrant). Each leaf is
11863 // searched against the reconstruction -- and the `mi`
11864 // grid -- the ones before it left, exactly as the writer
11865 // and the decoder will read them.
11866 //
11867 // A block the whole-32 search left skipped (no residual
11868 // at all) is not offered the split: libaom prunes the
11869 // same way at cpu-used 6, and it is where the wall would
11870 // otherwise go on static content.
11871 let leaf_positions: Vec<(usize, usize)> = (0..4)
11872 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
11873 .collect();
11874 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
11875 crate::tile::has_half(
11876 sc as u32 * crate::tile::SUB_MI,
11877 crate::tile::SUB_MI,
11878 header.mi_cols,
11879 ) && crate::tile::has_half(
11880 sr as u32 * crate::tile::SUB_MI,
11881 crate::tile::SUB_MI,
11882 header.mi_rows,
11883 )
11884 });
11885 // The breakout above: a 32x32 block that codes almost
11886 // nothing is not offered the split at all.
11887 let breakout = split_breakout_coeffs();
11888 let split = (!block.skip
11889 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
11890 && (breakout == 0 || block.luma.len() > 4 * breakout)
11891 && leaves_legal
11892 && split_inter_blocks())
11893 .then(|| {
11894 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
11895 let mut cost = search.lambda * partition_bits(BLOCK, true);
11896 let mut leaves = Vec::with_capacity(4);
11897 for &(sr, sc) in &leaf_positions {
11898 let (mi_row, mi_col) = (sr * 4, sc * 4);
11899 let (lx, ly) = (sc * SUB, sr * SUB);
11900 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
11901 let stack = find_mv_stack(
11902 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
11903 );
11904 let cstacks = leaf_compound_stacks(
11905 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
11906 header.reference_select, golden, altref,
11907 );
11908 let (leaf, leaf_cost) = code_square_inter(
11909 &mut luma,
11910 &mut chroma,
11911 (lx, ly),
11912 SUB,
11913 &search,
11914 &mode_bits_table,
11915 reference,
11916 &stack,
11917 &cstacks,
11918 &grid,
11919 (mi_row, mi_col),
11920 (mi_rows, mi_cols),
11921 &obmc_refs,
11922 fctx,
11923 );
11924 let leaf_cost = leaf_cost
11925 + search.lambda * partition_bits(SUB, false);
11926 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
11927
11928 // And what four 8x8 leaves cost instead --
11929 // the same tree one step further down, which
11930 // the writer codes as a real PARTITION_SPLIT
11931 // at BLOCK_16X16 (lane-av1rd2). Same
11932 // skipped-block prune as the level above.
11933 let eight = (!leaf.skip
11934 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
11935 && (breakout == 0 || leaf.luma.len() > breakout)
11936 && split_inter_8())
11937 .then(|| {
11938 restore(
11939 &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base,
11940 );
11941 let mut cost8 = search.lambda
11942 * (partition_bits(SUB, true)
11943 + 4.0 * partition_bits(8, false));
11944 let mut eight = Vec::with_capacity(4);
11945 for i in 0..4 {
11946 let (mr, mc) =
11947 (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
11948 let stack8 = find_mv_stack(
11949 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
11950 );
11951 let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
11952 if header.reference_select && leaf_compound() {
11953 [
11954 (crate::mvstack::GOLDEN_FRAME, golden),
11955 (crate::mvstack::ALTREF_FRAME, altref),
11956 ]
11957 .into_iter()
11958 .filter_map(|(r, pic)| {
11959 pic.map(|p| {
11960 (
11961 r,
11962 p,
11963 crate::mvstack::find_mv_stack_compound(
11964 &grid, mr, mc, 2, 2,
11965 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
11966 grid.sign_bias_table(), &[(0, 0); 7], None,
11967 ),
11968 )
11969 })
11970 })
11971 .collect()
11972 } else {
11973 Vec::new()
11974 };
11975 let (leaf8, cost) = code_square_inter(
11976 &mut luma,
11977 &mut chroma,
11978 (lx + (i % 2) * 8, ly + (i / 2) * 8),
11979 8,
11980 &search,
11981 &mode_bits_table,
11982 reference,
11983 &stack8,
11984 &cstacks8,
11985 &grid,
11986 (mr, mc),
11987 (mi_rows, mi_cols),
11988 &obmc_refs,
11989 fctx,
11990 );
11991 cost8 += cost;
11992 record_mi(&mut grid, mr, mc, 2, leaf8.inter, leaf8.skip);
11993 eight.push(leaf8);
11994 }
11995 (eight, cost8)
11996 });
11997 match eight {
11998 Some((eight, cost8)) if cost8 < leaf_cost => {
11999 partition_hit(3);
12000 cost += cost8;
12001 leaves.push(BlockCoeffs {
12002 eight: Some(eight),
12003 ..BlockCoeffs::default()
12004 });
12005 continue;
12006 }
12007 Some(_) => restore(
12008 &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf,
12009 ),
12010 None => {}
12011 }
12012 partition_hit(2);
12013 cost += leaf_cost;
12014 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter, leaf.skip);
12015 leaves.push(leaf);
12016 }
12017 (leaves, cost)
12018 });
12019 if let Some((leaves, cost)) = split {
12020 if cost < cost_whole {
12021 // The leaves' own `mi` cells are already in the
12022 // grid, and their reconstruction is what the
12023 // planes hold.
12024 partition_hit(1);
12025 sb_cost += cost;
12026 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
12027 continue;
12028 }
12029 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
12030 }
12031 partition_hit(0);
12032 sb_cost += cost_whole;
12033 record_mi(&mut grid, mi_row, mi_col, 8, block.inter, block.skip);
12034 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
12035 } else {
12036 // The sub-positions actually inside the true frame, same
12037 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
12038 let sub_positions: Vec<(usize, usize)> = (0..4)
12039 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
12040 .filter(|&(sr, sc)| {
12041 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
12042 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
12043 })
12044 .collect();
12045 // Each leaf searches intra against its own `NEARESTMV`
12046 // candidate (`code_square_inter`), same real-inter choice
12047 // `search_inter_block` makes for a whole 32x32 block, at
12048 // this leaf's own 4x4-mi mv-stack window -- unless the
12049 // leaf's own half itself straddles the true edge, which
12050 // it codes as two (or one, at a true corner) 8x8 leaves
12051 // (`crate::tile::write_leaf8`'s inter counterpart),
12052 // mirroring the key frame search's straddling-16x16
12053 // handling above (lane-av1inter8).
12054 let mut leaves = Vec::with_capacity(sub_positions.len());
12055 for (sr, sc) in sub_positions {
12056 let (has_cols16, has_rows16) = (
12057 crate::tile::has_half(
12058 sc as u32 * crate::tile::SUB_MI,
12059 crate::tile::SUB_MI,
12060 header.mi_cols,
12061 ),
12062 crate::tile::has_half(
12063 sr as u32 * crate::tile::SUB_MI,
12064 crate::tile::SUB_MI,
12065 header.mi_rows,
12066 ),
12067 );
12068 if has_cols16 && has_rows16 {
12069 let (x, y) = (sc * SUB, sr * SUB);
12070 let (mi_row, mi_col) = (sr * 4, sc * 4);
12071 let stack = find_mv_stack(
12072 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
12073 );
12074 let cstacks = leaf_compound_stacks(
12075 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
12076 header.reference_select, golden, altref,
12077 );
12078 let (block, _) = code_square_inter(
12079 &mut luma,
12080 &mut chroma,
12081 (x, y),
12082 SUB,
12083 &search,
12084 &mode_bits_table,
12085 reference,
12086 &stack,
12087 &cstacks,
12088 &grid,
12089 (mi_row, mi_col),
12090 (mi_rows, mi_cols),
12091 &obmc_refs,
12092 fctx,
12093 );
12094 // One publication point for every coded leaf
12095 // (`record_mi`): this site used to spell the vote
12096 // out with `ref_frame` pinned to LAST and `mv1`
12097 // to (0,0), which is the encoder-grid-drift class
12098 // -- correct only for as long as a leaf can never
12099 // be compound.
12100 record_mi(&mut grid, mi_row, mi_col, 4, block.inter, block.skip);
12101 leaves.push(block);
12102 } else {
12103 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
12104 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
12105 let mut eight = Vec::with_capacity(2);
12106 for i in 0..4 {
12107 let leaf_x = x_sub + (i % 2) * 8;
12108 let leaf_y = y_sub + (i / 2) * 8;
12109 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
12110 continue;
12111 }
12112 let (mi_row, mi_col) =
12113 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
12114 let stack = find_mv_stack(
12115 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
12116 );
12117 let cstacks = leaf_compound_stacks(
12118 &grid, mi_row, mi_col, 2, 2, mi_cols, mi_rows,
12119 header.reference_select, golden, altref,
12120 );
12121 let (leaf, _) = code_square_inter(
12122 &mut luma,
12123 &mut chroma,
12124 (leaf_x, leaf_y),
12125 8,
12126 &search,
12127 &mode_bits_table,
12128 reference,
12129 &stack,
12130 &cstacks,
12131 &grid,
12132 (mi_row, mi_col),
12133 (mi_rows, mi_cols),
12134 &obmc_refs,
12135 fctx,
12136 );
12137 // Same publication point as the 16x16
12138 // straddling leaf above (`record_mi`).
12139 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter, leaf.skip);
12140 eight.push(leaf);
12141 }
12142 leaves.push(BlockCoeffs {
12143 eight: Some(eight),
12144 ..BlockCoeffs::default()
12145 });
12146 }
12147 }
12148 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
12149 }
12150 }
12151 // The 64x64 root against what its four quadrants really cost.
12152 if let Some((cost64, block, after)) = sb64
12153 && (early64
12154 || cost64
12155 < sb_cost
12156 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true))
12157 {
12158 B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12159 if block.inter.is_some_and(|i| i.ref1.is_some()) {
12160 B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12161 }
12162 if !whole_inside {
12163 B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12164 }
12165 blocks.truncate(mark);
12166 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
12167 // Overwrites every 16x16 mi cell the quadrant searches
12168 // published under this superblock, so the next block's stack
12169 // is built off the block that was really coded.
12170 record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter, block.skip);
12171 blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block)));
12172 for q in 1..4 {
12173 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
12174 blocks.push((r32 * cols + c32, Quadrant::Covered));
12175 }
12176 }
12177 }
12178 }
12179 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
12180 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
12181 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
12182 for (&out, tile) in chroma_out.iter().zip(&chroma) {
12183 copy_rect(
12184 out,
12185 &tile.reconstruction,
12186 frame_width / 2,
12187 x0 / 2,
12188 y0 / 2,
12189 x1.div_ceil(2),
12190 y1.div_ceil(2),
12191 );
12192 }
12193 Ok(blocks)
12194 };
12195 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
12196 .into_iter()
12197 .flatten()
12198 {
12199 blocks[at] = quadrant;
12200 }
12201
12202 let modes = blocks
12203 .iter()
12204 .flat_map(Quadrant::blocks)
12205 .map(|b| b.mode)
12206 .collect::<Vec<_>>();
12207 let inter_block_share = blocks
12208 .iter()
12209 .flat_map(Quadrant::blocks)
12210 .filter(|b| b.inter.is_some())
12211 .count() as f64
12212 / modes.len() as f64;
12213 for block in blocks.iter().flat_map(Quadrant::blocks) {
12214 if let Some(info) = block.inter {
12215 let r = (info.ref_frame as usize).min(7);
12216 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
12217 }
12218 }
12219 #[cfg(test)]
12220 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
12221 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
12222 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
12223 // next frame's writer starts from them -- exactly what
12224 // `crate::stream::stored_cdfs_for` hands the decoder.
12225 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
12226 let mut cdfs = start_cdfs
12227 .cloned()
12228 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
12229 // lane-txi: set per frame, never inherited from the snapshot the
12230 // previous frame stored -- the content gate can flip the bit between
12231 // frames (class `per-tile-state-not-reset`).
12232 cdfs.reduced_tx_set = header.reduced_tx_set;
12233 let start_cdfs = CdfSnapshot(cdfs);
12234 let reference_select_bit = header.reference_select;
12235 let switchable_motion_mode = header.is_motion_mode_switchable;
12236 let warped_motion = header.allow_warped_motion;
12237 let order_hint_bits = seq.order_hint_bits;
12238 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
12239 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
12240 // What this frame stores is the LARGEST tile's end-of-tile tables --
12241 // its own header's `context_update_tile_id` (spec 7.20), which
12242 // `tile_info_of` set to exactly that tile.
12243 let store_tile = layout.largest_tile();
12244 let end_cdfs = std::cell::RefCell::new(None);
12245 // As in `encode_key_frame_inner`: every tile starts from this frame's
12246 // own tables, so no tile depends on any other.
12247 let code_tiles = |bits: u8,
12248 sb_cols: usize,
12249 cdef_grid: &[u8],
12250 units: &[Option<crate::restoration::WienerInfo>]|
12251 -> Result<Vec<Vec<u8>>> {
12252 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
12253 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
12254 crate::tile::arm_delta_q(
12255 deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0),
12256 sb_cols,
12257 sb_q.clone().unwrap_or_default(),
12258 base_q_idx,
12259 );
12260 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
12261 crate::tile::arm_sb128(sb128_on());
12262 crate::tile::arm_sign_bias(sign_bias);
12263 // Thread-locals: every tile job arms its own worker.
12264 crate::tile::arm_reference_select(reference_select_bit);
12265 crate::tile::arm_motion_mode(switchable_motion_mode);
12266 crate::tile::arm_warped_motion(warped_motion);
12267 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
12268 crate::tile::arm_screen(screen);
12269 crate::tile::arm_filter_intra(filter_intra_on());
12270 let mut cdfs = start_cdfs.0.clone();
12271 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
12272 // Each tile's own MV grid: a candidate scan never reaches past
12273 // the tile's bounds, so a grid holding only this tile's own
12274 // blocks reads exactly as the decoder's frame-wide one does
12275 // under `MiGrid::set_tile_bounds`.
12276 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
12277 mv_grid.set_sign_bias(sign_bias);
12278 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
12279 mi_cols,
12280 mi_rows,
12281 base_q_idx,
12282 &blocks,
12283 tx_select,
12284 &mut cdfs,
12285 layout.rect(index),
12286 &mut mv_grid,
12287 )?;
12288 Ok((bytes, Some(cdfs)))
12289 })?;
12290 if let Some(cdfs) = stored {
12291 *end_cdfs.borrow_mut() = Some(cdfs);
12292 }
12293 Ok(out)
12294 };
12295 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
12296 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
12297 // this tile against the same single-slot reference this encoder predicted
12298 // from, under each candidate level.
12299 // The reference a DECODER holds is this frame's cropped size, not the
12300 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
12301 // reference whose height is not the header's own `frame_height` (spec
12302 // 7.9's compatible-size rule), and the chained-decode round trips prove
12303 // the two predict identically.
12304 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
12305 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
12306 reference.clone()
12307 } else {
12308 Picture {
12309 width: fw,
12310 height: fh,
12311 y: crop_plane(&reference.y, reference.width, fw, fh),
12312 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
12313 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
12314 }
12315 };
12316 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
12317 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
12318 // blocks may name GOLDEN needs that plane too, cropped the same way.
12319 let trial_golden = golden.map(|g| {
12320 if (g.width, g.height) == (fw, fh) {
12321 g.clone()
12322 } else {
12323 Picture {
12324 width: fw,
12325 height: fh,
12326 y: crop_plane(&g.y, g.width, fw, fh),
12327 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
12328 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
12329 }
12330 }
12331 });
12332 let trial_altref = altref.map(|a| {
12333 if (a.width, a.height) == (fw, fh) {
12334 a.clone()
12335 } else {
12336 Picture {
12337 width: fw,
12338 height: fh,
12339 y: crop_plane(&a.y, a.width, fw, fh),
12340 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
12341 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
12342 }
12343 }
12344 });
12345 let trial_last2 = last2.map(|l| {
12346 if (l.width, l.height) == (fw, fh) {
12347 l.clone()
12348 } else {
12349 Picture {
12350 width: fw,
12351 height: fh,
12352 y: crop_plane(&l.y, l.width, fw, fh),
12353 u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2),
12354 v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2),
12355 }
12356 }
12357 });
12358 let mut refs: [Option<&Picture>; 8] = [None; 8];
12359 refs[1] = Some(&trial_ref);
12360 refs[2] = trial_last2.as_ref();
12361 refs[4] = trial_golden.as_ref();
12362 refs[7] = trial_altref.as_ref();
12363 let refpix = crate::decode::RefPix::ready(refs);
12364 // lane-txrd: the frame's luma error BEFORE the loop filters, i.e. the
12365 // sum the block search believed it was minimising. Against the
12366 // post-filter per-frame PSNR the gate prints, this separates a trial
12367 // whose reconstruction is a lie from a filter stage that undoes the win.
12368 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
12369 let sse: u64 = luma
12370 .reconstruction
12371 .chunks(luma.width)
12372 .take(luma.true_height)
12373 .zip(picture_y8.chunks(luma.width))
12374 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
12375 .map(|(&r, &s)| {
12376 let d = i64::from(r) - i64::from(s);
12377 (d * d) as u64
12378 })
12379 .sum();
12380 eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}");
12381 }
12382 let post = |luma: &Plane<'_>, tag: &str| {
12383 if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
12384 return;
12385 }
12386 let sse: u64 = luma
12387 .reconstruction
12388 .chunks(luma.width)
12389 .take(luma.true_height)
12390 .zip(picture_y8.chunks(luma.width))
12391 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
12392 .map(|(&r, &s)| {
12393 let d = i64::from(r) - i64::from(s);
12394 (d * d) as u64
12395 })
12396 .sum();
12397 eprintln!("{tag} q={base_q_idx} luma sse={sse}");
12398 };
12399 pick_and_apply_filters(
12400 &mut header,
12401 &mut luma,
12402 &mut chroma,
12403 [&picture_y8, &picture_u8, &picture_v8],
12404 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
12405 // this frame's own `tx_select`, so the search runs under inter
12406 // `TxMode::Select` too (it used to skip and leave every inter frame
12407 // unfiltered once Select became the default).
12408 true,
12409 &mut tiles,
12410 search.lambda,
12411 fctx,
12412 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
12413 // are what the NEXT frame writes from, so the winning re-code
12414 // publishes its own into `end_cdfs` -- the first write's are stale
12415 // the moment a second tile is coded.
12416 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
12417 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
12418 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
12419 crate::decode::decode_inter_frame_tiles_lr(
12420 &payloads,
12421 &header_tile_info,
12422 h.mi_cols,
12423 h.mi_rows,
12424 base_q_idx,
12425 h.frame_width,
12426 h.frame_height,
12427 &refpix,
12428 cdef,
12429 lf,
12430 h.allow_high_precision_mv,
12431 h.force_integer_mv,
12432 Some(fctx.interp_filter.get()),
12433 seq.enable_dual_filter,
12434 h.reference_select,
12435 // lane-txi: this frame's own bit, not the hardcoded `true`
12436 // the wrapper used to pass.
12437 h.reduced_tx_set,
12438 tx_select,
12439 lr,
12440 // The trial decode re-reads the tile the writer just wrote,
12441 // so it starts from the same tables the writer did (this
12442 // frame's `start_cdfs`), not from the defaults.
12443 Some(start_cdfs.0.clone()),
12444 sign_bias,
12445 h.allow_screen_content_tools,
12446 switchable_motion_mode,
12447 h.allow_warped_motion,
12448 seq.enable_filter_intra,
12449 // lane-deltaq: this frame's own delta_q/delta_lf params, so
12450 // the trial decode reads the per-superblock `delta_qindex`
12451 // syntax the writer just wrote.
12452 h.delta.clone(),
12453 fctx,
12454 )
12455 },
12456 )?;
12457 post(&luma, "EC_POSTFILTER");
12458 let mut cdfs = end_cdfs
12459 .into_inner()
12460 .unwrap_or_else(|| start_cdfs.0.clone());
12461 cdfs.reset_counts();
12462 let next_cdfs = CdfSnapshot(cdfs);
12463 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
12464 header.tile_info.tile_size_bytes = tile_size_bytes;
12465 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
12466 let mut stream = temporal_delimiter();
12467 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
12468
12469 let [u, v] = chroma;
12470 Ok(Encoded {
12471 stream,
12472 modes,
12473 inter_block_share,
12474 reconstruction: Picture {
12475 width: luma.width,
12476 height: luma.height,
12477 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
12478 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
12479 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
12480 },
12481 tile,
12482 mi_cols: header.mi_cols,
12483 mi_rows: header.mi_rows,
12484 base_q_idx,
12485 tx_select,
12486 switchable_motion_mode,
12487 screen,
12488 start_cdfs,
12489 next_cdfs,
12490 loop_filter: header.loop_filter,
12491 cdef: header.cdef,
12492 loop_restoration: header.loop_restoration,
12493 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
12494 // intra frames only).
12495 allow_intrabc: false,
12496 delta: header.delta.clone(),
12497 })
12498}
12499
12500/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
12501/// frame's temporal unit followed by one inter frame's temporal unit per
12502/// remaining picture, all sharing the key frame's sequence header -- and
12503/// each frame's own [`Encoded`], in coding order.
12504#[derive(Clone, Debug)]
12505pub struct EncodedSequence {
12506 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
12507 /// sequence header and the key frame) followed by each later frame's
12508 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
12509 /// the sequence header the key frame carried).
12510 pub stream: Vec<u8>,
12511 /// One entry per picture, in DISPLAY order — the order a decoder outputs
12512 /// them and the order `pictures` came in. Without a pyramid that is also
12513 /// the coding order; with one the two differ, and `coding_order` is the
12514 /// map between them.
12515 pub frames: Vec<Encoded>,
12516 /// The index into `frames` of each coded frame, in CODING order — what a
12517 /// per-coded-frame census (`take_predicted_bits`) must be zipped against.
12518 /// `0..frames.len()` on the flat path.
12519 pub coding_order: Vec<usize>,
12520}
12521
12522/// Encodes a sequence of pictures as a key frame followed by one inter frame
12523/// per remaining picture, each predicting from the previous frame's own
12524/// decoded reconstruction — never from the source, which is what a decoder
12525/// cannot see. Every picture must be the same even size (any even width and
12526/// height — each is padded to a whole number of 64x64 superblocks
12527/// internally, which is what lets an inter frame's reference always match
12528/// the frame being coded against it), and `pictures` must be non-empty.
12529///
12530/// # Errors
12531/// Returns an error when `pictures` is empty, when any picture besides the
12532/// first is not the same size as the first, or under the same conditions
12533/// [`encode_key_frame`] and the inter frame path do.
12534pub(crate) fn encode_sequence_with_ctx(
12535 pictures: &[Picture],
12536 base_q_idx: u8,
12537 deadzone: f64, fctx: &crate::decode::FrameCtx,
12538) -> Result<EncodedSequence> {
12539 let Some((first, rest)) = pictures.split_first() else {
12540 return Err(Error::unsupported(
12541 "AV1 encode",
12542 "a sequence needs at least one picture",
12543 ));
12544 };
12545 first.check_even()?;
12546 let render = (first.width, first.height);
12547 // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is
12548 // coded as mini-GOPs -- a hidden ALTREF ahead of its display position,
12549 // the leaves that predict backward off it, and a `show_existing_frame`
12550 // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for
12551 // an A/B. Screen content stays flat (the content gate in
12552 // `Av1Encoder::encode_frames`, whose detector this asks first so the
12553 // whole sequence path is decided in one place), and so does a run that
12554 // asks for a quantizer rounding offset the facade does not carry: the
12555 // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone --
12556 // the ablations' -- must keep the flat path rather than be silently
12557 // ignored.
12558 //
12559 // The reordering itself is NOT reimplemented here: it is the facade's
12560 // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]),
12561 // called with this sequence's shape, so the two paths cannot drift.
12562 let pyramid = crate::encoder::Pyramid::from_env()
12563 .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON)
12564 .filter(|_| !picture_is_screen(first));
12565 LAST_SEQ_PYRAMID.with(|c| c.set(pyramid));
12566 if let Some(pyramid) = pyramid {
12567 for picture in rest {
12568 picture.check_even()?;
12569 if (picture.width, picture.height) != render {
12570 return Err(Error::unsupported(
12571 "AV1 encode",
12572 "every picture in a sequence must be the same size as the first",
12573 ));
12574 }
12575 }
12576 return crate::encoder::Av1Encoder::encode_sequence_pyramid(
12577 pictures,
12578 base_q_idx,
12579 pyramid,
12580 armed_tiles(),
12581 );
12582 }
12583 // The key frame and every inter frame after it are coded at the same
12584 // padded size, so the reference each inter frame predicts from -- the
12585 // previous frame's own uncropped reconstruction, at the size a decoder's
12586 // reference buffer actually holds -- always matches the frame being
12587 // coded against it.
12588 let key = encode_key_frame_inner(
12589 &first.padded_to(SUPERBLOCK),
12590 base_q_idx,
12591 deadzone,
12592 &KEY_FRAME_MODES,
12593 split_blocks(),
12594 render,
12595 unspecified_color_config(), fctx,
12596 )?;
12597 let mut stream = key.stream.clone();
12598 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
12599 // key frame refreshes every slot, each inter frame only slot 0), which is
12600 // what `GOLDEN_FRAME` names.
12601 let golden = key.reconstruction.clone();
12602 // The frame two back, once there is one that is not the key frame
12603 // itself (which `GOLDEN_FRAME` already names).
12604 let mut prev2: Option<Picture> = None;
12605 let mut carried = key.next_cdfs.clone();
12606 let mut reference = key.reconstruction.clone();
12607 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
12608 for (i, picture) in rest.iter().enumerate() {
12609 picture.check_even()?;
12610 // lane-av1tpl2: the lookahead window the per-block lambda weighting
12611 // propagates back through -- the next [`tpl_depth`] - 1 pictures'
12612 // sources at this frame's coded (padded) size. The tail of the
12613 // sequence gets a shorter window, and the last frame none at all.
12614 let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
12615 .iter()
12616 .take(tpl_depth() - 1)
12617 .map(|n| n.padded_to(SUPERBLOCK))
12618 .collect();
12619 if (picture.width, picture.height) != render {
12620 return Err(Error::unsupported(
12621 "AV1 encode",
12622 "every picture in a sequence must be the same size as the first",
12623 ));
12624 }
12625 let order_hint = (i + 1) as u32;
12626 let inter = encode_inter_frame(
12627 &picture.padded_to(SUPERBLOCK),
12628 &reference,
12629 base_q_idx,
12630 deadzone,
12631 order_hint,
12632 flat_order_hints(order_hint, 0, prev2.is_some()),
12633 render,
12634 Some(&carried.0),
12635 Some(&golden),
12636 prev2.as_ref(),
12637 None,
12638 fctx,
12639 None,
12640 &lookahead,
12641 )?;
12642 stream.extend_from_slice(&inter.stream);
12643 carried = inter.next_cdfs.clone();
12644 prev2 = Some(std::mem::replace(
12645 &mut reference,
12646 inter.reconstruction.clone(),
12647 ));
12648 frames.push(crop_encoded(&inter, render.0, render.1));
12649 }
12650 Ok(EncodedSequence {
12651 stream,
12652 coding_order: (0..frames.len()).collect(),
12653 frames,
12654 })
12655}
12656
12657#[cfg(test)]
12658mod tests {
12659
12660 /// Every (site, frame type, block side) the census can be called with
12661 /// lands in its own ten-counter bucket, inside the array (class
12662 /// `enumerate-table-domain`: an off-by-one here would silently add two
12663 /// sites' trials together).
12664 #[test]
12665 fn the_split_census_buckets_are_distinct_and_in_bounds() {
12666 let mut seen = std::collections::BTreeSet::new();
12667 for site in 0..2 {
12668 for key in [true, false] {
12669 for side in [8usize, 16, 32, 64] {
12670 let base = super::split_census_base(site, key, side);
12671 assert!(base + 10 <= super::SPLIT_CENSUS.len(), "{site} {key} {side}");
12672 assert!(seen.insert(base), "{site} {key} {side} collides");
12673 }
12674 }
12675 }
12676 assert_eq!(seen.len(), 16);
12677 }
12678
12679 /// An [`crate::mvstack::MvStack`] with every context at zero and no
12680 /// neighbours, for the pricer tests below to fill the one band each of
12681 /// them is about.
12682 fn bare_stack() -> crate::mvstack::MvStack {
12683 crate::mvstack::MvStack {
12684 entries: Default::default(),
12685 nearest_mv: (0, 0),
12686 near_mv: (0, 0),
12687 pred_mv: (0, 0),
12688 new_mv_ctx: 0,
12689 ref_mv_ctx: 0,
12690 zero_mv_ctx: 0,
12691 drl_ctx: Default::default(),
12692 above_refs: (None, None),
12693 left_refs: (None, None),
12694 above_nbr: None,
12695 left_nbr: None,
12696 above_skip: false,
12697 left_skip: false,
12698 }
12699 }
12700
12701 /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
12702 /// `write_compound_ref_frames` codes for a pair, each at that symbol's
12703 /// own neighbour-derived context. Red before lane-ctx, where the pricer
12704 /// spent four constants at CDF row 0 that assumed the pair was
12705 /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
12706 /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
12707 #[test]
12708 fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {
12709 use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
12710 use crate::encode::symbol_bits as b;
12711 use crate::mvstack::{
12712 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
12713 LAST_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx,
12714 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
12715 single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
12716 };
12717 // (pair, unidirectional?, the tree's symbols as (table, p index,
12718 // context selector, value)) -- transcribed from the writer.
12719 // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.
12720 type Sym = (char, usize, usize, usize);
12721 let cases: [((i8, i8), bool, &[Sym]); 7] = [
12722 ((LAST_FRAME, LAST2_FRAME), true, &[('u', 0, 1, 0), ('u', 1, 7, 0)]),
12723 (
12724 (LAST_FRAME, LAST3_FRAME),
12725 true,
12726 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)],
12727 ),
12728 (
12729 (LAST_FRAME, GOLDEN_FRAME),
12730 true,
12731 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)],
12732 ),
12733 ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]),
12734 (
12735 (LAST_FRAME, ALTREF_FRAME),
12736 false,
12737 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)],
12738 ),
12739 (
12740 (LAST_FRAME, BWDREF_FRAME),
12741 false,
12742 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 0)],
12743 ),
12744 (
12745 (LAST_FRAME, ALTREF2_FRAME),
12746 false,
12747 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 1)],
12748 ),
12749 ];
12750 let nbr = |ref0, ref1: Option<i8>| {
12751 Some(NeighbourRef {
12752 is_inter: true,
12753 ref0,
12754 ref1,
12755 uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)),
12756 })
12757 };
12758 // No neighbours (every context zero), then a mixed pair that puts the
12759 // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.
12760 for (above_nbr, left_nbr, above_refs, left_refs) in [
12761 (None, None, (None, None), (None, None)),
12762 (
12763 nbr(LAST_FRAME, None),
12764 nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)),
12765 (Some(LAST_FRAME), None),
12766 (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)),
12767 ),
12768 ] {
12769 let stack = crate::mvstack::MvStack {
12770 above_nbr,
12771 left_nbr,
12772 above_refs,
12773 left_refs,
12774 ..bare_stack()
12775 };
12776 let (a, a1) = above_refs;
12777 let (l, l1) = left_refs;
12778 let ctx_of = |sel: usize| match sel {
12779 1 => single_ref_p1_ctx(a, a1, l, l1),
12780 2 => single_ref_p2_ctx(a, a1, l, l1),
12781 3 => single_ref_p3_ctx(a, a1, l, l1),
12782 4 => single_ref_p4_ctx(a, a1, l, l1),
12783 5 => single_ref_p5_ctx(a, a1, l, l1),
12784 6 => single_ref_p6_ctx(a, a1, l, l1),
12785 _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
12786 };
12787 for (pair, unidir, symbols) in cases {
12788 let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
12789 + b(
12790 &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
12791 usize::from(!unidir),
12792 );
12793 for &(table, p, sel, v) in symbols {
12794 let row = ctx_of(sel);
12795 want += match table {
12796 'u' => b(&UNI_COMP_REF[row][p], v),
12797 'c' => b(&COMP_REF[row][p], v),
12798 _ => b(&COMP_BWDREF[row][p], v),
12799 };
12800 }
12801 let got = super::compound_ref_bits(pair, &stack);
12802 assert!(
12803 (got - want).abs() < 1e-9,
12804 "pair {pair:?} above {above_refs:?} left {left_refs:?}: \
12805 priced {got} bits, writer codes {want}"
12806 );
12807 }
12808 }
12809 }
12810
12811 /// The `skip` and `is_inter` symbols are priced at the SAME context
12812 /// tile.rs codes them with -- `above_skip + left_skip` for the first and
12813 /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
12814 /// on every neighbour configuration whose context is not zero (class
12815 /// pricer-context-zero).
12816 #[test]
12817 fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
12818 use crate::cdf::{INTRA_INTER, SKIP};
12819 use crate::encode::symbol_bits as b;
12820 use crate::mvstack::NeighbourRef;
12821 let nbr = |is_inter| NeighbourRef {
12822 is_inter,
12823 ref0: if is_inter { crate::mvstack::LAST_FRAME } else { 0 },
12824 ref1: None,
12825 uni: false,
12826 };
12827 for (above, left, above_skip, left_skip) in [
12828 (None, None, false, false),
12829 (Some(nbr(true)), Some(nbr(true)), true, false),
12830 (Some(nbr(false)), Some(nbr(false)), true, true),
12831 (Some(nbr(false)), None, false, true),
12832 (None, Some(nbr(true)), true, true),
12833 ] {
12834 let stack = crate::mvstack::MvStack {
12835 above_nbr: above,
12836 left_nbr: left,
12837 above_skip,
12838 left_skip,
12839 ..bare_stack()
12840 };
12841 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
12842 let ii_ctx = crate::tile::intra_inter_ctx(
12843 above.is_some(),
12844 left.is_some(),
12845 above.is_some_and(|n| n.is_inter),
12846 left.is_some_and(|n| n.is_inter),
12847 );
12848 for v in [false, true] {
12849 let (got, want) = (
12850 super::skip_bits_at(&stack, v),
12851 b(&SKIP[skip_ctx], usize::from(v)),
12852 );
12853 assert!(
12854 (got - want).abs() < 1e-9,
12855 "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
12856 );
12857 let (got, want) = (
12858 super::intra_inter_bits_at(&stack, v),
12859 b(&INTRA_INTER[ii_ctx], usize::from(v)),
12860 );
12861 assert!(
12862 (got - want).abs() < 1e-9,
12863 "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
12864 );
12865 }
12866 }
12867 }
12868
12869 /// [`super::single_ref_bits`] pays exactly what tile.rs'
12870 /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD
12871 /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at
12872 /// the context that symbol's own `single_ref_p*_ctx` derives from the
12873 /// block's above/left neighbours. Red before lane-pricer, where every
12874 /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
12875 #[test]
12876 fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
12877 use crate::cdf::SINGLE_REF as SR;
12878 use crate::encode::symbol_bits as b;
12879 use crate::mvstack::{
12880 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
12881 LAST_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
12882 single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
12883 };
12884 let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
12885 above_refs,
12886 left_refs,
12887 above_nbr,
12888 left_nbr,
12889 ..bare_stack()
12890 };
12891 let nbr = |ref0, ref1| {
12892 Some(crate::mvstack::NeighbourRef { is_inter: true, ref0, ref1, uni: false })
12893 };
12894 // (reference, the symbols `write_single_ref` emits as (p index, value))
12895 let cases: [(i8, &[(usize, usize)]); 7] = [
12896 (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),
12897 (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),
12898 (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),
12899 (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),
12900 (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),
12901 (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),
12902 (ALTREF_FRAME, &[(0, 1), (1, 1)]),
12903 ];
12904 // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair
12905 // that puts every p* context on a different row -- the second with a
12906 // COMPOUND left neighbour, which is what takes `reference_mode_ctx`
12907 // off row 0.
12908 for (above_refs, left_refs, above_nbr, left_nbr) in [
12909 ((None, None), (None, None), None, None),
12910 (
12911 (Some(LAST_FRAME), None),
12912 (Some(ALTREF_FRAME), Some(LAST_FRAME)),
12913 nbr(LAST_FRAME, None),
12914 nbr(ALTREF_FRAME, Some(LAST_FRAME)),
12915 ),
12916 ] {
12917 let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr);
12918 let (a, a1) = above_refs;
12919 let (l, l1) = left_refs;
12920 let ctx_of = |p: usize| match p {
12921 0 => single_ref_p1_ctx(a, a1, l, l1),
12922 1 => single_ref_p2_ctx(a, a1, l, l1),
12923 2 => single_ref_p3_ctx(a, a1, l, l1),
12924 3 => single_ref_p4_ctx(a, a1, l, l1),
12925 4 => single_ref_p5_ctx(a, a1, l, l1),
12926 _ => single_ref_p6_ctx(a, a1, l, l1),
12927 };
12928 for (ref_frame, symbols) in cases {
12929 // Plus the `comp_mode = 0` symbol the writer codes ahead of
12930 // the reference syntax on a `reference_select` frame.
12931 let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
12932 if super::reference_select() {
12933 want += b(
12934 &crate::cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(
12935 above_nbr, left_nbr,
12936 )],
12937 0,
12938 );
12939 }
12940 let got = super::single_ref_bits(ref_frame, &stack);
12941 assert!(
12942 (got - want).abs() < 1e-9,
12943 "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \
12944 priced {got} bits, writer codes {want}"
12945 );
12946 }
12947 }
12948 }
12949
12950 /// lane-av1tpl2's propagated map, on the two properties every decision
12951 /// under it rests on: a frame the whole lookahead window repeats exactly
12952 /// (uniform texture) leans on every cell alike, so every factor is 1 and
12953 /// the weighting is a no-op; and where the window really does save bits
12954 /// by predicting -- the textured half of a frame whose other half is
12955 /// flat -- the factor FALLS below 1, i.e. that half is coded more
12956 /// distortion-averse than the half nothing gains from.
12957 /// The distortion metric itself (lane-sse): a block the true frame edge
12958 /// cuts through is scored over its INSIDE part only, so a difference that
12959 /// lives entirely in the padding costs nothing and a block wholly past
12960 /// the edge scores zero. Before this, the search ranked modes,
12961 /// transforms and partition trees on samples the display crop throws
12962 /// away -- which lane-b64b had fixed for the 64x64 root alone.
12963 #[test]
12964 fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
12965 // A 40x40 true frame on a 64x64 padded coding surface.
12966 let source = vec![10u8; 64 * 64];
12967 let plane = fresh_plane(&source, 64, 64, 40, 40);
12968 let mut reconstruction = vec![10u8; 64 * 64];
12969 // Off by 190 at (50, 50) -- past the true edge in both axes.
12970 reconstruction[50 * 64 + 50] = 200;
12971 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 0.0, "padding was scored");
12972 // Off by 10 at (39, 39) -- the last sample the decoder shows.
12973 reconstruction[39 * 64 + 39] = 20;
12974 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 100.0, "inside was not scored");
12975 // A 16x16 block whose every sample is padding.
12976 let block = vec![200u8; 16 * 16];
12977 assert_eq!(plane.block_sse(48, 0, 16, &block), 0.0, "a block past the edge scored");
12978 // A 16x16 block the edge cuts: 8 of its columns are inside.
12979 assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
12980 }
12981
12982 /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
12983 /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the
12984 /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
12985 #[test]
12986 fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
12987 let (base, res) = (162u8, 4i32);
12988 let rf = 2.0;
12989 // A superblock the window leans on more than the frame average is
12990 // coded FINER (lower qindex); a slack one coarser; the average one
12991 // exactly at the base.
12992 assert!(super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base, "leaned-on SB must go finer");
12993 assert!(super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base, "idle SB must go coarser");
12994 assert_eq!(super::deltaq_libaom(base, rf, rf, 1.0, res), base, "the average SB moves 0");
12995 // Every offset is a whole number of steps and inside +-(res * 9 - 1).
12996 let max = ((res * 9 - 1) / res) * res;
12997 for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {
12998 for k in [0.5f64, 1.0, 1.5] {
12999 let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
13000 let d = q - i32::from(base);
13001 assert_eq!(d % res, 0, "r={r} k={k}: offset {d} is not a whole {res}-step");
13002 assert!(d.abs() <= max, "r={r} k={k}: offset {d} past libaom's +-{max}");
13003 }
13004 }
13005 // The clamp is REACHED from both ends, so the bound is a real bound
13006 // and not a formula that never gets there.
13007 assert_eq!(i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base), -max);
13008 assert_eq!(i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base), max);
13009 // A stronger `k` never moves less than a weaker one.
13010 let d = |k: f64| (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs();
13011 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));
13012 // The frame reference is libaom's log-mean: flat in, the same value out.
13013 assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9);
13014 }
13015
13016 #[test]
13017 fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
13018 // Four 64x64 superblocks across: the shipped map forms its ratio per
13019 // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
13020 // only ever produce one ratio -- and one ratio, mean-normalised, is
13021 // the flat map, whatever the content underneath it.
13022 let (w, h) = (256usize, 64usize);
13023 let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
13024 let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
13025 let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
13026 assert_eq!(f.len(), 64, "16x4 cells of 16x16");
13027 for (i, &v) in f.iter().enumerate() {
13028 assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda");
13029 }
13030
13031 // Left half textured, right half constant: the window saves bits
13032 // predicting the left half and nothing at all on the right.
13033 let split: Vec<u8> = (0..w * h)
13034 .map(|i| if i % w < w / 2 { ((i * 37) % 251) as u8 } else { 128 })
13035 .collect();
13036 let frames: Vec<&[u8]> = vec![&split, &split, &split];
13037 let cells_x = w / 16;
13038 for k in [0.25f64, 0.5, 1.0, 2.0] {
13039 let (f, _) = super::tpl_lambda_factors(&frames, w, h, k);
13040 for r in 0..h / 16 {
13041 let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
13042 assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1");
13043 assert!(idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1");
13044 }
13045 }
13046 }
13047
13048 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
13049 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
13050 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
13051 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
13052 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
13053 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
13054 /// only a quarter of the 16x8 table and read the wrong byte for every
13055 /// block row but the first (silently wrong above-right/below-left
13056 /// availability -- wrong pixels, no error).
13057 #[test]
13058 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
13059 for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
13060 let (bw_log2, bh_log2) =
13061 ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize);
13062 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
13063 for (name, table) in
13064 [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)]
13065 {
13066 assert_eq!(
13067 table.len() * 8,
13068 rows * cols,
13069 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
13070 );
13071 let mut seen = vec![0u32; table.len() * 8];
13072 for blk_row in 0..rows {
13073 for blk_col in 0..cols {
13074 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
13075 assert!(
13076 idx < seen.len(),
13077 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
13078 );
13079 seen[idx] += 1;
13080 }
13081 }
13082 assert!(
13083 seen.iter().all(|&n| n == 1),
13084 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
13085 (row stride is not {cols})"
13086 );
13087 }
13088 }
13089 }
13090 use super::*;
13091 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
13092 use std::io::Write;
13093 use std::process::{Command, Stdio};
13094
13095 /// Every rectangular shape this decoder codes, at every position a block
13096 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
13097 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
13098 /// (`reconintra.c`) answer, whose bodies are ported below.
13099 ///
13100 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
13101 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
13102 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
13103 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
13104 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
13105 /// oracle's own arrays, so a re-routed or truncated table fails here even
13106 /// where the two rows happen to agree.
13107 ///
13108 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
13109 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
13110 /// callers handle by predicting each transform unit as its own block.
13111 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
13112 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
13113 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
13114 /// (the horizontal shapes, which those partitions never produce).
13115 #[test]
13116 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
13117 let fctx = &crate::decode::FrameCtx::for_encoder();
13118 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
13119 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
13120 (4, 8, 64, 9280, 64, 550),
13121 (8, 4, 64, 3712, 64, 9630),
13122 (8, 16, 16, 2352, 16, 134),
13123 (16, 8, 16, 960, 16, 2400),
13124 (16, 32, 4, 620, 4, 32),
13125 (32, 16, 4, 32, 4, 184),
13126 (32, 64, 1, 127, 1, 0),
13127 (64, 32, 1, 19, 1, 34),
13128 (4, 16, 32, 5472, 32, 14),
13129 (16, 4, 32, 960, 32, 6464),
13130 (8, 32, 8, 1400, 8, 2),
13131 (32, 8, 8, 32, 8, 1136),
13132 (16, 64, 2, 382, 2, 0),
13133 (64, 16, 2, 4, 2, 84),
13134 ];
13135 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
13136 /// a block whose transform covers it whole (`row_off == col_off == 0`,
13137 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
13138 /// superblock (`sb_mi_size == 16`).
13139 fn libaom_reach(
13140 bw: usize,
13141 bh: usize,
13142 x: usize,
13143 y: usize,
13144 width: usize,
13145 height: usize, _fctx: &crate::decode::FrameCtx,
13146 ) -> (bool, bool) {
13147 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
13148 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
13149 let sb_mi_size = 16usize;
13150 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
13151 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
13152 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
13153 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
13154 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
13155 // has_top_right: top_available && right_available, then row_off == 0.
13156 let top_right = if y == 0 || x + bw >= width {
13157 false
13158 } else if blk_row_in_sb == 0 {
13159 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
13160 // `bw_unit < bw_unit`, false for a whole-block transform.)
13161 true
13162 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
13163 false
13164 } else {
13165 bit(tr_table)
13166 };
13167 // has_bottom_left: bottom_available && left_available, col_off == 0.
13168 let bottom_left = if x == 0 || y + bh >= height {
13169 false
13170 } else if blk_col_in_sb == 0 {
13171 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
13172 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
13173 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
13174 false
13175 } else {
13176 bit(bl_table)
13177 };
13178 (top_right, bottom_left)
13179 }
13180 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
13181 let (tr, bl) = rect_reach_tables(bw, bh);
13182 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
13183 assert_eq!(
13184 (tr.len(), sum(tr), bl.len(), sum(bl)),
13185 (tr_len, tr_sum, bl_len, bl_sum),
13186 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
13187 );
13188 // Two superblocks across and down, so the superblock-relative
13189 // position (and not the frame position) is what decides.
13190 for sb_y in [0usize, 64] {
13191 for sb_x in [0usize, 64] {
13192 for y in (sb_y..sb_y + 64).step_by(bh) {
13193 for x in (sb_x..sb_x + 64).step_by(bw) {
13194 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
13195 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
13196 assert_eq!(
13197 (got.above_right, got.below_left),
13198 want,
13199 "{bw}x{bh} at ({x}, {y})"
13200 );
13201 }
13202 }
13203 }
13204 }
13205 }
13206 }
13207
13208 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
13209 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
13210 /// aomenc gate decodes its stream through ffmpeg and is meaningless
13211 /// without it -- turns it into a hard failure. Without this the require
13212 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
13213 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
13214 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
13215 fn have_ffmpeg() -> bool {
13216 let present = Command::new("ffmpeg")
13217 .arg("-version")
13218 .stdout(Stdio::null())
13219 .stderr(Stdio::null())
13220 .status()
13221 .is_ok_and(|s| s.success());
13222 assert!(
13223 present
13224 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
13225 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
13226 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
13227 );
13228 present
13229 }
13230
13231 /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the
13232 /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).
13233 fn have_encoder(encoder: &str) -> bool {
13234 Command::new("ffmpeg")
13235 .args(["-hide_banner", "-encoders"])
13236 .stderr(Stdio::null())
13237 .output()
13238 .is_ok_and(|o| {
13239 String::from_utf8_lossy(&o.stdout)
13240 .lines()
13241 .any(|l| l.split_whitespace().nth(1) == Some(encoder))
13242 })
13243 }
13244
13245 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
13246 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
13247 let mut child = Command::new("ffmpeg")
13248 .args([
13249 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
13250 ])
13251 .stdin(Stdio::piped())
13252 .stdout(Stdio::piped())
13253 .stderr(Stdio::piped())
13254 .spawn()
13255 .expect("ffmpeg failed to start");
13256 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
13257 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
13258 // fills before the last input byte is written -- which is exactly what
13259 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
13260 // (measured: 45 min, both processes at 0% CPU). A write error here is
13261 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
13262 // below, are the real diagnosis.
13263 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
13264 let payload = stream.to_vec();
13265 let writer = std::thread::spawn(move || {
13266 let _ = stdin.write_all(&payload);
13267 });
13268 let out = child.wait_with_output().expect("ffmpeg failed to run");
13269 writer.join().expect("ffmpeg stdin writer thread");
13270 assert!(
13271 out.status.success(),
13272 "ffmpeg refused the stream: {}",
13273 String::from_utf8_lossy(&out.stderr)
13274 );
13275 let (luma, chroma) = (width * height, width * height / 4);
13276 assert_eq!(
13277 out.stdout.len(),
13278 luma + 2 * chroma,
13279 "expected one 4:2:0 frame"
13280 );
13281 Picture {
13282 width,
13283 height,
13284 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
13285 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
13286 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
13287 }
13288 }
13289
13290 /// A picture with something of everything in it: a gradient, an edge, a
13291 /// ripple and a block of flat colour, none of them aligned to the block
13292 /// grid.
13293 /// The in-loop filters actually FIRE and the stream still decodes to
13294 /// exactly what the encoder kept as its reconstruction
13295 /// (gate-blind-to-feature: a filter search that always answered "off"
13296 /// would leave every other test just as green, and the BD gate that
13297 /// would notice is `#[ignore]`d).
13298 ///
13299 /// Run:
13300 /// cargo test -p ec-av1 --release --lib -- \
13301 /// encode::tests::the_filter_search_picks_real_filters
13302 #[test]
13303 fn the_filter_search_picks_real_filters() {
13304 let _knobs = crate::speed::knob_read();
13305 let fctx = &crate::decode::FrameCtx::for_encoder();
13306 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
13307 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
13308 let fired = encoded
13309 .frames
13310 .iter()
13311 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
13312 .count();
13313 assert!(
13314 fired > 0,
13315 "no frame of this sequence chose any in-loop filtering: {:?}",
13316 encoded
13317 .frames
13318 .iter()
13319 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
13320 .collect::<Vec<_>>()
13321 );
13322 // The reconstruction the encoder predicts from is the FILTERED one,
13323 // and it is what a decoder of the stream produces -- byte for byte,
13324 // frame for frame.
13325 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
13326 assert_eq!(decoded.len(), encoded.frames.len());
13327 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
13328 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
13329 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
13330 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
13331 }
13332 }
13333
13334 fn test_card(width: usize, height: usize) -> Picture {
13335 let mut picture = Picture::grey(width, height);
13336 for y in 0..height {
13337 for x in 0..width {
13338 let gradient = x as f64 * 200.0 / width as f64;
13339 let ripple = 30.0
13340 * (x as f64 * std::f64::consts::PI / 23.0).sin()
13341 * (y as f64 * std::f64::consts::PI / 37.0).cos();
13342 let edge = if x > width * 3 / 7 && y > height / 3 {
13343 40.0
13344 } else {
13345 0.0
13346 };
13347 picture.y[y * width + x] =
13348 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
13349 }
13350 }
13351 for y in 0..height / 2 {
13352 for x in 0..width / 2 {
13353 let i = y * width / 2 + x;
13354 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
13355 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
13356 }
13357 }
13358 picture
13359 }
13360
13361 fn psnr(a: &[u16], b: &[u16]) -> f64 {
13362 let squared: f64 = a
13363 .iter()
13364 .zip(b)
13365 .map(|(&x, &y)| {
13366 let d = f64::from(x) - f64::from(y);
13367 d * d
13368 })
13369 .sum();
13370 if squared == 0.0 {
13371 return f64::INFINITY;
13372 }
13373 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
13374 }
13375
13376 /// lane-i64's witness: a smooth gradient is exactly the picture a whole
13377 /// 64x64 intra block predicts as well as four 32x32 ones, so the key
13378 /// frame's new root fires on most superblocks -- and what BOTH decoders
13379 /// produce is the encoder's own reconstruction, sample for sample.
13380 ///
13381 /// The fire count is the `gate-blind-to-feature` guard: without it every
13382 /// assert below passes on a stream that codes no whole superblock at all.
13383 #[test]
13384 fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
13385 let _knobs = crate::speed::knob_read();
13386 let fctx = &crate::decode::FrameCtx::for_encoder();
13387 // 4 x 3 superblocks, all of them wholly inside the frame.
13388 let (width, height) = (256usize, 192usize);
13389 let mut picture = Picture::grey(width, height);
13390 for y in 0..height {
13391 for x in 0..width {
13392 picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
13393 }
13394 }
13395 for y in 0..height / 2 {
13396 for x in 0..width / 2 {
13397 picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
13398 picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
13399 }
13400 }
13401 let _ = take_i64_root_hits();
13402 let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
13403 let [roots, _offered, _edge] = take_i64_root_hits();
13404 // The counters are process-global, so another test encoding in
13405 // parallel can only ADD to them -- the per-FRAME fact is the mode
13406 // list, which carries one entry per coded block and so exactly 12
13407 // when every superblock was coded as one 64x64 intra block.
13408 assert_eq!(
13409 encoded.modes.len(),
13410 12,
13411 "not every superblock was coded as one 64x64 intra block"
13412 );
13413 assert!(
13414 roots >= 8,
13415 "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
13416 );
13417 eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
13418
13419 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
13420 assert_eq!(ours.len(), 1, "our decoder's frames");
13421 assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
13422 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
13423 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
13424
13425 if !have_ffmpeg() {
13426 eprintln!("SKIP the ffmpeg half: no ffmpeg");
13427 return;
13428 }
13429 let decoded = ffmpeg_decode(&encoded.stream, width, height);
13430 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
13431 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
13432 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
13433 }
13434
13435 /// The claim the whole encoder rests on: what a decoder produces is what
13436 /// the encoder said it would, sample for sample, on every plane.
13437 ///
13438 /// Prediction reads the reconstruction, so a single sample of drift
13439 /// anywhere would spread into every block below and to the right of it —
13440 /// which is why this is an equality and not a tolerance.
13441 #[test]
13442 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
13443 let _knobs = crate::speed::knob_read();
13444 let fctx = &crate::decode::FrameCtx::for_encoder();
13445 if !have_ffmpeg() {
13446 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
13447 return;
13448 }
13449 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48), (248, 152)] {
13450 let picture = test_card(width, height);
13451 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
13452 let decoded = ffmpeg_decode(&encoded.stream, width, height);
13453 assert_eq!(
13454 decoded.y, encoded.reconstruction.y,
13455 "{width}x{height}: luma"
13456 );
13457 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
13458 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
13459 }
13460 // One q index from each of the four coefficient-CDF contexts
13461 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
13462 let (width, height) = (64usize, 64usize);
13463 let picture = test_card(width, height);
13464 let _ = take_tx_depth_hits();
13465 for &q in &[15u8, 45, 100, 200] {
13466 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
13467 let decoded = ffmpeg_decode(&encoded.stream, width, height);
13468 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
13469 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
13470 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
13471 }
13472 // lane-av1tx: the exactness above is only a claim about SPLIT
13473 // transforms if some block actually split one (`gate-blind-to-feature`
13474 // -- with `tx_depth` stuck at 0 every assert here passes on the
13475 // pre-lane stream). The test card's edges split at these four
13476 // quantizers; the counter is per-process (another test encoding in
13477 // parallel can only ADD to it, so this can be masked, never falsely
13478 // failed), so it is read once for the whole q ladder.
13479 let depths = take_tx_depth_hits();
13480 assert!(
13481 depths[1] + depths[2] > 0,
13482 "no block split its transform: depths {depths:?}"
13483 );
13484 }
13485
13486 /// A synthetic screen-content picture -- a few flat colours in a grid of
13487 /// boxes with hard edges and text-like bars, the shape a desktop capture
13488 /// has -- so the palette path is exercised on content it is for.
13489 #[cfg(test)]
13490 fn screen_card(width: usize, height: usize) -> Picture {
13491 const INK: [u16; 4] = [16, 90, 180, 235];
13492 let mut picture = Picture::grey(width, height);
13493 for y in 0..height {
13494 for x in 0..width {
13495 let cell = (x / 24 + y / 24) % 2;
13496 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
13497 picture.y[y * width + x] = INK[cell * 2 + bar];
13498 }
13499 }
13500 // Four chroma colours, not two: a two-colour chroma block only ever
13501 // codes a `PaletteSizeUV` of 2, which leaves
13502 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
13503 // deltas and the neighbour cache flags, exercised only when
13504 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
13505 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
13506 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
13507 for y in 0..height / 2 {
13508 for x in 0..width / 2 {
13509 let cell = (x / 12 + 2 * (y / 12)) % 4;
13510 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
13511 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
13512 }
13513 }
13514 picture
13515 }
13516
13517 /// The lane's own end-to-end check: on screen content the detector fires,
13518 /// blocks really take a palette (fire count, class
13519 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
13520 /// symbol this lane writes -- reconstructs exactly what the encoder did.
13521 /// The film-shaped `test_card` must NOT trip the detector, which is what
13522 /// keeps every non-screen stream byte-identical.
13523 #[test]
13524 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
13525 let _knobs = crate::speed::knob_read();
13526 let fctx = &crate::decode::FrameCtx::for_encoder();
13527 let (width, height) = (192usize, 96usize);
13528 let _ = crate::tile::take_palette_hits();
13529 let picture = screen_card(width, height);
13530 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
13531 assert!(
13532 encoded.screen,
13533 "the detector did not fire on screen content -- no palette syntax was coded at all"
13534 );
13535 let hits = crate::tile::take_palette_hits();
13536 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
13537 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
13538 // The chroma half is a claim about the plane-1 syntax only if some
13539 // block really took a chroma palette (`gate-blind-to-feature`): every
13540 // exactness assert below passes on a stream that codes
13541 // `palette_uv_mode == 0` everywhere.
13542 let uv_hits = crate::tile::take_palette_uv_hits();
13543 assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
13544 let uv_cached = crate::tile::take_palette_uv_cache_hits();
13545 eprintln!(
13546 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
13547 uv_hits[0],
13548 &uv_hits[2..]
13549 );
13550 assert!(
13551 uv_cached > 0,
13552 "no chroma base colour came out of the neighbour cache -- \
13553 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
13554 );
13555 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
13556 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
13557 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
13558 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
13559 if !have_ffmpeg() {
13560 eprintln!("SKIP the ffmpeg half: no ffmpeg");
13561 return;
13562 }
13563 let decoded = ffmpeg_decode(&encoded.stream, width, height);
13564 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
13565 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
13566 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
13567 // A whole GOP: the inter frames' own intra blocks carry the palette
13568 // syntax too (the three intra arms of the inter writers), which only
13569 // ffmpeg reading the frames back can prove.
13570 let moved: Vec<Picture> = (0..4)
13571 .map(|f| {
13572 let base = screen_card(width, height);
13573 let mut out = Picture::grey(width, height);
13574 for y in 0..height {
13575 for x in 0..width {
13576 let sx = (x + f * 7) % width;
13577 out.y[y * width + x] = base.y[y * width + sx];
13578 }
13579 }
13580 for y in 0..height / 2 {
13581 for x in 0..width / 2 {
13582 let sx = (x + f * 3) % (width / 2);
13583 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
13584 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
13585 }
13586 }
13587 out
13588 })
13589 .collect();
13590 let _ = crate::tile::take_palette_hits();
13591 let _ = crate::tile::take_palette_uv_hits();
13592 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
13593 let gop_hits = crate::tile::take_palette_hits();
13594 let gop_uv_hits = crate::tile::take_palette_uv_hits();
13595 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
13596 eprintln!(
13597 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
13598 {} chroma palette blocks",
13599 inter_screen, gop_hits[0], gop_uv_hits[0]
13600 );
13601 assert!(
13602 gop_uv_hits[0] > 0,
13603 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
13604 );
13605 assert!(
13606 inter_screen > 0,
13607 "no inter frame set allow_screen_content_tools"
13608 );
13609 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
13610 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
13611 assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
13612 }
13613 if have_ffmpeg() {
13614 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
13615 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
13616 assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
13617 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
13618 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
13619 }
13620 }
13621
13622 // The other half of the keep rule: film-shaped content leaves the
13623 // detector (and so the whole sequence header) alone.
13624 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
13625 assert!(!film.screen, "the detector fired on the film-shaped test card");
13626 }
13627
13628 /// The lane's keep-rule measurement: the gate's own screen capture, one
13629 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
13630 /// Setting the bit forces deblocking, CDEF and loop restoration off for
13631 /// that frame, so the table is exactly the filter loss against the bytes
13632 /// the copied blocks save.
13633 #[test]
13634 #[ignore = "needs the real-library manifest and ffmpeg"]
13635 fn probe_intrabc_key_frame() {
13636 let _knobs = crate::speed::knob_write();
13637 let fctx = &crate::decode::FrameCtx::for_encoder();
13638 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
13639 .join("../../fixtures");
13640 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
13641 eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest");
13642 return;
13643 };
13644 let Some(clip) = manifest
13645 .lines()
13646 .skip(1)
13647 .filter_map(|l| l.split('\t').next())
13648 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
13649 else {
13650 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
13651 return;
13652 };
13653 let (width, height) = (1280usize, 768usize);
13654 let picture = clip_frame(clip, "0", width, height);
13655 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
13656 for q in [5u8, 20, 35, 45] {
13657 for on in [false, true] {
13658 force_intrabc(Some(on));
13659 let _ = crate::tile::take_intrabc_hits();
13660 let _ = take_intrabc_search();
13661 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
13662 let hits = crate::tile::take_intrabc_hits();
13663 let search = take_intrabc_search();
13664 eprintln!(
13665 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
13666 if encoded.allow_intrabc { "on" } else { "off" },
13667 encoded.stream.len(),
13668 psnr_all(&encoded.reconstruction, &picture),
13669 hits[0],
13670 &hits[1..],
13671 search[0], search[1], search[2],
13672 );
13673 }
13674 }
13675 force_intrabc(None);
13676 }
13677
13678 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
13679 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
13680 /// take a block vector (fire count + DV histogram, class
13681 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
13682 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
13683 /// exactly what the encoder did.
13684 #[test]
13685 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
13686 let _knobs = crate::speed::knob_write();
13687 let fctx = &crate::decode::FrameCtx::for_encoder();
13688 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
13689 // superblocks of 64) and tall enough for a source superblock row
13690 // above the blocks that copy from it.
13691 let (width, height) = (512usize, 256usize);
13692 let picture = screen_card(width, height);
13693 let _ = crate::tile::take_intrabc_hits();
13694 // The default is OFF (it measured worse on the real screen capture --
13695 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
13696 // the arm on for its own encode and puts it back straight after.
13697 force_intrabc(Some(true));
13698 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
13699 force_intrabc(None);
13700 assert!(
13701 encoded.allow_intrabc,
13702 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
13703 intrabc_source_share() * 100.0
13704 );
13705 let hits = crate::tile::take_intrabc_hits();
13706 eprintln!(
13707 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
13708 hits[0],
13709 &hits[1..],
13710 intrabc_source_share() * 100.0
13711 );
13712 let search = take_intrabc_search();
13713 eprintln!(
13714 "intrabc searches {} found-valid {} won-RD {}",
13715 search[0], search[1], search[2]
13716 );
13717 assert!(
13718 hits[0] > 0,
13719 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
13720 );
13721 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
13722 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
13723 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
13724 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
13725 if !have_ffmpeg() {
13726 eprintln!("SKIP the ffmpeg half: no ffmpeg");
13727 return;
13728 }
13729 let decoded = ffmpeg_decode(&encoded.stream, width, height);
13730 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
13731 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
13732 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
13733 }
13734
13735 /// The minimal repro that isolated the inter-residual desync: a key frame
13736 /// followed by one inter frame whose single superblock carries one
13737 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
13738 /// coefficient, its three sibling blocks all `skip: true`. Before the
13739 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
13740 /// found when processing input") even though every symbol either block
13741 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
13742 /// same coefficient syntax decodes clean on every intra key-frame gate).
13743 #[test]
13744 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
13745 let _knobs = crate::speed::knob_write();
13746 let fctx = &crate::decode::FrameCtx::for_encoder();
13747 if !have_ffmpeg() {
13748 eprintln!(
13749 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
13750 );
13751 return;
13752 }
13753 let (width, height) = (64usize, 64usize);
13754 let picture = Picture::grey(width, height);
13755 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
13756
13757 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
13758 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
13759
13760 let residual_block = BlockCoeffs {
13761 luma_tx_types: Vec::new(),
13762 angle_delta_y: 0,
13763 cfl_alphas: None,
13764 filter_intra: None,
13765 luma: vec![Coeff {
13766 row: 0,
13767 col: 0,
13768 level: 4,
13769 }],
13770 u: Vec::new(),
13771 v: Vec::new(),
13772 mode: 0,
13773 uv_mode: 0,
13774 skip: false,
13775 eight: None,
13776 dv: None,
13777 palette: None,
13778 palette_uv: None,
13779 tx_depth: 0,
13780 inter: Some(InterInfo {
13781 ref1: None,
13782 mv1: (0, 0),
13783 ref_frame: crate::mvstack::LAST_FRAME,
13784 mode: InterMode::NearestMv,
13785 mv: (0, 0),
13786 ref_mv_idx: 0,
13787 }),
13788 motion_mode: 0,
13789 };
13790 let skipped_block = BlockCoeffs {
13791 skip: true,
13792 inter: Some(InterInfo {
13793 ref1: None,
13794 mv1: (0, 0),
13795 ref_frame: crate::mvstack::LAST_FRAME,
13796 mode: InterMode::NearestMv,
13797 mv: (0, 0),
13798 ref_mv_idx: 0,
13799 }),
13800 ..BlockCoeffs::default()
13801 };
13802 let blocks = vec![
13803 Quadrant::Whole(residual_block),
13804 Quadrant::Whole(skipped_block.clone()),
13805 Quadrant::Whole(skipped_block.clone()),
13806 Quadrant::Whole(skipped_block),
13807 ];
13808 // lane-av1obmc: the header this tile is decoded under carries
13809 // `is_motion_mode_switchable`, so the writer must be armed with it
13810 // too or the decoder reads a `motion_mode` symbol nobody wrote.
13811 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
13812 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
13813 let tile =
13814 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
13815 .unwrap();
13816
13817 // `key.stream` is already a temporal delimiter, the sequence header
13818 // and the key frame's own OBU (`encode_key_frame` built it from the
13819 // same `key_frame_headers(width, height, 100)` this test calls), so
13820 // the inter frame's OBU is appended straight onto it rather than
13821 // re-deriving the key frame's tile bytes.
13822 let mut stream = key.stream.clone();
13823 stream.extend_from_slice(&temporal_delimiter());
13824 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
13825
13826 ffmpeg_decode_sequence(&stream, width, height, 2);
13827 }
13828
13829 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
13830 /// frame size an AV1 decoder allocates, not necessarily the render size
13831 /// (see [`a_frame_round_trips_at_its_own_size`]).
13832 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
13833 // Distinct per call, not per process: the test binary runs callers on
13834 // parallel threads, and a shared name lets one test's cleanup delete
13835 // the stream another test's ffprobe is still reading.
13836 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
13837 let path = std::env::temp_dir().join(format!(
13838 "ec-av1-probe-{}-{}.obu",
13839 std::process::id(),
13840 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
13841 ));
13842 let _ = std::fs::remove_file(&path);
13843 std::fs::write(&path, stream).expect("writing the probe stream");
13844 let out = Command::new("ffprobe")
13845 .args([
13846 "-v",
13847 "error",
13848 "-f",
13849 "obu",
13850 "-select_streams",
13851 "v:0",
13852 "-show_entries",
13853 "stream=width,height",
13854 "-of",
13855 "csv=p=0",
13856 ])
13857 .arg(&path)
13858 .output()
13859 .expect("ffprobe failed to run");
13860 let _ = std::fs::remove_file(&path);
13861 assert!(
13862 out.status.success(),
13863 "ffprobe refused the stream: {}",
13864 String::from_utf8_lossy(&out.stderr)
13865 );
13866 let text = String::from_utf8_lossy(&out.stdout);
13867 let mut fields = text.trim().split(',');
13868 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
13869 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
13870 (width, height)
13871 }
13872
13873 /// lane-av1cap: the final filter replay against the capture decode it
13874 /// replaced, at the block-padded and straddling sizes the whole-frame
13875 /// tests cover -- `set_verify_final_replay` makes
13876 /// [`pick_and_apply_filters`] run both on every frame and assert, per
13877 /// frame, that the spliced picture and the two filter stages the
13878 /// restoration search reads are bit-identical over the frame's own crop.
13879 #[test]
13880 fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() {
13881 let _knobs = crate::speed::knob_write();
13882 let fctx = &crate::decode::FrameCtx::for_encoder();
13883 crate::decode::set_verify_final_replay(true);
13884 for &(width, height) in
13885 &[(64usize, 56usize), (216, 96), (192, 120), (640, 352), (1280, 720)]
13886 {
13887 eprintln!("--- {width}x{height}");
13888 let picture = test_card(width, height);
13889 let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
13890 }
13891 crate::decode::set_verify_final_replay(false);
13892 }
13893
13894 /// A key frame at an arbitrary even size round-trips through ffmpeg over
13895 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
13896 /// picture's own size, and what ffmpeg decodes over that same top-left
13897 /// region equals it sample for sample.
13898 ///
13899 /// This does not check that `ffprobe` reports the picture's own size,
13900 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
13901 /// (block-padded) frame size, the same one libaom itself would code for
13902 /// a non-block-aligned picture. `render_width`/`render_height` (which
13903 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
13904 /// decoder is required to crop pixels by, and ffmpeg's does not --
13905 /// checked empirically against ffprobe here and against a real libaom
13906 /// encode separately. So the coded size, not the render size, is what
13907 /// `ffprobe` is asserted to report below.
13908 #[test]
13909 fn a_frame_round_trips_at_its_own_size() {
13910 let _knobs = crate::speed::knob_read();
13911 let fctx = &crate::decode::FrameCtx::for_encoder();
13912 if !have_ffmpeg() {
13913 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
13914 return;
13915 }
13916 // 854x480 is covered separately by
13917 // `an_854x480_picture_round_trips_through_its_padding`, which its own
13918 // doc comment explains was worth keeping as its own test.
13919 for &(width, height) in &[
13920 (1920usize, 1080usize),
13921 (640, 352),
13922 (1280, 720),
13923 (64, 56),
13924 (854, 480),
13925 (216, 96),
13926 (192, 120),
13927 ] {
13928 let picture = test_card(width, height);
13929 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
13930 assert_eq!(
13931 (encoded.reconstruction.width, encoded.reconstruction.height),
13932 (width, height),
13933 "{width}x{height}: reconstruction is cropped to the picture's own size"
13934 );
13935 assert_eq!(
13936 ffprobe_size(&encoded.stream),
13937 (width as u32, height as u32),
13938 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
13939 );
13940 let decoded = ffmpeg_decode(&encoded.stream, width, height);
13941 assert_eq!(
13942 decoded.y, encoded.reconstruction.y,
13943 "{width}x{height}: luma"
13944 );
13945 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
13946 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
13947 }
13948 }
13949
13950 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
13951 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
13952 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
13953 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
13954 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
13955 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
13956 /// col`) -- different bits of an 8-byte table, one true, one false. The
13957 /// stride libaom indexes by is fixed at its compile-time maximum
13958 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
13959 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
13960 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
13961 /// row/col position within the (correctly 64-relative) superblock stayed
13962 /// right, only the table's own row stride was wrong. Fixed in
13963 /// `Reach::table_stride`; not an arithmetic-coder desync (an
13964 /// EC_RNG-per-symbol trace against the same debug decoder found the
13965 /// bitstream byte-for-byte identical to libaom's across all 51188
13966 /// symbols of this frame before this bug was found).
13967 ///
13968 /// Since the frame header started writing the true (unpadded) display
13969 /// size into `frame_width`/`frame_height` rather than the padded coded
13970 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
13971 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
13972 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
13973 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
13974 /// the header's own size before output).
13975 #[test]
13976 fn an_854x480_picture_round_trips_through_its_padding() {
13977 let _knobs = crate::speed::knob_read();
13978 let fctx = &crate::decode::FrameCtx::for_encoder();
13979 if !have_ffmpeg() {
13980 return;
13981 }
13982 let (width, height) = (854usize, 480usize);
13983 let picture = test_card(width, height);
13984 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
13985 let decoded = ffmpeg_decode(&encoded.stream, width, height);
13986 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
13987 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
13988 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
13989 }
13990
13991 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
13992 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
13993 /// superblock, both partition tables:
13994 ///
13995 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
13996 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
13997 /// wiring the TU sites onto it changes no existing stream;
13998 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
13999 /// NULL in libaom because that lookup never happens, and reading a
14000 /// 4x4 row out of the three-row vert tables is what crashed a real
14001 /// `--enable-tx-size-search=1` stream (r2);
14002 /// 3. and it must be the BLOCK's vert answer where the two tables
14003 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
14004 /// row 1, column 0 reads its above-right samples from the 8x8 to its
14005 /// upper right, which a vertical AB partition codes AFTER it
14006 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
14007 #[test]
14008 fn of_tu_follows_the_block_row_including_under_vert_ab() {
14009 let fctx = &crate::decode::FrameCtx::for_encoder();
14010 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
14011 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
14012 // above-right answer is the BLOCK's, which is the whole reason a unit
14013 // asks the block instead of looking itself up (the
14014 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
14015 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
14016 assert_eq!(
14017 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
14018 plain.above_right,
14019 "ordinary table: the top-right TX4 unit takes the block's row"
14020 );
14021 let guard = Reach::vert_ab_partition();
14022 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
14023 assert_eq!(
14024 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
14025 vert.above_right,
14026 "vert AB: the unit follows the vert row the block just picked"
14027 );
14028 assert_ne!(
14029 plain.above_right, vert.above_right,
14030 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
14031 );
14032 drop(guard);
14033 }
14034
14035 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
14036 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
14037 /// reconintra.c`), for every 16x16 and 32x32 block position across three
14038 /// superblocks square -- interior and every superblock edge (top row,
14039 /// left column, right column, bottom row) both sizes reach. Written to
14040 /// catch the class the `table_stride` bug was: an index stride silently
14041 /// wrong for one block size while looking plausible for the other.
14042 #[test]
14043 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
14044 let fctx = &crate::decode::FrameCtx::for_encoder();
14045 // Transcribed from has_top_right/has_bottom_left's row_off==0,
14046 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
14047 // 128px reference grid) pinned as libaom pins it, independent of the
14048 // 64px superblock this crate actually codes.
14049 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
14050 if y == 0 || x + side >= width {
14051 return false;
14052 }
14053 let (row, col, per_side) = (
14054 (y % SUPERBLOCK) / side,
14055 (x % SUPERBLOCK) / side,
14056 SUPERBLOCK / side,
14057 );
14058 if row == 0 {
14059 return true;
14060 }
14061 if col + 1 == per_side {
14062 return false;
14063 }
14064 let stride = 128 / side;
14065 let index = row * stride + col;
14066 let table = if side == BLOCK {
14067 [95u8, 87].to_vec()
14068 } else {
14069 vec![255, 85, 119, 85, 127, 85, 119, 85]
14070 };
14071 (table[index / 8] >> (index % 8)) & 1 != 0
14072 }
14073
14074 fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool {
14075 if x == 0 || y + side >= height {
14076 return false;
14077 }
14078 let (row, col, per_side) = (
14079 (y % SUPERBLOCK) / side,
14080 (x % SUPERBLOCK) / side,
14081 SUPERBLOCK / side,
14082 );
14083 if col == 0 {
14084 return row * side + side < SUPERBLOCK;
14085 }
14086 if row + 1 == per_side {
14087 return false;
14088 }
14089 let stride = 128 / side;
14090 let index = row * stride + col;
14091 let table = if side == BLOCK {
14092 [4u8, 4].to_vec()
14093 } else {
14094 vec![84, 16, 84, 0, 84, 16, 84, 0]
14095 };
14096 (table[index / 8] >> (index % 8)) & 1 != 0
14097 }
14098
14099 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
14100 for side in [16usize, BLOCK] {
14101 for y in (0..height).step_by(side) {
14102 for x in (0..width).step_by(side) {
14103 let reach = Reach::of(side, x, y, width, height, fctx);
14104 assert_eq!(
14105 reach.above_right,
14106 libaom_top_right(side, x, y, width, height),
14107 "side={side} x={x} y={y}: above_right"
14108 );
14109 assert_eq!(
14110 reach.below_left,
14111 libaom_bottom_left(side, x, y, height, fctx),
14112 "side={side} x={x} y={y}: below_left"
14113 );
14114 }
14115 }
14116 }
14117 }
14118
14119 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
14120 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
14121 /// column inside the superblock) may read the below-left samples the
14122 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
14123 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
14124 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
14125 /// stream that partitions that small first hits the still-refused
14126 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
14127 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
14128 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
14129 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
14130 /// pixels -- lane-palette2 r12: the square multi-TU path used the
14131 /// standalone-block tables instead of this rule and granted a 16x16
14132 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
14133 #[test]
14134 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
14135 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
14136 // *_count_unit = tx size / 4.
14137 fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
14138 let (plane_bw_unit, count) = (bw / 4, tx / 4);
14139 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
14140 let _ = bh;
14141 if row_off_u > 0 {
14142 col_off_u + count < plane_bw_unit
14143 } else if col_off_u + count < plane_bw_unit {
14144 true
14145 } else {
14146 blk
14147 }
14148 }
14149 fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
14150 let (plane_bh_unit, count) = (bh / 4, tx / 4);
14151 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
14152 let _ = bw;
14153 if col_off_u > 0 {
14154 false
14155 } else if row_off_u + count < plane_bh_unit {
14156 true
14157 } else {
14158 blk
14159 }
14160 }
14161 for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
14162 for &tx in &[4usize, 8, 16, 32] {
14163 if tx > bw.min(bh) {
14164 continue;
14165 }
14166 for row_off in (0..bh).step_by(tx) {
14167 for col_off in (0..bw).step_by(tx) {
14168 for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] {
14169 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
14170 assert_eq!(
14171 got.above_right,
14172 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
14173 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
14174 );
14175 assert_eq!(
14176 got.below_left,
14177 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
14178 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
14179 );
14180 }
14181 }
14182 }
14183 }
14184 }
14185 }
14186
14187 #[test]
14188 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
14189 let fctx = &crate::decode::FrameCtx::for_encoder();
14190 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
14191 // Interior superblock, so neither the frame edge nor the col == 0 /
14192 // last-row early returns answer instead of the table.
14193 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
14194 let mut flipped = 0;
14195 for row in 0..8 {
14196 for col in 1..8 {
14197 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
14198 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
14199 let vert = {
14200 let _guard = Reach::vert_ab_partition();
14201 Reach::of(8, x, y, width, height, fctx).below_left
14202 };
14203 // The TR square of a VERT_A/_B sits at an even row, odd
14204 // column; every other slot must be untouched by the guard.
14205 if row % 2 == 0 && col % 2 == 1 {
14206 assert!(!raster, "raster below_left at row={row} col={col}");
14207 assert!(vert, "vert below_left at row={row} col={col}");
14208 flipped += 1;
14209 } else {
14210 assert_eq!(raster, vert, "guard moved row={row} col={col}");
14211 }
14212 }
14213 }
14214 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
14215 // The guard is scoped: it must not leak past its own block.
14216 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
14217 }
14218
14219 /// An odd width or height is refused by name, not by however the padder
14220 /// or the block coder would happen to fail on it.
14221 #[test]
14222 fn odd_dimensions_are_refused() {
14223 let _knobs = crate::speed::knob_read();
14224 let fctx = &crate::decode::FrameCtx::for_encoder();
14225 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
14226 let picture = Picture::grey(width, height);
14227 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
14228 .expect_err(&format!("{width}x{height} is odd and must be refused"));
14229 assert!(
14230 err.to_string().contains("even"),
14231 "{width}x{height}: error was {err}"
14232 );
14233 }
14234 }
14235
14236 /// A sequence at a size that is not a multiple of the block grid decodes
14237 /// to the right frame count and the right size for every frame,
14238 /// including the inter frames whose reference is the previous frame's
14239 /// own (padded) reconstruction.
14240 #[test]
14241 fn sequence_round_trips_at_a_non_multiple_size() {
14242 let _knobs = crate::speed::knob_read();
14243 let fctx = &crate::decode::FrameCtx::for_encoder();
14244 if !have_ffmpeg() {
14245 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
14246 return;
14247 }
14248 let (width, height) = (160usize, 96usize);
14249 let pictures: Vec<Picture> = (0..3)
14250 .map(|i| panned_test_card(width, height, i * 3))
14251 .collect();
14252 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
14253 assert_eq!(encoded.frames.len(), 3);
14254 for (i, frame) in encoded.frames.iter().enumerate() {
14255 assert_eq!(
14256 (frame.reconstruction.width, frame.reconstruction.height),
14257 (width, height),
14258 "frame {i}: reconstruction size"
14259 );
14260 }
14261 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
14262 // true (display) size a sequence's frames share, not the padded one.
14263 assert_eq!(
14264 ffprobe_size(&encoded.stream),
14265 (width as u32, height as u32),
14266 "sequence: ffprobe reports the true (display) size"
14267 );
14268 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
14269 assert_eq!(decoded.len(), 3, "decoded frame count");
14270 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
14271 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
14272 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
14273 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
14274 }
14275 }
14276
14277 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
14278 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
14279 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
14280 /// `pos + side_mi / 2 < bound` boundary), which is the case
14281 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
14282 /// refusing. A key frame alone already covered this size; this proves the
14283 /// inter tile writer's parity with it across a real multi-frame export.
14284 #[test]
14285 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
14286 let _knobs = crate::speed::knob_read();
14287 let fctx = &crate::decode::FrameCtx::for_encoder();
14288 if !have_ffmpeg() {
14289 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
14290 return;
14291 }
14292 let (width, height) = (1280usize, 720usize);
14293 let pictures: Vec<Picture> = (0..3)
14294 .map(|i| panned_test_card(width, height, i * 3))
14295 .collect();
14296 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
14297 assert_eq!(encoded.frames.len(), 3);
14298 for (i, frame) in encoded.frames.iter().enumerate() {
14299 assert_eq!(
14300 (frame.reconstruction.width, frame.reconstruction.height),
14301 (width, height),
14302 "frame {i}: reconstruction size"
14303 );
14304 }
14305 assert_eq!(
14306 ffprobe_size(&encoded.stream),
14307 (width as u32, height as u32),
14308 "ffprobe reports the true (display) 1280x720 size"
14309 );
14310 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
14311 assert_eq!(decoded.len(), 3, "decoded frame count");
14312 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
14313 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
14314 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
14315 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
14316 }
14317 }
14318
14319 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
14320 /// leaf's own half (`has_half` at the SUB level) itself straddles the
14321 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
14322 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
14323 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
14324 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
14325 /// straddling-16x16 branch), so an inter frame no longer refuses this
14326 /// size either. This only proves the encoder does not error out -- see
14327 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
14328 /// decoder-clean proof (a 3-frame sequence, so the inter path is
14329 /// actually exercised).
14330 #[test]
14331 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
14332 let _knobs = crate::speed::knob_read();
14333 let fctx = &crate::decode::FrameCtx::for_encoder();
14334 let (width, height) = (640usize, 360usize);
14335 let picture = Picture::grey(width, height);
14336 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
14337
14338 // `encode_sequence`'s second frame is the inter path: same size, now
14339 // wired the same way.
14340 let pictures = vec![picture.clone(), picture];
14341 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
14342 .expect("inter frame now codes the mod-32==8 straddle too");
14343 }
14344
14345 /// The r15 fix at production size: three 640x360 key frames (inter is
14346 /// still refused at this size, per the test above, so this stands in for
14347 /// the charter's "3-frame sequence" using three independent key frames of
14348 /// shifted content), each proven decoder-clean through ffmpeg rather than
14349 /// only encoder-clean.
14350 #[test]
14351 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
14352 let _knobs = crate::speed::knob_read();
14353 let fctx = &crate::decode::FrameCtx::for_encoder();
14354 if !have_ffmpeg() {
14355 eprintln!(
14356 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
14357 no ffmpeg"
14358 );
14359 return;
14360 }
14361 let (width, height) = (640usize, 360usize);
14362 for shift in [0i64, 7, 19] {
14363 let picture = panned_test_card(width, height, shift);
14364 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
14365 let decoded = ffmpeg_decode(&encoded.stream, width, height);
14366 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
14367 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
14368 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
14369 }
14370 }
14371
14372 /// The 640x360 straddle class, but through the inter path an actual
14373 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
14374 /// proves the leaf-8 inter stream this round wires up is not just
14375 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
14376 #[test]
14377 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
14378 let _knobs = crate::speed::knob_read();
14379 let fctx = &crate::decode::FrameCtx::for_encoder();
14380 if !have_ffmpeg() {
14381 eprintln!(
14382 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
14383 );
14384 return;
14385 }
14386 let (width, height) = (640usize, 360usize);
14387 let pictures: Vec<Picture> = (0..4)
14388 .map(|i| panned_test_card(width, height, i * 3))
14389 .collect();
14390 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
14391 assert_eq!(encoded.frames.len(), 4);
14392 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
14393 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
14394 }
14395 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
14396 assert_eq!(decoded.len(), 4, "decoded frame count");
14397 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
14398 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
14399 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
14400 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
14401 }
14402 }
14403
14404 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
14405 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
14406 let out = Command::new("ffmpeg")
14407 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
14408 .args(["-vf", &format!("scale={width}:{height}")])
14409 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
14410 .output()
14411 .expect("ffmpeg failed to run");
14412 assert!(
14413 out.status.success(),
14414 "ffmpeg: {}",
14415 String::from_utf8_lossy(&out.stderr)
14416 );
14417 let (luma, chroma) = (width * height, width * height / 4);
14418 assert_eq!(
14419 out.stdout.len(),
14420 luma + 2 * chroma,
14421 "expected one 4:2:0 frame"
14422 );
14423 Picture {
14424 width,
14425 height,
14426 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
14427 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
14428 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
14429 }
14430 }
14431
14432 /// Prints what the mode search saves over DC prediction alone, for the
14433 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
14434 /// weight the search puts on rate can be swept.
14435 #[test]
14436 #[ignore = "a sweep, not a gate"]
14437 fn probe_lambda() {
14438 let _knobs = crate::speed::knob_read();
14439 let fctx = &crate::decode::FrameCtx::for_encoder();
14440 let mut pictures = vec![
14441 ("test card".to_string(), test_card(160, 96)),
14442 ("stripes".to_string(), stripes(160, 96, true)),
14443 ];
14444 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
14445 for entry in clips.split(':').filter(|e| !e.is_empty()) {
14446 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
14447 let name = path.rsplit('/').next().unwrap_or(path).to_string();
14448 pictures.push((name, clip_frame(path, skip, 640, 352)));
14449 }
14450 }
14451 for (name, picture) in pictures {
14452 let dc = ladder(&picture, &[DC_PRED], fctx);
14453 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
14454 println!(
14455 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
14456 bd_rate(&dc, &searched) * 100.0,
14457 10f64.powf(searched[1].1),
14458 searched[1].0,
14459 10f64.powf(dc[1].1),
14460 dc[1].0,
14461 );
14462 }
14463 }
14464
14465 /// Prints the whole mode-search ladder, so two builds of the search can be
14466 /// compared against each other rather than each against its own baseline.
14467 #[test]
14468 #[ignore = "a sweep, not a gate"]
14469 fn probe_ladder() {
14470 let _knobs = crate::speed::knob_read();
14471 let fctx = &crate::decode::FrameCtx::for_encoder();
14472 for (name, picture) in sweep_pictures() {
14473 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
14474 let points = all
14475 .iter()
14476 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
14477 .collect::<Vec<_>>()
14478 .join(" ");
14479 println!("ladder {name}: {points}");
14480 }
14481 }
14482
14483 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
14484 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
14485 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
14486 #[test]
14487 #[ignore = "a sweep, not a gate"]
14488 fn probe_split() {
14489 let _knobs = crate::speed::knob_read();
14490 let fctx = &crate::decode::FrameCtx::for_encoder();
14491 for (name, picture) in sweep_pictures() {
14492 let ladder = |split: bool| {
14493 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
14494 .iter()
14495 .map(|&q| {
14496 let encoded = encode_key_frame_inner(
14497 &picture,
14498 q,
14499 0.5,
14500 &KEY_FRAME_MODES,
14501 split,
14502 (picture.width, picture.height),
14503 unspecified_color_config(), fctx,
14504 )
14505 .unwrap();
14506 (
14507 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
14508 (encoded.stream.len() as f64).log10(),
14509 )
14510 })
14511 .collect();
14512 points.sort_by(|a, b| a.0.total_cmp(&b.0));
14513 points
14514 };
14515 let (whole, split) = (ladder(false), ladder(true));
14516 let blocks = encode_key_frame_inner(
14517 &picture,
14518 90,
14519 0.5,
14520 &KEY_FRAME_MODES,
14521 true,
14522 (picture.width, picture.height),
14523 unspecified_color_config(), fctx,
14524 )
14525 .unwrap()
14526 .modes
14527 .len();
14528 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
14529 println!(
14530 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
14531 bd_rate(&whole, &split) * 100.0
14532 );
14533 }
14534 }
14535
14536 /// A striped picture, running one way or the other. The stripes are what
14537 /// separates a vertical predictor from a horizontal one: a mode search
14538 /// reading a transposed edge would pick the wrong one of the pair, which no
14539 /// symmetric picture would show.
14540 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
14541 let mut picture = Picture::grey(width, height);
14542 for y in 0..height {
14543 for x in 0..width {
14544 let along = if vertical { x } else { y };
14545 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
14546 }
14547 }
14548 picture
14549 }
14550
14551 /// Where two planes first disagree, and by how much: a mismatch reported as
14552 /// a position says which block and which sample of it went wrong, which a
14553 /// pair of thousand-sample arrays does not.
14554 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
14555 let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
14556 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
14557 Some(format!(
14558 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
14559 i % width,
14560 i / width,
14561 ours[i],
14562 theirs[i]
14563 ))
14564 }
14565
14566 /// Every mode the encoder offers has to predict what the decoder predicts,
14567 /// not just the ones a particular picture happens to choose: each is forced
14568 /// over a whole picture and the reconstruction gated against ffmpeg.
14569 #[test]
14570 fn every_mode_decodes_to_what_the_encoder_predicted() {
14571 let _knobs = crate::speed::knob_write();
14572 let fctx = &crate::decode::FrameCtx::for_encoder();
14573 if !have_ffmpeg() {
14574 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
14575 return;
14576 }
14577 // A mode ablation measures the MODE search: a filter-intra block is
14578 // coded `DC_PRED` whatever mode the arm forces, so it would fail the
14579 // "the encoder coded something else" check for a reason that is not
14580 // about the mode search at all.
14581 force_filter_intra(Some(false));
14582 // 128 wide is a whole number of superblocks and 160 is not: the last
14583 // superblock of a 160-wide row is half a one, whose blocks have no
14584 // above-right samples inside the frame at all.
14585 for (width, height) in [(128, 96), (160, 96)] {
14586 let picture = test_card(width, height);
14587 for mode in KEY_FRAME_MODES {
14588 let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap();
14589 let decoded = ffmpeg_decode(&encoded.stream, width, height);
14590 for (plane, ours, theirs, stride) in [
14591 ("luma", &encoded.reconstruction.y, &decoded.y, width),
14592 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
14593 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
14594 ] {
14595 assert!(
14596 first_difference(ours, theirs, stride).is_none(),
14597 "{width}x{height} mode {mode}, {plane}: {}",
14598 first_difference(ours, theirs, stride).unwrap()
14599 );
14600 }
14601 assert!(
14602 encoded.modes.iter().all(|&m| m == mode),
14603 "mode {mode}: the encoder coded something else"
14604 );
14605 }
14606 }
14607 }
14608
14609 /// The search has to follow the picture: vertical stripes are cheapest
14610 /// predicted from the row above, horizontal ones from the column to the
14611 /// left. Reading the edges the other way round would swap the two answers
14612 /// while leaving every fidelity gate intact.
14613 #[test]
14614 fn the_search_picks_the_direction_the_picture_runs() {
14615 let _knobs = crate::speed::knob_write();
14616 let fctx = &crate::decode::FrameCtx::for_encoder();
14617 // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]:
14618 // a filter-intra block is coded `DC_PRED` whatever mode the arm
14619 // offers, and these stripes are SCREEN content, where the filter arm
14620 // now searches its own transform depth (lane-fitu) and wins outright
14621 // -- which says nothing about the mode search this gate measures.
14622 force_filter_intra(Some(false));
14623 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
14624 let picture = stripes(128, 96, vertical);
14625 // Only the pair, because on stripes a third mode predicts exactly
14626 // what the right one of the pair does -- PAETH reads the corner and
14627 // the left column, which a striped picture makes equal -- and the
14628 // tie then goes to whichever is cheaper to name, which is not what
14629 // this gate is about.
14630 let encoded =
14631 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
14632 // The first block of the picture has neither neighbour, so it
14633 // cannot tell the modes apart; every other one can.
14634 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
14635 assert!(
14636 picked * 2 > encoded.modes.len() - 1,
14637 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
14638 encoded.modes.len() - 1,
14639 encoded.modes
14640 );
14641 }
14642 }
14643
14644 /// What the search is for: the same picture, at the same quantizer, coded
14645 /// smaller and more faithfully than DC alone can manage.
14646 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
14647 /// between the two rate-distortion curves in log-rate against PSNR, as a
14648 /// fraction of the reference's rate. Negative means the second curve costs
14649 /// less for the same picture.
14650 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
14651 let low = reference[0].0.max(other[0].0);
14652 let high = reference[reference.len() - 1]
14653 .0
14654 .min(other[other.len() - 1].0);
14655 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
14656 // the non-directional one on the synthetic diagonals -- every point
14657 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
14658 // to integrate over any more. A curve that dominates that way has
14659 // saved everything the measure can express (the
14660 // `instrument-at-bound` class: the answer is at the instrument's own
14661 // edge, not undefined), so name it rather than panicking; anything
14662 // less clean than strict dominance still is.
14663 if high <= low {
14664 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
14665 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
14666 let dominates = other[0].0 > reference[reference.len() - 1].0
14667 && other_hi_rate <= ref_lo_rate;
14668 assert!(
14669 dominates,
14670 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
14671 );
14672 return -1.0;
14673 }
14674 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
14675 let i = curve
14676 .windows(2)
14677 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
14678 .unwrap_or(0);
14679 let (x0, y0) = curve[i];
14680 let (x1, y1) = curve[i + 1];
14681 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
14682 };
14683 let steps = 64;
14684 let mut area = 0.0;
14685 for step in 0..steps {
14686 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
14687 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
14688 }
14689 10f64.powf(area / f64::from(steps)) - 1.0
14690 }
14691
14692 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
14693 /// fidelity.
14694 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
14695 // A mode ablation measures the MODE search: the palette would code
14696 // these synthetic two-colour pictures losslessly under every arm and
14697 // leave nothing to compare (see [`force_screen`]).
14698 force_screen(Some(false));
14699 // Same reason, for the filter-intra candidate: it wins blocks under
14700 // BOTH arms of a mode ablation and so cancels the difference the
14701 // ablation measures (class `gate-recipe-confound`).
14702 force_filter_intra(Some(false));
14703 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
14704 .iter()
14705 .map(|&q| {
14706 let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
14707 (
14708 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
14709 (encoded.stream.len() as f64).log10(),
14710 )
14711 })
14712 .collect();
14713 points.sort_by(|a, b| a.0.total_cmp(&b.0));
14714 points
14715 }
14716
14717 /// What the search is for: the same pictures cost less to code at the same
14718 /// fidelity than DC prediction alone can manage. A picture that runs one
14719 /// way saves far more than a busy one, which is the shape a working
14720 /// directional pair has.
14721 #[test]
14722 fn the_search_beats_dc_alone() {
14723 let _knobs = crate::speed::knob_read();
14724 let fctx = &crate::decode::FrameCtx::for_encoder();
14725 for (name, picture, want) in [
14726 ("test card", test_card(160, 96), -0.05),
14727 ("stripes", stripes(160, 96, true), -0.40),
14728 ] {
14729 let saved = bd_rate(
14730 &ladder(&picture, &[DC_PRED], fctx),
14731 &ladder(&picture, &NON_DIRECTIONAL, fctx),
14732 );
14733 assert!(
14734 saved < want,
14735 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
14736 saved * 100.0,
14737 -want * 100.0
14738 );
14739 }
14740 }
14741
14742 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
14743 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
14744 fn sweep_pictures() -> Vec<(String, Picture)> {
14745 let mut pictures = vec![
14746 ("test card".to_string(), test_card(160, 96)),
14747 ("stripes".to_string(), stripes(160, 96, true)),
14748 ("diagonal".to_string(), diagonal(160, 96, true)),
14749 ];
14750 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
14751 for entry in clips.split(':').filter(|e| !e.is_empty()) {
14752 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
14753 let name = path.rsplit('/').next().unwrap_or(path).to_string();
14754 pictures.push((name, clip_frame(path, skip, 640, 352)));
14755 }
14756 }
14757 pictures
14758 }
14759
14760 /// What the six directional modes are worth, per picture, at whatever
14761 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
14762 /// no further, and how often the search picks one.
14763 #[test]
14764 #[ignore = "a sweep, not a gate"]
14765 fn probe_directional() {
14766 let _knobs = crate::speed::knob_write();
14767 let fctx = &crate::decode::FrameCtx::for_encoder();
14768 for (name, picture) in sweep_pictures() {
14769 let dc = ladder(&picture, &[DC_PRED], fctx);
14770 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
14771 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
14772 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
14773 let directional = encoded
14774 .modes
14775 .iter()
14776 .filter(|&&m| (3..=8).contains(&m))
14777 .count();
14778 // A picture whose ladders sit at different fidelities altogether
14779 // has no BD-rate to report -- see the flat-sample-window class.
14780 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
14781 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
14782 };
14783 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
14784 if overlap(a, b) {
14785 format!("{:+.2}%", bd_rate(a, b) * 100.0)
14786 } else {
14787 "no overlap".to_string()
14788 }
14789 };
14790 println!(
14791 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
14792 against(&flat, &all),
14793 against(&dc, &all),
14794 encoded.modes.len(),
14795 );
14796 }
14797 }
14798
14799 /// A picture whose stripes run along a diagonal, one way or the other.
14800 /// This is to the directional modes what [`stripes`] is to the vertical and
14801 /// horizontal pair: a predictor that walked the edge in the wrong direction
14802 /// would answer the two pictures the same way round.
14803 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
14804 let mut picture = Picture::grey(width, height);
14805 for y in 0..height {
14806 for x in 0..width {
14807 let along = if down_right { x + height - y } else { x + y };
14808 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
14809 }
14810 }
14811 picture
14812 }
14813
14814 /// The mode picked by the most blocks of a picture, ignoring the first
14815 /// block, which has no neighbours to tell the modes apart with.
14816 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
14817 // A mode ablation measures the MODE search: the palette would code
14818 // these synthetic two-colour pictures losslessly under every arm and
14819 // leave nothing to compare (see [`force_screen`]).
14820 force_screen(Some(false));
14821 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
14822 let blocks = &encoded.modes[1..];
14823 let mut counts = [0usize; 13];
14824 for &mode in blocks {
14825 counts[usize::from(mode)] += 1;
14826 }
14827 let (mode, count) = counts
14828 .iter()
14829 .enumerate()
14830 .max_by_key(|&(_, count)| *count)
14831 .expect("thirteen modes");
14832 (mode as u8, *count, blocks.len())
14833 }
14834
14835 /// The search has to follow a diagonal the way it runs: stripes down and to
14836 /// the right are cheapest predicted at 135 degrees, stripes down and to the
14837 /// left at 45. A walk that stepped the wrong way along the edge, or read
14838 /// the above row where it should read the left column, would swap these.
14839 #[test]
14840 fn the_search_picks_the_diagonal_the_picture_runs() {
14841 let _knobs = crate::speed::knob_write();
14842 let fctx = &crate::decode::FrameCtx::for_encoder();
14843 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
14844 let picture = diagonal(160, 96, down_right);
14845 let (mode, count, blocks) = favourite_mode(&picture, fctx);
14846 assert_eq!(
14847 mode, want,
14848 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
14849 );
14850 }
14851 }
14852
14853 /// What the directional modes are for: a picture that runs along a diagonal
14854 /// costs far less to code with them than the seven that read only their own
14855 /// edges can manage, and a picture that runs no particular way costs no
14856 /// more. The second half is the one that bites: a mode set the search
14857 /// cannot price is a mode set that loses rate on content that does not want
14858 /// it, which is what costing the mode symbol is for.
14859 #[test]
14860 fn the_diagonals_beat_the_modes_that_read_no_further() {
14861 let _knobs = crate::speed::knob_read();
14862 let fctx = &crate::decode::FrameCtx::for_encoder();
14863 for (name, picture, want) in [
14864 ("down-right", diagonal(160, 96, true), -0.20),
14865 ("down-left", diagonal(160, 96, false), -0.20),
14866 ("test card", test_card(160, 96), 0.01),
14867 ] {
14868 let saved = bd_rate(
14869 &ladder(&picture, &NON_DIRECTIONAL, fctx),
14870 &ladder(&picture, &KEY_FRAME_MODES, fctx),
14871 );
14872 assert!(
14873 saved < want,
14874 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
14875 saved * 100.0,
14876 -want * 100.0
14877 );
14878 }
14879 }
14880
14881 /// A mode the encoder cannot predict must be refused rather than coded as
14882 /// something else, and a search with nothing to choose from likewise.
14883 #[test]
14884 fn a_mode_the_encoder_cannot_predict_is_refused() {
14885 let _knobs = crate::speed::knob_read();
14886 let fctx = &crate::decode::FrameCtx::for_encoder();
14887 let picture = test_card(64, 64);
14888 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
14889 .unwrap_err()
14890 .to_string();
14891 assert!(
14892 message.contains("intra mode 13"),
14893 "the refusal must name the mode, got {message}"
14894 );
14895 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
14896 }
14897
14898 /// The picture that comes back is the picture that went in, to within the
14899 /// quantizer. A prediction that read the wrong neighbours, or a block
14900 /// written into the wrong place, would still decode to what the encoder
14901 /// reconstructed — it is this gate that says the reconstruction is of the
14902 /// right picture.
14903 #[test]
14904 fn the_encoded_picture_is_the_one_that_went_in() {
14905 let _knobs = crate::speed::knob_read();
14906 let fctx = &crate::decode::FrameCtx::for_encoder();
14907 let picture = test_card(160, 96);
14908 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
14909 let luma = psnr(&encoded.reconstruction.y, &picture.y);
14910 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
14911 for (plane, (got, want)) in [
14912 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
14913 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
14914 ]
14915 .iter()
14916 .enumerate()
14917 {
14918 let chroma = psnr(got, want);
14919 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
14920 }
14921 }
14922
14923 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
14924 /// does the opposite. Both are monotone, which is what a rate-distortion
14925 /// loop above this will assume.
14926 #[test]
14927 fn fidelity_and_rate_move_with_the_quantizer() {
14928 let _knobs = crate::speed::knob_read();
14929 let fctx = &crate::decode::FrameCtx::for_encoder();
14930 let picture = test_card(128, 128);
14931 let mut previous: Option<(usize, f64)> = None;
14932 for &q in &[70u8, 90, 110] {
14933 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
14934 let quality = psnr(&encoded.reconstruction.y, &picture.y);
14935 if let Some((bytes, better)) = previous {
14936 assert!(
14937 encoded.stream.len() < bytes,
14938 "q {q}: {} bytes",
14939 encoded.stream.len()
14940 );
14941 assert!(quality < better, "q {q}: PSNR {quality}");
14942 }
14943 previous = Some((encoded.stream.len(), quality));
14944 }
14945
14946 // The deadzone half of this claim lives in
14947 // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now:
14948 // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding
14949 // every zeroing, the deadzone no longer moves a coded stream
14950 // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against
14951 // fewer at 0.5 on this 128x128 card), and that is the pass doing its
14952 // job, not a quantiser defect.
14953
14954 // Bytes must not jump up across a q-context boundary: a wrong CDF
14955 // table for the far side would show up as a rate discontinuity here,
14956 // even though a coarser quantizer always codes no more than a finer
14957 // one on the same picture.
14958 //
14959 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
14960 // chroma searches its own mode, a coarser quantizer can pick a
14961 // *different* uv_mode on a block whose modes now cost nearly the
14962 // same, and the search prices that symbol against the static default
14963 // CDF while the writer codes it against an adapted one -- 311 -> 319
14964 // bytes at q 120->121 on this picture. The table this gate is really
14965 // watching would move the rate by far more than the mode churn does.
14966 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
14967 // same block can also change transform DEPTH between two neighbouring
14968 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
14969 // symbol is priced off the static CDF row 0 for the same reason the
14970 // uv_mode one is.
14971 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
14972 // path is pricing through the adapting CDF state (what
14973 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
14974 // drift of), after which the exact bound comes back.
14975 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
14976 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
14977 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
14978 assert!(
14979 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
14980 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
14981 );
14982 }
14983 }
14984
14985 /// A flat picture is a flat stream: every block predicts its neighbours'
14986 /// average, which is the picture's own value, and codes nothing.
14987 #[test]
14988 fn a_flat_picture_costs_almost_nothing() {
14989 let _knobs = crate::speed::knob_read();
14990 let fctx = &crate::decode::FrameCtx::for_encoder();
14991 let mut picture = Picture::grey(128, 128);
14992 picture.y.fill(97);
14993 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
14994 // The first block has no neighbour and predicts 128, so it carries a
14995 // DC; every block after it predicts 97 and carries nothing.
14996 assert!(
14997 encoded.stream.len() < 100,
14998 "{} bytes for a flat picture",
14999 encoded.stream.len()
15000 );
15001 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
15002 assert_eq!(s, 97, "sample {i} of a flat picture");
15003 }
15004 }
15005
15006 /// The sizes the encoder refuses, refused for a reason rather than by
15007 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
15008 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
15009 /// lands past the halfway point of whichever block it falls in, so
15010 /// `PARTITION_NONE` or a single gathered split flag still says everything
15011 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
15012 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
15013 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
15014 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
15015 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
15016 /// refusal here claimed otherwise and was wrong; see
15017 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
15018 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
15019 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
15020 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
15021 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
15022 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
15023 /// still refused is a malformed picture.
15024 #[test]
15025 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
15026 let _knobs = crate::speed::knob_read();
15027 let fctx = &crate::decode::FrameCtx::for_encoder();
15028 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
15029 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
15030 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
15031 .expect("36 luma columns still round up to an even MiCols");
15032
15033 let mut short = Picture::grey(64, 64);
15034 short.u.truncate(10);
15035 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
15036 }
15037
15038 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
15039 /// column half only (`has_half` false on cols, true on rows) -- exactly
15040 /// the single-axis straddle lane-av1-rect r7 wires through
15041 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
15042 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
15043 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
15044 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
15045 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
15046 /// `partition_context_lookup` entry this writer ever produces (no 4x4
15047 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
15048 /// leaf regardless of neighbour state -- our writer already agreed with
15049 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
15050 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
15051 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
15052 /// it does not regress the gate. r11 tell-for-tell traced two further,
15053 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
15054 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
15055 /// leaves, when the second leaf's true above (or left) neighbour is the
15056 /// first leaf itself -- fixed by threading the first leaf's mode into the
15057 /// second leaf's context, mi-precise, like `record_mi` already does for
15058 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
15059 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
15060 /// `reduced_tx_set` is false), but this crate's key frames set
15061 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
15062 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
15063 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
15064 /// symbol bits to desync everything after it. Fixed with a new
15065 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
15066 /// eset/size slot). Both fixes are provably correct against libaom
15067 /// source and each closed part of the gap (leaf0's `eob` went from a
15068 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
15069 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
15070 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
15071 /// (do not reuse r11's committed logs, which predate its own fixes) and
15072 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
15073 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
15074 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
15075 /// every other `write_block` caller at 16x16 and up already passes
15076 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
15077 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
15078 /// different amount of arithmetic range and derailed everything after
15079 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
15080 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
15081 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
15082 /// never updating those coarse arrays itself -- so a *second* straddling
15083 /// 16x16 quadrant stacked above or left of the first (never covered by
15084 /// r11's same-call `prev_leaf` override, which only threads state
15085 /// between the two leaves of one shared quadrant) read whatever stale
15086 /// mode sat in that slot before either leaf ran. Fixed by writing the
15087 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
15088 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
15089 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
15090 /// offset of a single unit; fixing (3)+(4) together still leaves a
15091 /// residual divergence one leaf further in -- the decoder now reads
15092 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
15093 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
15094 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
15095 /// desyncs the stream by exactly the width of one earlier symbol -- not
15096 /// yet isolated to a single named symbol. r15 found the last bug: the
15097 /// header fix from r14 explained the rng skew fully, and the remaining
15098 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
15099 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
15100 /// loop, once per leaf, so the first leaf's write clobbered the true
15101 /// external neighbour mode the second leaf of the *same* straddling
15102 /// quadrant still needed for its non-adjacency axis (a column-straddle
15103 /// case: two leaves share one `outer_at` column index, so leaf 1's
15104 /// write to `left_mode[r]` overwrote the real western neighbour before
15105 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
15106 /// doing it once, after the whole leaf loop, from the last (bottom/
15107 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
15108 #[test]
15109 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
15110 let _knobs = crate::speed::knob_read();
15111 let fctx = &crate::decode::FrameCtx::for_encoder();
15112 if !have_ffmpeg() {
15113 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
15114 return;
15115 }
15116 let (width, height) = (40usize, 32usize);
15117 let picture = test_card(width, height);
15118 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15119 assert_eq!(
15120 (encoded.reconstruction.width, encoded.reconstruction.height),
15121 (width, height)
15122 );
15123 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
15124 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
15125 }
15126 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15127 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
15128 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
15129 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
15130 }
15131
15132 /// A frame of real video, rather than a picture built to be easy.
15133 ///
15134 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
15135 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
15136 /// encoder's reconstruction has to survive the same equality gate as the
15137 /// synthetic pictures — real video reaches contexts a test card does not.
15138 #[test]
15139 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
15140 let _knobs = crate::speed::knob_read();
15141 let fctx = &crate::decode::FrameCtx::for_encoder();
15142 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
15143 eprintln!(
15144 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
15145 set EC_AV1_CLIP to a clip"
15146 );
15147 return;
15148 };
15149 if !have_ffmpeg() {
15150 eprintln!(
15151 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
15152 );
15153 return;
15154 }
15155 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
15156 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
15157 // test quick while still spanning many superblocks.
15158 let (width, height) = (640usize, 352usize);
15159 let picture = clip_frame(&clip, &skip, width, height);
15160
15161 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15162 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15163 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
15164 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
15165 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
15166 eprintln!(
15167 "{} bytes, luma PSNR {:.2} dB",
15168 encoded.stream.len(),
15169 psnr(&decoded.y, &picture.y)
15170 );
15171 }
15172
15173 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
15174 /// sequence of these is a translation a motion search can actually find
15175 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
15176 /// inter frame's rate against the key frame's is measuring the same
15177 /// picture moving, not two different pictures.
15178 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
15179 let mut picture = Picture::grey(width, height);
15180 for y in 0..height {
15181 for x in 0..width {
15182 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
15183 let gradient = sx * 200.0 / width as f64;
15184 let ripple = 30.0
15185 * (sx * std::f64::consts::PI / 23.0).sin()
15186 * (y as f64 * std::f64::consts::PI / 37.0).cos();
15187 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
15188 40.0
15189 } else {
15190 0.0
15191 };
15192 picture.y[y * width + x] =
15193 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
15194 }
15195 }
15196 for y in 0..height / 2 {
15197 for x in 0..width / 2 {
15198 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
15199 let i = y * width / 2 + x;
15200 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
15201 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
15202 }
15203 }
15204 picture
15205 }
15206
15207 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
15208 fn ffmpeg_decode_sequence(
15209 stream: &[u8],
15210 width: usize,
15211 height: usize,
15212 frames: usize,
15213 ) -> Vec<Picture> {
15214 let mut child = Command::new("ffmpeg")
15215 .args([
15216 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
15217 ])
15218 .stdin(Stdio::piped())
15219 .stdout(Stdio::piped())
15220 .stderr(Stdio::piped())
15221 .spawn()
15222 .expect("ffmpeg failed to start");
15223 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
15224 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
15225 // fills before the last input byte is written -- which is exactly what
15226 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
15227 // (measured: 45 min, both processes at 0% CPU). A write error here is
15228 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
15229 // below, are the real diagnosis.
15230 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
15231 let payload = stream.to_vec();
15232 let writer = std::thread::spawn(move || {
15233 let _ = stdin.write_all(&payload);
15234 });
15235 let out = child.wait_with_output().expect("ffmpeg failed to run");
15236 writer.join().expect("ffmpeg stdin writer thread");
15237 assert!(
15238 out.status.success(),
15239 "ffmpeg refused the stream: {}",
15240 String::from_utf8_lossy(&out.stderr)
15241 );
15242 let (luma, chroma) = (width * height, width * height / 4);
15243 let frame_bytes = luma + 2 * chroma;
15244 assert_eq!(
15245 out.stdout.len(),
15246 frame_bytes * frames,
15247 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
15248 String::from_utf8_lossy(&out.stderr)
15249 );
15250 (0..frames)
15251 .map(|i| {
15252 let base = i * frame_bytes;
15253 Picture {
15254 width,
15255 height,
15256 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
15257 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
15258 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
15259 }
15260 })
15261 .collect()
15262 }
15263
15264 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
15265 /// makes for a key frame, extended down the reference chain: each inter
15266 /// frame's reconstruction predicts from the previous frame's own decoded
15267 /// reconstruction, so a single sample of drift anywhere would propagate
15268 /// into every frame after it -- which is why every frame is checked, not
15269 /// just the last one, and why this is an equality and not a tolerance.
15270 #[test]
15271 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
15272 let _knobs = crate::speed::knob_read();
15273 let fctx = &crate::decode::FrameCtx::for_encoder();
15274 if !have_ffmpeg() {
15275 eprintln!(
15276 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
15277 );
15278 return;
15279 }
15280 let (width, height) = (128usize, 64usize);
15281 let pictures: Vec<Picture> = (0..5)
15282 .map(|i| panned_test_card(width, height, i * 3))
15283 .collect();
15284 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
15285 assert_eq!(encoded.frames.len(), 5);
15286
15287 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
15288 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
15289 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
15290 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
15291 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
15292 }
15293
15294 eprintln!("frame bytes luma PSNR (dB) inter share");
15295 for (i, frame) in encoded.frames.iter().enumerate() {
15296 eprintln!(
15297 "{i:5} {:5} {:14.2} {:11.2}",
15298 frame.stream.len(),
15299 psnr(&frame.reconstruction.y, &pictures[i].y),
15300 frame.inter_block_share
15301 );
15302 }
15303 }
15304
15305 /// The same sequence through OUR OWN decoder, sample-exact against the
15306 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
15307 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
15308 /// divergence point at all, while our decoder can be traced symbol by
15309 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
15310 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
15311 /// names the first differing frame, plane and position.
15312 /// lane-sb128b: the writer used to price a `NEWMV` residual against
15313 /// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the
15314 /// write-time stack could not carry, while the drl symbols signalled the
15315 /// clamped index -- so the decoder derived a DIFFERENT motion vector with
15316 /// the entropy stream still in sync, and the drift only surfaced frames
15317 /// later as a drl desync (on film B, as the encoder's own trial decode
15318 /// refusing a reference slot).
15319 ///
15320 /// The clamp needs a stack that shrinks between search and write, which
15321 /// is what a 128x128 superblock's visit order does; the counter is the
15322 /// point (class `gate-blind-to-feature`): a green round trip on a clip
15323 /// that never clamps proves nothing.
15324 ///
15325 /// `#[ignore]`: [`force_sb128`] moves a process-global.
15326 ///
15327 /// cargo test -p ec-av1 --release --lib -- --ignored \
15328 /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture
15329 #[test]
15330 #[ignore = "sets the process-global superblock size: run it alone"]
15331 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
15332 let _knobs = crate::speed::knob_write();
15333 if !have_ffmpeg() {
15334 eprintln!("SKIP: no ffmpeg");
15335 return;
15336 }
15337 force_sb128(true);
15338 let dir = std::env::temp_dir().join(format!("ec-av1-sb128b-{}", std::process::id()));
15339 std::fs::create_dir_all(&dir).unwrap();
15340 let clip = dir.join("mandelbrot-1280x768.y4m");
15341 let ok = Command::new("ffmpeg")
15342 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "mandelbrot=size=1280x768:rate=24"])
15343 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
15344 .arg(&clip)
15345 .status()
15346 .expect("ffmpeg failed to run")
15347 .success();
15348 assert!(ok, "ffmpeg could not write the synthetic clip");
15349 let path = clip.to_str().unwrap();
15350 let (width, height) = (1280usize, 768usize);
15351 let pictures = crate::probe::source(path, "0", "null", width, height, 12);
15352
15353 let _ = crate::tile::take_drl_clamp_hits();
15354 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
15355 let clamps = crate::tile::take_drl_clamp_hits();
15356 assert!(
15357 clamps > 0,
15358 "this clip never asked for a drl index the write-time stack could not carry, \
15359 so it cannot witness the defect"
15360 );
15361 eprintln!("clamped drl indices: {clamps}");
15362
15363 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
15364 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
15365 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
15366 let recon = &frame.reconstruction;
15367 for (plane, got, want) in [
15368 ("luma", &dec.y, &recon.y),
15369 ("U", &dec.u, &recon.u),
15370 ("V", &dec.v, &recon.v),
15371 ] {
15372 let differ = got.iter().zip(want).filter(|(a, b)| a != b).count();
15373 assert_eq!(
15374 differ, 0,
15375 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
15376 own reconstruction",
15377 got.len()
15378 );
15379 }
15380 }
15381 }
15382
15383 #[test]
15384 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
15385 let _knobs = crate::speed::knob_read();
15386 let fctx = &crate::decode::FrameCtx::for_encoder();
15387 // 256x128, not the 128x64 this started at: once a leaf could search
15388 // its second reference (lane-av1comp4) the small card's every
15389 // eligible block went to a compound winner, which commits its flat
15390 // transform, and the split below stopped firing on content that
15391 // still splits at every larger size ([[gate-blind-to-feature]] --
15392 // the guard is right, the fixture had shrunk under it).
15393 let (width, height) = (256usize, 128usize);
15394 let pictures: Vec<Picture> =
15395 (0..5).map(|i| panned_test_card(width, height, i * 3)).collect();
15396 let _ = take_inter_tx_split_hits();
15397 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
15398 let raw = take_inter_tx_split_hits();
15399 // Summed over the four block classes the census keys on (leaf/32x32 x
15400 // single/compound): this assert is about the split firing at all.
15401 let split = [
15402 raw.iter().step_by(2).sum::<usize>(),
15403 raw.iter().skip(1).step_by(2).sum::<usize>(),
15404 ];
15405 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
15406 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
15407 // content splits -- a green round trip in which the split never fires
15408 // would prove only the flat path.
15409 if tx_select() && tx_select_inter() {
15410 assert!(split[1] > 0, "the inter var-tx split never fired");
15411 }
15412 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
15413 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
15414 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
15415 let recon = &frame.reconstruction;
15416 for (plane, got, want, stride) in [
15417 ("luma", &dec.y, &recon.y, width),
15418 ("U", &dec.u, &recon.u, width / 2),
15419 ("V", &dec.v, &recon.v, width / 2),
15420 ] {
15421 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
15422 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
15423 panic!(
15424 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
15425 reconstruction {} ({} of {} samples differ)",
15426 at % stride,
15427 at / stride,
15428 got[at],
15429 want[at],
15430 got.iter().zip(want).filter(|(a, b)| a != b).count(),
15431 got.len(),
15432 );
15433 }
15434 }
15435 }
15436 }
15437
15438 /// The rate term the mode search ranks every decision by has to be the
15439 /// rate the writer then spends. The search prices a block's coefficients
15440 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
15441 /// against the default CDFs a tile starts from and the contexts of a
15442 /// block whose neighbours coded nothing -- while the tile writer codes
15443 /// them against a state that has been adapting all frame (the
15444 /// price-the-narrowing class). This measures that drift: the sum of what
15445 /// the search paid for the coefficients it kept, against the bytes the
15446 /// writer actually emitted for the whole tile (which also carries the
15447 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
15448 /// expected to be the larger of the two).
15449 #[test]
15450 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
15451 let _knobs = crate::speed::knob_read();
15452 let fctx = &crate::decode::FrameCtx::for_encoder();
15453 let (width, height) = (256usize, 128usize);
15454 let pictures: Vec<Picture> = (0..5)
15455 .map(|i| panned_test_card(width, height, i * 2))
15456 .collect();
15457 let _ = take_predicted_bits();
15458 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
15459 let predicted = take_predicted_bits();
15460 assert_eq!(predicted.len(), encoded.frames.len());
15461
15462 eprintln!("frame predicted bits written bits drift");
15463 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
15464 // defect this gate exists to catch), a positive one is the written
15465 // side carrying syntax the coefficient sum leaves out -- and since
15466 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
15467 // on that side, so the two directions no longer share a bound.
15468 let mut worst_over: f64 = 0.0;
15469 let mut worst_under: f64 = 0.0;
15470 // The census is per CODED frame, so it is zipped in coding order --
15471 // which is not display order under a pyramid.
15472 let coded: Vec<&Encoded> =
15473 encoded.coding_order.iter().map(|&i| &encoded.frames[i]).collect();
15474 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
15475 let written = frame.tile.len() as f64 * 8.0;
15476 let drift = (written - bits) / written;
15477 worst_over = worst_over.max(-drift);
15478 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
15479 // all (150-250 bits of tile, nearly all of it partition/mode/mv
15480 // syntax the coefficient sum never counts), so its ratio measures
15481 // that floor rather than any drift. Frames under 512 written bits
15482 // are left out of the under-price bound for that reason; the
15483 // over-price bound -- the defect direction, where the search pays
15484 // MORE than the writer -- still covers every frame.
15485 if written >= 512.0 {
15486 worst_under = worst_under.max(drift);
15487 }
15488 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
15489 }
15490 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
15491 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
15492 // over-prices every frame but the last (its sum EXCLUDES the
15493 // partition/mode/skip/mv syntax the written side carries, so the true
15494 // coefficient over-price is larger still): the writer's CDFs adapt to
15495 // the content while the search's stay at the defaults. The bound is
15496 // set just above the worst measured point -- a widening drift is the
15497 // thing this gate exists to catch.
15498 assert!(
15499 worst_over <= 0.16,
15500 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
15501 worst_over * 100.0
15502 );
15503 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
15504 // the worst inter frame, where nearly every block now codes an MV
15505 // residual and a reference the coefficient sum never counts. Re-measured
15506 // at +29.6% once the encoder's grid published compound blocks properly
15507 // (compound share 8.8% -> 11.5%): a compound block carries a second
15508 // reference tree, a compound mode symbol and -- for the half-new modes
15509 // -- an MV residual, none of which the coefficient sum counts.
15510 // lane-av1txbits: pricing against the tables the frame's writer really
15511 // starts from collapses the over-price above to nothing, so the whole
15512 // remaining gap is the syntax the coefficient sum leaves out. That is
15513 // the default on a non-screen frame since lane-av1price2 (this
15514 // fixture is one), and it reads +32.6% here.
15515 // lane-av1obmc: every eligible single-reference inter block now also
15516 // carries a `motion_mode` symbol the coefficient sum never counts,
15517 // and an OBMC block carries the more expensive of the two values --
15518 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
15519 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
15520 // decisions, so this bound and the byte pins above FAIL BY DESIGN
15521 // under it; the default path (no motion_mode syntax at all) is the
15522 // one they are measured on.
15523 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
15524 // coding pyramid now, so the five frames are a key frame, a hidden
15525 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
15526 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
15527 // near-empty leaves below it. Both bounds stand where they were.
15528 // lane-av1rejudge: local warp is ON by default now, so every eligible
15529 // single-reference block carries that same `motion_mode` symbol (a
15530 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
15531 // +34.9% here, one point past the OBMC reading above. The bound moves
15532 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
15533 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
15534 // symbol and one or two magnitude symbols, none of which the
15535 // coefficient sum counts either -- +36.9% here against the same
15536 // fixture's +34.9% with `EC_AV1_CFL=0`.
15537 // ... and a directional block whose `angle_delta_y` is no longer
15538 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
15539 assert!(
15540 worst_under <= 0.40,
15541 "the writer spent {:.2}% more than the search priced -- more than \
15542 the mode/mv syntax outside the coefficient sum explains",
15543 worst_under * 100.0
15544 );
15545 }
15546
15547 /// The census behind step (1) of the pricer lane: for every transform
15548 /// block the writer really codes, what the search priced those levels at
15549 /// against what the writer spent on them, split by table set and non-zero
15550 /// count. One average hides the interesting part -- the classes the
15551 /// estimate is systematically wrong about (all-zero blocks, the
15552 /// one-coefficient blocks the inter search lives on) -- so the split is
15553 /// printed and only the total is asserted on.
15554 #[test]
15555 fn pricer_error_census_by_block_class() {
15556 let _knobs = crate::speed::knob_read();
15557 let fctx = &crate::decode::FrameCtx::for_encoder();
15558 let (width, height) = (256usize, 128usize);
15559 let pictures: Vec<Picture> = (0..5)
15560 .map(|i| panned_test_card(width, height, i * 2))
15561 .collect();
15562 crate::tile::pricer_census_on();
15563 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
15564 let rows = crate::tile::take_pricer_census();
15565 assert!(!rows.is_empty(), "the census saw no transform block");
15566
15567 println!("| set | nz | blocks | priced bits | written bits | error |");
15568 println!("|---|---|---|---|---|---|");
15569 let (mut priced_all, mut written_all) = (0.0, 0.0);
15570 for ((set, bucket), (blocks, priced, written)) in &rows {
15571 priced_all += priced;
15572 written_all += written;
15573 println!(
15574 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
15575 crate::tile::census_bucket_label(*bucket),
15576 if *written > 0.0 {
15577 (priced - written) / written * 100.0
15578 } else {
15579 0.0
15580 }
15581 );
15582 }
15583 println!(
15584 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
15585 rows.values().map(|r| r.0).sum::<u64>(),
15586 (priced_all - written_all) / written_all * 100.0
15587 );
15588 assert!(written_all > 0.0);
15589 }
15590
15591 /// Step (2) of the pricer lane: the same census, but on the REAL clips
15592 /// the BD gate scores -- one film clip and the screen capture -- so the
15593 /// question the film/screen split raises can be answered from data. Real
15594 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
15595 /// the screen capture larger, and the census says why: on a screen
15596 /// capture the frame's own starting tables are the tables of a frame that
15597 /// coded PALETTE and long runs of zero blocks, so they are far from the
15598 /// tables the writer ends the frame with; the pricer error does not fall
15599 /// the way it does on film.
15600 ///
15601 /// Not a gate -- it prints. Run it once per mode:
15602 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
15603 /// --ignored pricer_error_census_on_clips --nocapture
15604 #[test]
15605 #[ignore = "reads the real library, needs ffmpeg"]
15606 fn pricer_error_census_on_clips() {
15607 let _knobs = crate::speed::knob_write();
15608 if !have_ffmpeg() {
15609 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
15610 return;
15611 }
15612 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
15613 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
15614 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
15615 if film.exists() {
15616 clips.push(("film 1080p".to_string(), film));
15617 }
15618 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
15619 && let Some(p) = manifest
15620 .lines()
15621 .skip(1)
15622 .filter_map(|l| l.split('\t').next())
15623 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
15624 {
15625 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
15626 }
15627 assert!(!clips.is_empty(), "no source clip available");
15628 let (width, height, frames) = (640usize, 384usize, 6usize);
15629 for (name, path) in &clips {
15630 let fctx = &crate::decode::FrameCtx::for_encoder();
15631 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
15632 SCREEN_FRAMES.iter().for_each(|c| {
15633 c.store(0, std::sync::atomic::Ordering::Relaxed);
15634 });
15635 let _ = crate::tile::take_pricing_hits();
15636 crate::tile::pricer_census_on();
15637 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
15638 let rows = crate::tile::take_pricer_census();
15639 let (price_default, price_real) = crate::tile::take_pricing_hits();
15640 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
15641 println!(
15642 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
15643 {screen_on}, pricer armings default={price_default} real={price_real}"
15644 );
15645 println!("| set | nz | blocks | priced bits | written bits | error |");
15646 println!("|---|---|---|---|---|---|");
15647 let (mut priced_all, mut written_all) = (0.0, 0.0);
15648 for ((set, bucket), (blocks, priced, written)) in &rows {
15649 priced_all += priced;
15650 written_all += written;
15651 println!(
15652 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
15653 crate::tile::census_bucket_label(*bucket),
15654 if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 }
15655 );
15656 }
15657 println!(
15658 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
15659 rows.values().map(|r| r.0).sum::<u64>(),
15660 (priced_all - written_all) / written_all * 100.0
15661 );
15662 assert!(written_all > 0.0, "{name}: the census saw no transform block");
15663 }
15664 }
15665
15666 /// Low motion has to actually buy something: at least one inter frame of
15667 /// a panning sequence has to cost fewer bytes than the key frame that
15668 /// starts it, and the inter-block share it prints has to be non-zero --
15669 /// a search that never picks an inter mode would still pass a rate gate
15670 /// on a picture with no motion in it (the class this repo calls
15671 /// gate-blind-to-feature), so the share is printed even though it is not
15672 /// asserted on beyond being reachable at all.
15673 #[test]
15674 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
15675 let _knobs = crate::speed::knob_read();
15676 let fctx = &crate::decode::FrameCtx::for_encoder();
15677 let (width, height) = (256usize, 128usize);
15678 let pictures: Vec<Picture> = (0..5)
15679 .map(|i| panned_test_card(width, height, i * 2))
15680 .collect();
15681 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
15682
15683 let key_bytes = encoded.frames[0].stream.len();
15684 eprintln!("frame bytes inter share");
15685 for (i, frame) in encoded.frames.iter().enumerate() {
15686 eprintln!(
15687 "{i:5} {:5} {:11.2}",
15688 frame.stream.len(),
15689 frame.inter_block_share
15690 );
15691 }
15692 assert!(
15693 encoded.frames[1..]
15694 .iter()
15695 .any(|f| f.stream.len() < key_bytes),
15696 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
15697 );
15698 assert!(
15699 encoded.frames[1..]
15700 .iter()
15701 .any(|f| f.inter_block_share > 0.0),
15702 "no inter frame coded a single inter block -- the search never fired"
15703 );
15704 }
15705
15706 /// A manual perf probe, not a gate: prints where a key frame's and an
15707 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
15708 /// measures before it optimizes rather than guessing. Run with
15709 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
15710 #[test]
15711 #[ignore = "a perf probe, not a gate"]
15712 fn stage_timing_breakdown() {
15713 let _knobs = crate::speed::knob_read();
15714 let fctx = &crate::decode::FrameCtx::for_encoder();
15715 use std::time::Instant;
15716
15717 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
15718 let picture = test_card(width, height);
15719
15720 let t = Instant::now();
15721 let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
15722 let dc_only_t = t.elapsed();
15723
15724 let t = Instant::now();
15725 let non_directional =
15726 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
15727 let non_directional_t = t.elapsed();
15728
15729 let t = Instant::now();
15730 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15731 let all_modes_t = t.elapsed();
15732
15733 eprintln!(
15734 "\n=== key frame {width}x{height} ===\n\
15735 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
15736 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
15737 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
15738 dc_only.stream.len(),
15739 non_directional.stream.len(),
15740 all_modes.stream.len(),
15741 );
15742
15743 // One inter frame predicting off the key frame's own
15744 // reconstruction, the (256, 256)-padded surface encode_sequence
15745 // itself would hand encode_inter_frame.
15746 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
15747 let padded_pic = picture.padded_to(SUPERBLOCK);
15748 let t = Instant::now();
15749 let inter =
15750 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();
15751 let inter_t = t.elapsed();
15752 eprintln!(
15753 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
15754 {:.2})",
15755 inter.stream.len(),
15756 inter.inter_block_share
15757 );
15758 }
15759
15760 // Isolated per-call cost of the trial pipeline's own stages, at both
15761 // transform sizes the search runs, averaged over enough calls to
15762 // rise above `Instant::now`'s own noise.
15763 for side in [16usize, 32] {
15764 const N: u32 = 20_000;
15765 let residual: Vec<i32> = (0..side * side)
15766 .map(|i| ((i * 37 % 61) as i32) - 30)
15767 .collect();
15768
15769 let t = Instant::now();
15770 let mut levels = Vec::new();
15771 for _ in 0..N {
15772 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
15773 }
15774 let forward_t = t.elapsed() / N;
15775
15776 let t = Instant::now();
15777 for _ in 0..N {
15778 std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
15779 }
15780 let inverse_t = t.elapsed() / N;
15781
15782 let set = if side == 32 {
15783 crate::cdf_state::TxbSet::Luma32
15784 } else {
15785 crate::cdf_state::TxbSet::Luma16
15786 };
15787 let t = Instant::now();
15788 for _ in 0..N {
15789 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
15790 }
15791 let entropy_t = t.elapsed() / N;
15792
15793 let above = vec![128u8; side * 2];
15794 let left = vec![128u8; side * 2];
15795 let mut prediction = vec![0u8; side * side];
15796 let t = Instant::now();
15797 for _ in 0..N {
15798 intra_predict_u8(
15799 D45_PRED,
15800 0,
15801 Some(&above),
15802 Some(&left),
15803 Some(128),
15804 side,
15805 side,
15806 false,
15807 false,
15808 &mut prediction, fctx,
15809 );
15810 }
15811 let predict_t = t.elapsed() / N;
15812
15813 eprintln!(
15814 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
15815 predict (1 directional mode): {predict_t:>9.2?}\n\
15816 forward_and_quantize: {forward_t:>9.2?}\n\
15817 dequant_and_inverse: {inverse_t:>9.2?}\n\
15818 coeff_bits: {entropy_t:>9.2?}"
15819 );
15820 }
15821 }
15822
15823 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
15824 /// (motion search, [`crate::mc::predict`], transform+quantize,
15825 /// `coeff_bits`), plus what is left over once those are subtracted --
15826 /// the thirteen-mode intra-candidate loop `search_inter_block` still
15827 /// runs on every inter block (its own transform/quant/entropy calls are
15828 /// already inside buckets 2/3, so "left over" here is everything NOT
15829 /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
15830 /// symbol-cost lookups outside `coeff_bits`).
15831 ///
15832 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
15833 #[test]
15834 #[ignore = "a perf probe, not a gate"]
15835 fn stage_timing_breakdown_inter() {
15836 let _knobs = crate::speed::knob_read();
15837 let fctx = &crate::decode::FrameCtx::for_encoder();
15838 use std::time::Instant;
15839
15840 let (width, height) = (1280usize, 720);
15841 let picture = test_card(width, height);
15842 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15843 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
15844 let padded_pic = picture.padded_to(SUPERBLOCK);
15845
15846 stage_reset();
15847 let t = Instant::now();
15848 let inter =
15849 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();
15850 let total_t = t.elapsed();
15851 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
15852 let accounted = motion_search + transform_quant + entropy;
15853 // motion_search already contains interpolation's own time (every
15854 // candidate the search costs calls crate::mc::predict), so it is not
15855 // added again here -- interpolation is reported alongside as "of
15856 // which interpolation", not as a fifth additive bucket.
15857 let other = total_t.saturating_sub(accounted);
15858
15859 eprintln!(
15860 "\n=== inter frame {width}x{height}, one frame ===\n\
15861 total: {total_t:>9.2?} ({} bytes)\n\
15862 motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
15863 {interpolation:>9.2?})\n\
15864 transform + quantize: {transform_quant:>9.2?}\n\
15865 coeff_bits (entropy pricing): {entropy:>9.2?}\n\
15866 everything else (13-mode intra {other:>9.2?}\n\
15867 candidate loop's own predict/bookkeeping, NEARESTMV's own \
15868 predict, RD glue):",
15869 inter.stream.len(),
15870 );
15871 }
15872
15873 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
15874 /// frames (a dark/flat one, a detailed one, a normal film one) at two
15875 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
15876 /// None`, the baseline this same build produces without
15877 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
15878 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
15879 /// go in the lane report, which is where "ship as default" is decided --
15880 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
15881 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
15882 #[test]
15883 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
15884 fn prune_k_quality_sweep() {
15885 let _knobs = crate::speed::knob_read();
15886 let fctx = &crate::decode::FrameCtx::for_encoder();
15887 if !have_ffmpeg() {
15888 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
15889 return;
15890 }
15891 let (width, height) = (640usize, 352usize);
15892 let frames: &[(&str, &str, &str)] = &[
15893 // (label, clip, seek) -- a near-black scene, a busy one, and an
15894 // ordinary film frame, each from a different real file.
15895 (
15896 "dark/flat",
15897 "/home/user/Videos/reela.mp4",
15898 "3",
15899 ),
15900 (
15901 "detailed",
15902 "/home/user/Downloads/reelb.mkv",
15903 "1200",
15904 ),
15905 (
15906 "film",
15907 "/home/user/Videos/Films/reelc.mkv",
15908 "600",
15909 ),
15910 ];
15911 for &(label, clip, skip) in frames {
15912 if !std::path::Path::new(clip).exists() {
15913 eprintln!("SKIP {label}: {clip} not present on this machine");
15914 continue;
15915 }
15916 let picture = clip_frame(clip, skip, width, height);
15917 for &q in &[60u8, 150] {
15918 // SAFETY (not literally unsafe, just process-global): this is
15919 // a single-threaded #[ignore] probe, run by hand, never
15920 // alongside other tests that read Search::top_k.
15921 set_test_top_k_override(None);
15922 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
15923 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
15924 eprint!(
15925 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
15926 baseline.stream.len(),
15927 baseline_psnr
15928 );
15929 for &k in &[3usize, 4, 6] {
15930 set_test_top_k_override(Some(k));
15931 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
15932 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
15933 eprint!(
15934 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
15935 pruned.stream.len(),
15936 pruned_psnr,
15937 pruned_psnr - baseline_psnr
15938 );
15939 }
15940 eprintln!();
15941 }
15942 }
15943 set_test_top_k_override(None);
15944 }
15945
15946 /// Two consecutive decoded frames from one clip, for an inter-frame
15947 /// sweep -- [`clip_frame`] alone only ever gives one.
15948 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
15949 let out = Command::new("ffmpeg")
15950 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
15951 .args(["-vf", &format!("scale={width}:{height}")])
15952 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
15953 .output()
15954 .expect("ffmpeg failed to run");
15955 assert!(
15956 out.status.success(),
15957 "ffmpeg: {}",
15958 String::from_utf8_lossy(&out.stderr)
15959 );
15960 let (luma, chroma) = (width * height, width * height / 4);
15961 let frame_len = luma + 2 * chroma;
15962 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
15963 std::array::from_fn(|i| {
15964 let bytes = &out.stdout[i * frame_len..][..frame_len];
15965 Picture {
15966 width,
15967 height,
15968 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
15969 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
15970 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
15971 }
15972 })
15973 }
15974
15975 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
15976 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
15977 /// then one inter frame off it (`search_inter_block`'s own intra
15978 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
15979 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
15980 /// padding step complicates the comparison. Prints bytes and luma PSNR
15981 /// for the inter frame alone, unpruned vs each `K`.
15982 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
15983 #[test]
15984 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
15985 fn prune_k_quality_sweep_inter() {
15986 let _knobs = crate::speed::knob_read();
15987 let fctx = &crate::decode::FrameCtx::for_encoder();
15988 if !have_ffmpeg() {
15989 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
15990 return;
15991 }
15992 let (width, height) = (1280usize, 704usize);
15993 let frames: &[(&str, &str, &str)] = &[
15994 (
15995 "dark/flat",
15996 "/home/user/Videos/reela.mp4",
15997 "3",
15998 ),
15999 (
16000 "detailed",
16001 "/home/user/Downloads/reelb.mkv",
16002 "1200",
16003 ),
16004 (
16005 "film",
16006 "/home/user/Videos/Films/reelc.mkv",
16007 "600",
16008 ),
16009 ];
16010 for &(label, clip, skip) in frames {
16011 if !std::path::Path::new(clip).exists() {
16012 eprintln!("SKIP {label}: {clip} not present on this machine");
16013 continue;
16014 }
16015 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
16016 for &q in &[60u8, 150] {
16017 // SAFETY (not literally unsafe, just process-global): a
16018 // single-threaded #[ignore] probe, run by hand, never
16019 // alongside other tests that read Search::top_k.
16020 set_test_top_k_override_inter(None);
16021 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
16022 let baseline = encode_inter_frame(
16023 &inter_source,
16024 &key.reconstruction,
16025 q,
16026 0.5,
16027 1,
16028 flat_order_hints(1, 0, false),
16029 (width, height), None, None, None, None, fctx, None, &[],
16030 )
16031 .unwrap();
16032 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
16033 eprint!(
16034 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
16035 baseline.stream.len(),
16036 baseline_psnr
16037 );
16038 for &k in &[3usize, 4, 6] {
16039 set_test_top_k_override_inter(Some(k));
16040 let pruned = encode_inter_frame(
16041 &inter_source,
16042 &key.reconstruction,
16043 q,
16044 0.5,
16045 1,
16046 flat_order_hints(1, 0, false),
16047 (width, height), None, None, None, None, fctx, None, &[],
16048 )
16049 .unwrap();
16050 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
16051 eprint!(
16052 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
16053 pruned.stream.len(),
16054 pruned_psnr,
16055 pruned_psnr - baseline_psnr
16056 );
16057 }
16058 eprintln!();
16059 }
16060 }
16061 set_test_top_k_override_inter(None);
16062 }
16063
16064 /// `frames` consecutive pictures out of a real clip, scaled to a whole
16065 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
16066 /// to an arbitrary count for the fixture regression gate below.
16067 fn clip_frames(
16068 clip: &str,
16069 skip: &str,
16070 width: usize,
16071 height: usize,
16072 frames: usize,
16073 ) -> Vec<Picture> {
16074 clip_frames_vf(clip, skip, &format!("scale={width}:{height}"), width, height, frames)
16075 }
16076
16077 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
16078 /// for a native-resolution CROP instead of a downscale (the downscale is
16079 /// what destroys a screen capture's exact repeats -- class
16080 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
16081 fn clip_frames_vf(
16082 clip: &str,
16083 skip: &str,
16084 vf: &str,
16085 width: usize,
16086 height: usize,
16087 frames: usize,
16088 ) -> Vec<Picture> {
16089 // ONE definition of the gate's loader recipe, shared with
16090 // `examples/enc_probe` so the instrument cannot arm a different source
16091 // than the gate it reports on (class `instrument disagrees with the
16092 // gate`; lane-probe).
16093 crate::probe::source(clip, skip, vf, width, height, frames)
16094 }
16095
16096 /// The standing regression gate on real content: 12 frames of a real
16097 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
16098 /// this crate's own input regardless of its own source codec), encoded
16099 /// as an AV1 GOP and checked against three numeric floors so a
16100 /// compatibility or quality regression fails the suite instead of
16101 /// waiting for a downstream repo's gate to catch it (as happened for a
16102 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
16103 /// refusal, both caught only that way).
16104 ///
16105 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
16106 /// that geometry is already covered elsewhere), chosen only so encode
16107 /// time and gate numbers are not muddied by an edge-block class this
16108 /// test is not about.
16109 ///
16110 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
16111 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
16112 /// below carry a margin off those measured numbers (PSNR floor =
16113 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
16114 #[test]
16115 fn real_clip_encodes_within_its_quality_and_size_budget() {
16116 let _knobs = crate::speed::knob_read();
16117 let fctx = &crate::decode::FrameCtx::for_encoder();
16118 if !have_ffmpeg() {
16119 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
16120 return;
16121 }
16122 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16123 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
16124 if !clip.exists() {
16125 eprintln!(
16126 "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing",
16127 clip.display()
16128 );
16129 return;
16130 }
16131 let (width, height, frame_count) = (640usize, 384usize, 12usize);
16132 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
16133 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
16134 assert_eq!(encoded.frames.len(), frame_count);
16135
16136 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
16137 // stream and hands back every frame -- a stream a downstream
16138 // decoder refuses is the exact class of regression this gate
16139 // exists for.
16140 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
16141 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
16142
16143 // Gate 2: quality vs the source did not silently collapse.
16144 let mean_psnr: f64 = decoded
16145 .iter()
16146 .zip(&source)
16147 .map(|(d, s)| psnr(&d.y, &s.y))
16148 .sum::<f64>()
16149 / frame_count as f64;
16150 assert!(
16151 mean_psnr >= 44.91,
16152 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
16153 );
16154
16155 // Gate 3: the stream did not silently bloat.
16156 assert!(
16157 encoded.stream.len() <= 80_340,
16158 "stream grew to {} bytes, over the 80340-byte ceiling",
16159 encoded.stream.len()
16160 );
16161 }
16162
16163 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
16164 /// straddle size: 640x384 is exact on both axes (32-aligned), so
16165 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
16166 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
16167 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
16168 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
16169 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
16170 /// card; this one is the real-clip gate, same three floors.
16171 ///
16172 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
16173 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
16174 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
16175 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
16176 #[test]
16177 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
16178 let _knobs = crate::speed::knob_read();
16179 let fctx = &crate::decode::FrameCtx::for_encoder();
16180 if !have_ffmpeg() {
16181 eprintln!(
16182 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
16183 no ffmpeg"
16184 );
16185 return;
16186 }
16187 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16188 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
16189 if !clip.exists() {
16190 eprintln!(
16191 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
16192 {} missing",
16193 clip.display()
16194 );
16195 return;
16196 }
16197 let (width, height, frame_count) = (704usize, 400usize, 8usize);
16198 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
16199 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
16200 assert_eq!(encoded.frames.len(), frame_count);
16201
16202 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
16203 // stream and hands back every frame.
16204 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
16205 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
16206
16207 // Gate 2: quality vs the source did not silently collapse.
16208 let mean_psnr: f64 = decoded
16209 .iter()
16210 .zip(&source)
16211 .map(|(d, s)| psnr(&d.y, &s.y))
16212 .sum::<f64>()
16213 / frame_count as f64;
16214 assert!(
16215 mean_psnr >= 44.98,
16216 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
16217 );
16218
16219 // Gate 3: the stream did not silently bloat.
16220 assert!(
16221 encoded.stream.len() <= 62_703,
16222 "stream grew to {} bytes, over the 62703-byte ceiling",
16223 encoded.stream.len()
16224 );
16225 }
16226
16227 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
16228 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
16229 /// facade -- timed end to end, so the edith export-time projection is a
16230 /// real number rather than a guess from the isolated key/inter numbers
16231 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
16232 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
16233 #[test]
16234 #[ignore = "a perf probe, not a gate"]
16235 fn sequence_bench_sanity() {
16236 let _knobs = crate::speed::knob_read();
16237 let fctx = &crate::decode::FrameCtx::for_encoder();
16238 use std::time::Instant;
16239 let (width, height) = (1280usize, 720usize);
16240 let pictures: Vec<Picture> = (0..24)
16241 .map(|i| panned_test_card(width, height, i * 3))
16242 .collect();
16243 let t = Instant::now();
16244 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16245 let elapsed = t.elapsed();
16246 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
16247 eprintln!(
16248 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
16249 elapsed / 24
16250 );
16251 }
16252
16253 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
16254 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
16255 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
16256 /// -- --ignored --nocapture`.
16257 #[test]
16258 #[ignore = "a calibration probe, not a gate"]
16259 fn calibration_sweep_base_q_idx() {
16260 let _knobs = crate::speed::knob_read();
16261 let fctx = &crate::decode::FrameCtx::for_encoder();
16262 if !have_ffmpeg() {
16263 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
16264 return;
16265 }
16266 let (width, height, frames) = (640usize, 384usize, 12usize);
16267 for clip in [
16268 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
16269 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
16270 ] {
16271 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16272 .join("../../fixtures/video")
16273 .join(clip);
16274 if !path.exists() {
16275 eprintln!("SKIP {clip}: fixture missing");
16276 continue;
16277 }
16278 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
16279 eprintln!("--- {clip} ---");
16280 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
16281 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
16282 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
16283 let mean_psnr: f64 = decoded
16284 .iter()
16285 .zip(&source)
16286 .map(|(d, s)| psnr(&d.y, &s.y))
16287 .sum::<f64>()
16288 / frames as f64;
16289 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
16290 eprintln!(
16291 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
16292 encoded.stream.len()
16293 );
16294 }
16295 }
16296 }
16297
16298 // -----------------------------------------------------------------------
16299 // The encoder's standing BD-rate baseline against libaom and rav1e.
16300 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
16301 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
16302 // agreeing with our encoder proves nothing about the bitstream.
16303 // -----------------------------------------------------------------------
16304
16305 /// All-plane PSNR of a decoded picture against its source, on the same
16306 /// 8-bit scale [`psnr`] uses.
16307 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
16308 let cat = |p: &Picture| {
16309 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
16310 v.extend_from_slice(&p.y);
16311 v.extend_from_slice(&p.u);
16312 v.extend_from_slice(&p.v);
16313 v
16314 };
16315 psnr(&cat(decoded), &cat(source))
16316 }
16317
16318 /// The pictures back as the planar 8-bit bytes an encoder reads.
16319 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
16320 let mut raw = Vec::new();
16321 for p in source {
16322 for plane in [&p.y, &p.u, &p.v] {
16323 raw.extend(plane.iter().map(|&s| s as u8));
16324 }
16325 }
16326 raw
16327 }
16328
16329 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
16330 /// through ffmpeg: one point per entry of `points`, each a quality flag
16331 /// set. Returns the ladder ordered by fidelity and the total encode wall
16332 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
16333 /// so both curves are measured by the same decoder.
16334 fn external_ladder(
16335 source: &[Picture],
16336 width: usize,
16337 height: usize,
16338 encoder: &str,
16339 points: &[Vec<String>],
16340 ) -> (Vec<(f64, f64)>, f64) {
16341 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
16342 let dir = std::env::temp_dir();
16343 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
16344 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
16345 let mut ladder = Vec::new();
16346 let mut wall = 0.0;
16347 for (i, params) in points.iter().enumerate() {
16348 let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id()));
16349 let start = std::time::Instant::now();
16350 let out = Command::new("ffmpeg")
16351 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
16352 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
16353 .arg(&raw_path)
16354 .args(["-an", "-threads", "1"])
16355 .args(["-g", &source.len().to_string(), "-c:v", encoder])
16356 .args(params)
16357 .args(["-f", "obu"])
16358 .arg(&obu)
16359 .output()
16360 .expect("ffmpeg failed to run");
16361 wall += start.elapsed().as_secs_f64();
16362 assert!(
16363 out.status.success(),
16364 "{encoder} {params:?}: {}",
16365 String::from_utf8_lossy(&out.stderr)
16366 );
16367 let stream = std::fs::read(&obu).expect("reference stream");
16368 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
16369 // lane-dkey: every reference point must also decode through OUR
16370 // decoder, sample-exact against ffmpeg's decode of the same bytes.
16371 // A BD table computed off streams we cannot read is a table about
16372 // an encoder we cannot check; this is the assertion that would
16373 // have caught the `force_integer_mv` defect (its stream decoded to
16374 // 25 dB garbage while this gate stayed green) and the crf-5 key
16375 // frame desync. A failure names the encoder, the point's flags and
16376 // the first differing frame/plane/sample.
16377 // lane-dpm1: a failing reference point is COLLECTED, not panicked
16378 // on, so one run still prints the whole BD table and names every
16379 // bad point instead of stopping at the first. The collection is
16380 // asserted empty by [`assert_ladder_decodes`] at the end of each
16381 // gate.
16382 match crate::stream::decode_stream(&stream) {
16383 Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
16384 "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
16385 ours.len(),
16386 decoded.len(),
16387 )),
16388 Ok(ours) => {
16389 for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
16390 if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
16391 note_ladder_failure(format!(
16392 "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
16393 decoder decoded {got}, ffmpeg {want}"
16394 ));
16395 break;
16396 }
16397 }
16398 }
16399 Err(e) => note_ladder_failure(format!(
16400 "{encoder} {params:?}: our decoder refused the stream ({e})"
16401 )),
16402 }
16403 let mean: f64 = decoded
16404 .iter()
16405 .zip(source)
16406 .map(|(d, s)| psnr_all(d, s))
16407 .sum::<f64>()
16408 / source.len() as f64;
16409 ladder.push((mean, (stream.len() as f64).log10()));
16410 let _ = std::fs::remove_file(&obu);
16411 }
16412 let _ = std::fs::remove_file(&raw_path);
16413 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
16414 (ladder, wall)
16415 }
16416
16417 /// Every reference ladder point that did not decode sample-exactly
16418 /// through our own decoder, collected across a whole gate run so the BD
16419 /// table still prints and EVERY bad point is named
16420 /// (`encoder params frame plane sample`) instead of only the first.
16421 static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
16422
16423 fn note_ladder_failure(msg: String) {
16424 eprintln!("LADDER DECODE FAILURE: {msg}");
16425 LADDER_FAILURES.lock().expect("ladder failures").push(msg);
16426 }
16427
16428 /// Fail the gate at its END on everything [`external_ladder`] collected.
16429 fn assert_ladder_decodes() {
16430 let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
16431 assert!(
16432 failures.is_empty(),
16433 "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
16434 failures.len(),
16435 failures.join("\n"),
16436 );
16437 }
16438
16439 /// First differing sample between two pictures, as
16440 /// `(plane, index, left, right)` -- so a gate failure names the plane and
16441 /// the sample instead of just "differs". A length difference counts as a
16442 /// mismatch of that plane at the first index past the shorter one.
16443 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
16444 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
16445 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
16446 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
16447 }
16448 if l.len() != r.len() {
16449 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
16450 }
16451 }
16452 None
16453 }
16454
16455 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
16456 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
16457 /// stream is decoded twice -- by ffmpeg and by our own
16458 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
16459 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
16460 /// in Y, U and V over every shown frame in display order. That is itself
16461 /// a gate: it proves the bitstream says what the encoder thinks, in the
16462 /// only two decoders that read it.
16463 fn our_ladder(
16464 name: &str,
16465 source: &[Picture],
16466 width: usize,
16467 height: usize,
16468 fctx: &crate::decode::FrameCtx,
16469 ) -> (Vec<(f64, f64)>, f64) {
16470 let mut ladder = Vec::new();
16471 let mut wall = 0.0;
16472 for &q in &[150u8, 120, 90, 60] {
16473 let start = std::time::Instant::now();
16474 // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
16475 // the gate has to be able to re-sweep it. 0.5 is the shipped one
16476 // (`crate::encoder::DEADZONE`).
16477 let deadzone = std::env::var("EC_AV1_DEADZONE")
16478 .ok()
16479 .and_then(|v| v.parse().ok())
16480 .unwrap_or(0.5);
16481 let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
16482 wall += start.elapsed().as_secs_f64();
16483 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
16484 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
16485 assert_eq!(
16486 ours.len(),
16487 source.len(),
16488 "{name} q={q}: our decoder's display-order frame count"
16489 );
16490 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
16491 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
16492 panic!(
16493 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
16494 {got}, the encoder reconstructed {want}"
16495 );
16496 }
16497 }
16498 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
16499 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
16500 panic!(
16501 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
16502 {got}, the encoder reconstructed {want}"
16503 );
16504 }
16505 }
16506 let per_frame: Vec<f64> = decoded.iter().zip(source).map(|(d, s)| psnr_all(d, s)).collect();
16507 // lane-txrd: does a tool's loss start at the FIRST inter frame
16508 // (a local mispricing) or grow down the GOP (propagation into
16509 // the reference chain)? One line per q point answers it.
16510 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
16511 let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect();
16512 eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" "));
16513 // lane-txrd: per PLANE, because an all-plane mean hides a
16514 // collapse in one of them (class `metric blind to a plane`).
16515 let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String {
16516 let v: Vec<String> = decoded
16517 .iter()
16518 .zip(source)
16519 .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s))))
16520 .collect();
16521 v.join(" ")
16522 };
16523 eprintln!("{name}: q={q} Y {}", plane(|p| &p.y));
16524 eprintln!("{name}: q={q} U {}", plane(|p| &p.u));
16525 eprintln!("{name}: q={q} V {}", plane(|p| &p.v));
16526 }
16527 let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64;
16528 ladder.push((mean, (encoded.stream.len() as f64).log10()));
16529 }
16530 // What this clip asked for and what the content gate left it coding
16531 // under: a screen clip requests a pyramid and codes flat, and that
16532 // difference is what keeps its row identical to the flat baseline
16533 // (class `gate-blind-to-feature`).
16534 eprintln!(
16535 "{name}: sequence, pyramid requested {:?} effective {:?}",
16536 crate::encoder::Pyramid::from_env(),
16537 last_sequence_pyramid(),
16538 );
16539 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
16540 (ladder, wall)
16541 }
16542
16543 /// [`our_ladder`] through the streaming facade — the surface the editor's
16544 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
16545 /// each stream is also reordered (hidden `ALTREF` first,
16546 /// `show_existing_frame` last per group) and each level is coded at its
16547 /// own quantizer offset; without one it is the flat ladder, which
16548 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
16549 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
16550 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
16551 /// the whole ladder how many frames and how many bytes it spent, and the
16552 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
16553 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
16554 /// flat path, so a requested pyramid can come back `None` here.
16555 fn our_ladder_facade(
16556 name: &str,
16557 source: &[Picture],
16558 width: usize,
16559 height: usize,
16560 pyramid: Option<crate::encoder::Pyramid>,
16561 ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4], Option<crate::encoder::Pyramid>) {
16562 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
16563 let slot = |l: Level| match l {
16564 Level::Key => 0,
16565 Level::Arf => 1,
16566 Level::Leaf => 2,
16567 Level::ShowExisting => 3,
16568 };
16569 let mut ladder = Vec::new();
16570 let mut wall = 0.0;
16571 let mut effective = None;
16572 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
16573 for &q in &[150u8, 120, 90, 60] {
16574 let config = EncoderConfig {
16575 width,
16576 height,
16577 base_q_idx: q,
16578 gop: source.len(),
16579 colour: Colour::Unspecified,
16580 tile_cols_log2: 0,
16581 tile_rows_log2: 0,
16582 };
16583 let start = std::time::Instant::now();
16584 let mut enc = match pyramid {
16585 None => Av1Encoder::new(config).unwrap(),
16586 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
16587 };
16588 let mut packets = Vec::new();
16589 for picture in source {
16590 packets.extend(enc.encode_frames(picture).unwrap());
16591 }
16592 packets.extend(enc.flush().unwrap());
16593 wall += start.elapsed().as_secs_f64();
16594 effective = enc.pyramid();
16595 let mut stream = Vec::new();
16596 for p in &packets {
16597 counts[slot(p.level)] += 1;
16598 bytes[slot(p.level)] += p.data.len();
16599 stream.extend_from_slice(&p.data);
16600 }
16601 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
16602 // correct if the DISPLAY-order output still has one frame per
16603 // source picture, in the right order -- checked against our own
16604 // decoder as well as ffmpeg's, both below.
16605 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
16606 assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count");
16607 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
16608 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
16609 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
16610 panic!(
16611 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
16612 decoded {got}, our decoder decoded {want}"
16613 );
16614 }
16615 }
16616 let mean: f64 = decoded
16617 .iter()
16618 .zip(source)
16619 .map(|(d, s)| psnr_all(d, s))
16620 .sum::<f64>()
16621 / source.len() as f64;
16622 ladder.push((mean, (stream.len() as f64).log10()));
16623 }
16624 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
16625 (ladder, wall, counts, bytes, effective)
16626 }
16627
16628 /// Byte-exactness gate for encoder work that is meant to change only
16629 /// how long the encoder takes.
16630 ///
16631 /// The BD gate above measures quality, which a speed lane can move by a
16632 /// hair without failing anything; this pins the streams themselves.
16633 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
16634 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
16635 /// in the tile) and again on lane-av1mv's merge of it: an extra
16636 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
16637 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
16638 /// prices coefficients against the tables the frame's writer really
16639 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
16640 /// decision change the BD gate judges. Re-pinned again on
16641 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
16642 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
16643 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
16644 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
16645 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
16646 /// by default ([`warp_on`], a sequence/frame header bit and a new
16647 /// motion_mode symbol on eligible blocks) and
16648 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
16649 /// every inter frame's superblocks now code at their own lambda
16650 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
16651 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
16652 /// and the two var-tx depth searches ([`tx32_depth_search`],
16653 /// [`compound_var_tx`]) are on by default, all three re-judged on the
16654 /// native gate's real film rows.
16655 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
16656 /// every block whose chroma takes it codes a different mode symbol, two
16657 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
16658 /// restores the previous streams. Re-pinned again in the same lane once
16659 /// directional luma winners searched their `angle_delta_y`
16660 /// (`EC_AV1_ANGLE=0` restores that half).
16661 #[test]
16662 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
16663 // These are DEFAULT-PRESET pins: a speed preset switches search levers
16664 // off, so it legitimately moves every byte. Encode at speed 0 whatever
16665 // `EC_AV1_SPEED` says (write guard: the preset is process-global).
16666 let _knobs = crate::speed::knob_write();
16667 let was = crate::speed::speed();
16668 crate::speed::set_speed(0);
16669 if !have_ffmpeg() {
16670 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
16671 return;
16672 }
16673 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
16674 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
16675 if !clip.exists() {
16676 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip");
16677 return;
16678 }
16679 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
16680 // FNV-1a over the stream: a witness that every coded bit is where it
16681 // was, which a byte count alone is not.
16682 let fnv = |b: &[u8]| {
16683 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
16684 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
16685 })
16686 };
16687 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
16688 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
16689 // of 4, its leaves at q+8 and a `show_existing_frame` header per
16690 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
16691 // four frames; four pictures is one short mini-GOP, which is the
16692 // shape that pays least (the ARF's own quality has no later group to
16693 // carry it), so this is not the BD gate's number.
16694 // Re-taken again on lane-av1cfl: the chroma search offers
16695 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
16696 // so every block taking either codes different syntax and different
16697 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
16698 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
16699 // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
16700 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
16701 // so these four pictures code as one truncated group -- a hidden
16702 // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
16703 // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
16704 // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
16705 // Re-taken on lane-fintra: the sequence header sets
16706 // `enable_filter_intra`, so every DC_PRED intra block of at most
16707 // 32x32 without a luma palette carries a `use_filter_intra` flag and
16708 // the blocks that take one code a filter-intra mode, a different
16709 // prediction and different coefficients -- 7321 -> 7373 at q=150 and
16710 // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
16711 // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
16712 // (default pyramid `8:-32:16`, one truncated group of 8 with its
16713 // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
16714 // root can code a REAL residual now (one TX_64X64 luma transform and
16715 // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
16716 // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
16717 // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
16718 // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
16719 // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
16720 // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
16721 // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
16722 // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
16723 // -> 9835 at q=150 and 35450 -> 35798 at q=60.
16724 // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
16725 // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
16726 // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
16727 // these four pictures -- offers every superblock a 64x64 intra root
16728 // now. `EC_AV1_I64=0` restores 8557 / 33345.
16729 // Re-taken on lane-pricer: the inter RD search prices a single
16730 // reference through the tree and the neighbour contexts the writer
16731 // really codes it with, so every inter picture's reference decisions
16732 // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
16733 // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
16734 // for `skip`/`is_inter` and for the whole compound reference tree, so
16735 // every inter block's cost -- and with it the skip and reference
16736 // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
16737 // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
16738 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
16739 // single and compound are priced against the same syntax -- 8311 ->
16740 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
16741 // Re-taken on lane-newmv: the motion search charges its own rate term
16742 // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
16743 // and each subpel stage re-runs from its own winner
16744 // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
16745 // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
16746 // and 33014 -> 33090 at q=60.
16747 // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
16748 // from libaom's objective tpl mapping, so every inter picture's
16749 // quantizer grid -- and every decision priced against it -- moved
16750 // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
16751 // at the merge of both lanes.
16752 let pins: [(u8, usize, u64); 2] = [(150, 8252, 0x5b6e40a2b5498988), (60, 33053, 0x9a0abfc234eccc37)];
16753 let coded: Vec<(u8, usize, u64)> = pins
16754 .iter()
16755 .map(|&(q, _, _)| {
16756 let e = encode_sequence(&source, q, 0.5).unwrap();
16757 (q, e.stream.len(), fnv(&e.stream))
16758 })
16759 .collect();
16760 crate::speed::set_speed(was);
16761 for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
16762 assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
16763 }
16764 }
16765
16766 /// A ladder is only a ladder if both axes rise together.
16767 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
16768 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
16769 for w in ladder.windows(2) {
16770 assert!(
16771 w[1].0 > w[0].0 && w[1].1 > w[0].1,
16772 "{name}: not monotone, {ladder:?}"
16773 );
16774 }
16775 }
16776
16777 /// The sweep behind [`screen_content`]'s constants
16778 /// (`unswept-decision-constants`), on the SAME five clips
16779 /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
16780 /// same native crop: for each colour bound N the share of 16x16 luma
16781 /// blocks with 2..=N distinct colours, and the share of those whose
16782 /// per-pixel variance also clears a floor V -- libaom's
16783 /// `av1_set_screen_content_options` counts the variance-cleared blocks
16784 /// too (its `counts_2`, which gates intrabc), and without that term a
16785 /// smooth dark film frame reads as screen content.
16786 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
16787 #[test]
16788 #[ignore = "reads the real library"]
16789 fn probe_screen_detect() {
16790 let _knobs = crate::speed::knob_read();
16791 if !have_ffmpeg() {
16792 eprintln!("SKIP probe_screen_detect: no ffmpeg");
16793 return;
16794 }
16795 let limits = [4usize, 8, 16, 32, 64, 128];
16796 let floors = [0u64, 4, 16, 64, 256];
16797 // The census of one clip at one size: mean share, over the frames, of
16798 // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
16799 let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
16800 let mut acc = [[0f64; 5]; 6];
16801 for picture in frames {
16802 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
16803 let mut hit = [[0usize; 5]; 6];
16804 let mut blocks = 0usize;
16805 for by in (0..ch).step_by(16) {
16806 for bx in (0..cw).step_by(16) {
16807 let mut seen = [false; 256];
16808 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
16809 for row in 0..16 {
16810 for col in 0..16 {
16811 let v = y[(by + row) * cw + bx + col];
16812 sum += u64::from(v);
16813 sq += u64::from(v) * u64::from(v);
16814 if !seen[usize::from(v)] {
16815 seen[usize::from(v)] = true;
16816 colors += 1;
16817 }
16818 }
16819 }
16820 let var = (sq - sum * sum / 256) / 256;
16821 blocks += 1;
16822 for (li, &limit) in limits.iter().enumerate() {
16823 if colors > 1 && colors <= limit {
16824 for (fi, &floor) in floors.iter().enumerate() {
16825 hit[li][fi] += usize::from(var > floor);
16826 }
16827 }
16828 }
16829 }
16830 }
16831 for li in 0..6 {
16832 for fi in 0..5 {
16833 acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
16834 }
16835 }
16836 }
16837 let n = frames.len().max(1) as f64;
16838 eprintln!("{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:", frames.len());
16839 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{f:>8}")).collect::<String>());
16840 for (li, &limit) in limits.iter().enumerate() {
16841 eprintln!(
16842 " {limit:>5} |{}",
16843 (0..5).map(|fi| format!("{:>7.1}%", acc[li][fi] / n)).collect::<String>()
16844 );
16845 }
16846 };
16847 for (name, path, seek) in native_gate_clips() {
16848 let Some((nw, nh)) = probe_dims(&path) else {
16849 eprintln!("SKIP {name}: ffprobe gave no size");
16850 continue;
16851 };
16852 let cw = nw.min(1920) / 128 * 128;
16853 let ch = nh.min(1024) / 128 * 128;
16854 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
16855 let frames = clip_frames_vf(&path, &seek, &format!("crop={cw}:{ch}:{x}:{y0}"), cw, ch, 12);
16856 census(&name, &frames, cw, ch);
16857 // The 640x384 gate scales instead of cropping, and the scaling
16858 // changes the census (bars smooth out): the constants have to
16859 // separate at BOTH sizes.
16860 let small = clip_frames(&path, &seek, 640, 384, 12);
16861 census(&name, &small, 640, 384);
16862 }
16863 }
16864
16865 /// The detector against the WHOLE real library (class
16866 /// `unswept-decision-constants`, user rule "his data is the gate"):
16867 /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
16868 /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
16869 /// duration, four frames each, 8-bit 4:2:0, at native size or a
16870 /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
16871 /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
16872 /// Prints per file and offset the share of qualifying 16x16 blocks, the
16873 /// [`screen_content`] verdict and a content hint (mean luma, luma
16874 /// standard deviation, inter MAD), then sweeps the colour bound against
16875 /// the variance floor over the whole library: for each (N, V) the worst
16876 /// (highest) share among the camera/film rows against the best (lowest)
16877 /// among the screen-recording rows, so the rule with the widest gap can
16878 /// be read off. Rows carry the manifest index, codec and size only --
16879 /// no titles, no home paths.
16880 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
16881 #[test]
16882 #[ignore = "reads the real library"]
16883 fn probe_screen_library() {
16884 let _knobs = crate::speed::knob_read();
16885 if !have_ffmpeg() {
16886 eprintln!("SKIP probe_screen_library: no ffmpeg");
16887 return;
16888 }
16889 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
16890 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
16891 eprintln!("SKIP probe_screen_library: no real-library manifest");
16892 return;
16893 };
16894 let limits = [4usize, 8, 16, 32, 64];
16895 let floors = [0u64, 4, 8, 16, 32, 64, 128];
16896 // Whatever ffmpeg gave us, without the exact-count assertion the
16897 // gate loaders make: a seek near the end of a clip returns fewer
16898 // frames, and that is a row to print, not a panic.
16899 let decode = |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
16900 let out = Command::new("ffmpeg")
16901 .args(["-v", "error", "-ss", seek, "-i", clip])
16902 .args(["-frames:v", &n.to_string()])
16903 .args(["-vf", vf])
16904 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
16905 .output();
16906 let Ok(out) = out else { return Vec::new() };
16907 if !out.status.success() {
16908 return Vec::new();
16909 }
16910 let (luma, chroma) = (w * h, w * h / 4);
16911 let frame_len = luma + 2 * chroma;
16912 (0..out.stdout.len() / frame_len)
16913 .map(|i| {
16914 let b = &out.stdout[i * frame_len..][..frame_len];
16915 Picture {
16916 width: w,
16917 height: h,
16918 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
16919 u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
16920 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
16921 }
16922 })
16923 .collect()
16924 };
16925 // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
16926 // variance > V, for every (N, V) of the sweep grid, over one frame.
16927 let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
16928 let mut hit = [[0usize; 7]; 5];
16929 let mut blocks = 0usize;
16930 for by in (0..h).step_by(16) {
16931 for bx in (0..w).step_by(16) {
16932 let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
16933 let mut seen = [false; 256];
16934 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
16935 for row in 0..bh {
16936 for col in 0..bw {
16937 let v = y[(by + row) * w + bx + col];
16938 sum += u64::from(v);
16939 sq += u64::from(v) * u64::from(v);
16940 if !seen[usize::from(v)] {
16941 seen[usize::from(v)] = true;
16942 colors += 1;
16943 }
16944 }
16945 }
16946 let n = (bh * bw) as u64;
16947 let var = (sq - sum * sum / n) / n;
16948 blocks += 1;
16949 for (li, &limit) in limits.iter().enumerate() {
16950 if colors > 1 && colors <= limit {
16951 for (fi, &floor) in floors.iter().enumerate() {
16952 hit[li][fi] += usize::from(var > floor);
16953 }
16954 }
16955 }
16956 }
16957 }
16958 let mut out = [[0f64; 7]; 5];
16959 for li in 0..5 {
16960 for fi in 0..7 {
16961 out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
16962 }
16963 }
16964 out
16965 };
16966 // (index, label, path, duration, screen-by-its-own-content). The
16967 // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
16968 // are desktop recordings; everything else in this library is camera
16969 // or film material.
16970 let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
16971 for (label, file) in [("bars 1080p", "h264-1080p-23.976-8bit.mp4"), ("bars 2160p", "h264-2160p-23.976-8bit.mp4")] {
16972 let path = fixtures.join("video").join(file);
16973 if path.exists() {
16974 rows.push(("fx".into(), label.into(), path.to_str().unwrap().into(), 10.0, false));
16975 }
16976 }
16977 for (i, line) in manifest.lines().skip(1).enumerate() {
16978 let f: Vec<&str> = line.split('\t').collect();
16979 if f.len() < 10 {
16980 continue;
16981 }
16982 let (path, codec) = (f[0], f[2]);
16983 if codec == "-" || codec.is_empty() {
16984 continue;
16985 }
16986 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
16987 eprintln!("SKIP {}: manifest carries no coded size", i + 1);
16988 continue;
16989 };
16990 if !std::path::Path::new(path).exists() {
16991 eprintln!("SKIP {}: file is gone", i + 1);
16992 continue;
16993 }
16994 let name = path.rsplit('/').next().unwrap_or(path);
16995 let is_capture = path.contains("/OBS/")
16996 || (name.len() > 19
16997 && name.as_bytes()[4] == b'-'
16998 && name.as_bytes()[7] == b'-'
16999 && name.as_bytes()[10] == b' '
17000 && name.as_bytes()[13] == b'-');
17001 rows.push((
17002 format!("{}", i + 1),
17003 format!("{codec} {w}x{h}"),
17004 path.to_string(),
17005 f[8].parse::<f64>().unwrap_or(0.0),
17006 is_capture,
17007 ));
17008 }
17009 // Per (N, V): the worst camera/film row and the best screen row, so
17010 // the separation of the whole library is one subtraction.
17011 let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
17012 eprintln!("| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |");
17013 for (idx, label, path, dur, is_capture) in &rows {
17014 let Some((nw, nh)) = probe_dims(path) else {
17015 eprintln!("SKIP {idx}: ffprobe gave no size");
17016 continue;
17017 };
17018 let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
17019 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
17020 let vf = format!("crop={cw}:{ch}:{x}:{y0}");
17021 let mut file_grid = [[0f64; 7]; 5];
17022 let mut file_frames = 0usize;
17023 for pct in [10u32, 50, 90] {
17024 let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
17025 let frames = decode(path, &seek, &vf, cw, ch, 4);
17026 if frames.is_empty() {
17027 eprintln!("| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |", if *is_capture { "screen" } else { "camera" });
17028 continue;
17029 }
17030 let (mut share, mut yes, mut mean, mut sd, mut mad) = (0f64, 0usize, 0f64, 0f64, 0f64);
17031 let mut prev: Option<Vec<u8>> = None;
17032 for picture in &frames {
17033 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
17034 let grid = census(&y, cw, ch);
17035 for li in 0..5 {
17036 for fi in 0..7 {
17037 file_grid[li][fi] += grid[li][fi];
17038 }
17039 }
17040 file_frames += 1;
17041 // The shipped rule is (16 colours, var > 16): grid row 2,
17042 // floor 16 is column 3.
17043 share += grid[2][3];
17044 yes += usize::from(screen_content(&y, cw, cw, ch));
17045 let n = y.len() as f64;
17046 let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
17047 let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
17048 mean += sum / n;
17049 sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
17050 if let Some(p) = &prev {
17051 mad += p.iter().zip(&y).map(|(&a, &b)| f64::from(a.abs_diff(b))).sum::<f64>() / n;
17052 }
17053 prev = Some(y);
17054 }
17055 let f = frames.len() as f64;
17056 eprintln!(
17057 "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
17058 if *is_capture { "screen" } else { "camera" },
17059 share / f,
17060 if yes * 2 > frames.len() { "SCREEN" } else { "camera" },
17061 frames.len(),
17062 mean / f,
17063 sd / f,
17064 mad / (f - 1.0).max(1.0),
17065 );
17066 }
17067 if file_frames == 0 {
17068 continue;
17069 }
17070 for li in 0..5 {
17071 for fi in 0..7 {
17072 let s = file_grid[li][fi] / file_frames as f64;
17073 match is_capture {
17074 true => scr_min[li][fi] = scr_min[li][fi].min(s),
17075 false => cam_max[li][fi] = cam_max[li][fi].max(s),
17076 }
17077 }
17078 }
17079 }
17080 eprintln!("sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):");
17081 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{:>18}", format!("V>{f}"))).collect::<String>());
17082 let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
17083 for (li, &limit) in limits.iter().enumerate() {
17084 let mut row = String::new();
17085 for fi in 0..7 {
17086 let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
17087 row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
17088 if s - c > best {
17089 best = s - c;
17090 best_rule = (limit, floors[fi]);
17091 }
17092 }
17093 eprintln!(" {limit:>5} |{row}");
17094 }
17095 // The threshold sits at the midpoint of the widest gap; the shipped
17096 // constant is its reciprocal in whole parts of the frame.
17097 let (li, fi) = (
17098 limits.iter().position(|&l| l == best_rule.0).unwrap(),
17099 floors.iter().position(|&f| f == best_rule.1).unwrap(),
17100 );
17101 let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
17102 eprintln!(
17103 "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
17104 best_rule.0,
17105 best_rule.1,
17106 best,
17107 cam_max[li][fi],
17108 scr_min[li][fi],
17109 mid,
17110 (100.0 / mid.max(0.1)).round() as usize,
17111 );
17112 }
17113
17114 /// The missing instrument: what this encoder costs against libaom and
17115 /// rav1e at matched fidelity, and how long it takes to get there.
17116 ///
17117 /// Recipe, identical on all three sides: 12 consecutive frames of each
17118 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
17119 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
17120 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
17121 /// it by default), 4:2:0 8-bit in and out. Reference points:
17122 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
17123 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
17124 /// tile_cols=1:tile_rows=1:threads=1`
17125 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
17126 /// ffmpeg-decoded frames of each encoder's own stream.
17127 ///
17128 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
17129 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
17130 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
17131 /// four encodes of that ladder together):
17132 ///
17133 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
17134 /// |---|---|---|---|---|
17135 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
17136 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
17137 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
17138 ///
17139 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
17140 /// the encoder takes -- every stream it writes is byte-identical, so the
17141 /// BD columns are this box's own re-run of the same recipe rather than a
17142 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
17143 /// rav1e). What moved is the wall of the four encodes:
17144 ///
17145 /// | clip | wall ours before | after | instructions:u before -> after |
17146 /// |---|---|---|---|
17147 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
17148 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
17149 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
17150 ///
17151 /// Three exact steps, none of which touches a coded bit: the coefficient
17152 /// rate pricer stopped rebuilding every CDF table per candidate
17153 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
17154 /// tile once per candidate (`decode::FilterReplay`), and the forward
17155 /// transform stopped transforming the all-zero residual that 70% of its
17156 /// calls carry.
17157 ///
17158 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
17159 ///
17160 /// | step | 1080p | 2160p | screen |
17161 /// |---|---|---|---|
17162 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
17163 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
17164 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
17165 ///
17166 /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
17167 /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
17168 /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
17169 /// -- all three decided on the REAL film rows of
17170 /// [`bd_rate_screen_native`], which this downscaled recipe does not
17171 /// carry:
17172 ///
17173 /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
17174 /// |---|---|---|---|
17175 /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
17176 /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
17177 /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
17178 ///
17179 /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
17180 /// DEFAULT of the sequence path this gate codes through -- the bars are
17181 /// non-screen so they take it, the capture is gated flat:
17182 ///
17183 /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
17184 /// |---|---|---|---|---|
17185 /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
17186 /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
17187 /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
17188 ///
17189 /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
17190 /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
17191 /// facade arm -- which is what "one mini-GOP driver, two entry points"
17192 /// means here. This downscaled recipe HATES the pyramid (as it hates
17193 /// every knob the real film rows of `bd_rate_screen_native` keep, which
17194 /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
17195 /// above. The capture's row is the flat row to the byte in both runs --
17196 /// that equality IS the content gate.
17197 ///
17198 /// Loop restoration is NOT in yet: it is the one filter whose parameters
17199 /// are per restoration UNIT inside the tile payload, so it needs both
17200 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
17201 /// buffer to solve against -- neither of which this frame-header-level
17202 /// search reaches.
17203 ///
17204 /// The baseline it replaced, before an inter frame's blocks chose their
17205 /// own partition, was +501.4/+504.4/+440.9 against libaom and
17206 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
17207 ///
17208 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
17209 /// fidelity, while spending far more time than either (the partition
17210 /// search's own cost, uncut: see the two intra-pruning variants measured
17211 /// and rejected in the lane report). No
17212 /// threshold is asserted yet -- this run sets the baseline; the gate
17213 /// asserts four monotone points per ladder, and at EVERY ladder point of
17214 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
17215 /// `crate::stream::decode_stream` -- and asserts the encoder's
17216 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
17217 /// and V over every shown frame in display order. A failure names the
17218 /// clip, the q, the frame, the plane and the first differing sample.
17219 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
17220 /// which exposes no per-packet reconstruction, so that path asserts the
17221 /// two decoders against each other on all three planes.)
17222 ///
17223 /// Run:
17224 /// cargo test -p ec-av1 --release --lib -- --ignored \
17225 /// bd_rate_vs_libaom_and_rav1e --nocapture
17226 #[test]
17227 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
17228 fn bd_rate_vs_libaom_and_rav1e() {
17229 let _knobs = crate::speed::knob_write();
17230 if !have_ffmpeg() {
17231 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
17232 return;
17233 }
17234 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
17235 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
17236 // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
17237 // rows for real content (the real rows live in the native gate).
17238 for (label, name) in [
17239 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
17240 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
17241 ] {
17242 let path = fixtures.join("video").join(name);
17243 if path.exists() {
17244 clips.push((label.to_string(), path));
17245 } else {
17246 eprintln!("SKIP clip {name}: missing");
17247 }
17248 }
17249 // Screen capture: the repo carries no screen-capture fixture, so take
17250 // the first OBS recording the real-library manifest names.
17251 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
17252 Ok(manifest) => {
17253 let screen = manifest
17254 .lines()
17255 .skip(1)
17256 .filter_map(|l| l.split('\t').next())
17257 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists());
17258 match screen {
17259 Some(p) => clips.push((
17260 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
17261 std::path::PathBuf::from(p),
17262 )),
17263 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
17264 }
17265 }
17266 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
17267 }
17268 assert!(!clips.is_empty(), "no source clip available");
17269
17270 let (width, height, frames) = (640usize, 384usize, 12usize);
17271 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
17272 .iter()
17273 .map(|q| {
17274 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
17275 .map(String::from)
17276 .to_vec()
17277 })
17278 .collect();
17279 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
17280 .iter()
17281 .map(|q| {
17282 vec![
17283 "-rav1e-params".to_string(),
17284 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
17285 ]
17286 })
17287 .collect();
17288 println!(
17289 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
17290 );
17291 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |");
17292 println!("|---|---|---|---|---|");
17293 for (name, path) in &clips {
17294 let fctx = &crate::decode::FrameCtx::for_encoder();
17295 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
17296 let _ = take_partition_hits();
17297 let _ = crate::tile::take_palette_hits();
17298 SCREEN_FRAMES.iter().for_each(|c| {
17299 c.store(0, std::sync::atomic::Ordering::Relaxed);
17300 });
17301 let _ = take_uv_mode_hits();
17302 let _ = crate::tile::take_inter_mode_hits();
17303 let _ = crate::tile::take_drl_hits();
17304 let _ = crate::tile::take_ref_hits();
17305 let _ = crate::tile::take_compound_mode_hits();
17306 let _ = crate::tile::take_compound_pair_hits();
17307 let _ = crate::tile::take_compound_size_hits();
17308 let _ = crate::tile::take_compound_leaf_mode_hits();
17309 let _ = take_b64_root_hits();
17310 let _ = take_b64_residual_hits();
17311 let _ = take_b64_compound_hits();
17312 let _ = crate::motion::take_census();
17313 // The entry-surface arm: run the SAME ladder through the
17314 // streaming facade the editor's export calls, which must print
17315 // the same BD numbers as the sequence path -- byte for byte the
17316 // same stream now that both drive one mini-GOP driver
17317 // (lane-av1pyrdef).
17318 let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
17319 let (ours, ours_wall) = match facade {
17320 false => our_ladder(name, &source, width, height, fctx),
17321 true => {
17322 let pyramid = crate::encoder::Pyramid::from_env();
17323 let (ladder, wall, counts, bytes, effective) =
17324 our_ladder_facade(name, &source, width, height, pyramid);
17325 eprintln!(
17326 "{name}: facade, pyramid requested {pyramid:?} effective \
17327 {effective:?} -- frames key {} arf {} leaf {} \
17328 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
17329 counts[0], counts[1], counts[2], counts[3],
17330 bytes[0], bytes[1], bytes[2], bytes[3],
17331 );
17332 (ladder, wall)
17333 }
17334 };
17335 // How often the inter split actually fired over this clip's four
17336 // encodes, against the whole 32x32 that was the only outcome
17337 // before (gate-blind-to-feature).
17338 let [whole32, split32, whole16, split16] = take_partition_hits();
17339 // Which inter modes actually fired over this clip's four encodes,
17340 // and at which DRL index -- a mode nobody picks is a mode the BD
17341 // number cannot be crediting (gate-blind-to-feature).
17342 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
17343 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
17344 let refs = crate::tile::take_ref_hits();
17345 let modes_total = (nearest + near + global + new).max(1);
17346 eprintln!(
17347 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
17348 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
17349 {drl0}/{drl1}/{drl2}/{drl3}",
17350 100.0 * nearest as f64 / modes_total as f64,
17351 100.0 * near as f64 / modes_total as f64,
17352 100.0 * global as f64 / modes_total as f64,
17353 100.0 * new as f64 / modes_total as f64,
17354 );
17355 // The compound census: what share of the coded inter blocks took
17356 // a compound reference at all, which compound mode they took, and
17357 // which pair (gate-blind-to-feature -- a compound mode nobody
17358 // picks cannot be what a BD number credits).
17359 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
17360 // superblocks were left whole at all, and how many of those coded
17361 // a residual or took a compound reference.
17362 let (roots, root_res, root_comp) = (
17363 take_b64_root_hits(),
17364 take_b64_residual_hits(),
17365 take_b64_compound_hits(),
17366 );
17367 eprintln!(
17368 "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})"
17369 );
17370 let comp_modes = crate::tile::take_compound_mode_hits();
17371 let comp_pairs = crate::tile::take_compound_pair_hits();
17372 let comp_sizes = crate::tile::take_compound_size_hits();
17373 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
17374 let comp_total: usize = comp_modes.iter().sum();
17375 eprintln!(
17376 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
17377 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
17378 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
17379 modes_total + comp_total,
17380 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
17381 comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3],
17382 comp_modes[6], comp_modes[7],
17383 comp_pairs[3], comp_pairs[6],
17384 );
17385 eprintln!(
17386 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
17387 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
17388 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6],
17389 comp_leaf[7],
17390 );
17391 eprintln!(
17392 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
17393 comp_sizes[1], comp_sizes[2], comp_sizes[3],
17394 );
17395 // Where the wall-owning stage actually goes: how many candidate
17396 // evaluations (one `mc::predict` + SAD each) a search spends, how
17397 // many of them are subpel, and how often the winner is the seed
17398 // it started from -- the census the seeded search is judged by.
17399 let [calls, evals, subpel, rounds, near_pred, unmoved, widest, widest_moves] =
17400 crate::motion::take_census();
17401 let per = |n: u64| n as f64 / calls.max(1) as f64;
17402 eprintln!(
17403 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
17404 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
17405 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
17406 per(evals),
17407 100.0 * subpel as f64 / evals.max(1) as f64,
17408 per(rounds),
17409 100.0 * near_pred as f64 / calls.max(1) as f64,
17410 100.0 * unmoved as f64 / calls.max(1) as f64,
17411 );
17412 // lane-newmv, class `instrument at bound`: how often the winner
17413 // was walked to at the log stage's own WIDEST step -- a high
17414 // share means the search stops where its step lets it, not where
17415 // the content is.
17416 eprintln!(
17417 "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
17418 100.0 * widest as f64 / calls.max(1) as f64,
17419 per(widest_moves),
17420 );
17421 eprintln!(
17422 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
17423 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
17424 );
17425 eprintln!(
17426 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
17427 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
17428 whole32 + split32,
17429 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
17430 whole16 + split16,
17431 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
17432 );
17433 // The deblocking level each of this clip's frames chose
17434 // (lane-av1filt): 0 everywhere would mean the filter never fires.
17435 let levels = crate::filter_search::take_chosen_levels();
17436 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
17437 let mean = |f: fn(&Chosen) -> u8| {
17438 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
17439 };
17440 eprintln!(
17441 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
17442 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
17443 levels.len(),
17444 mean(|l| l.0.0),
17445 mean(|l| l.0.1),
17446 mean(|l| l.1.0),
17447 mean(|l| l.1.1),
17448 mean(|l| l.2.0),
17449 mean(|l| l.2.1),
17450 );
17451 // How many strength presets each frame's CDEF list carried and
17452 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
17453 // everywhere would mean the per-unit choice never fires.
17454 let presets = crate::filter_search::take_cdef_presets();
17455 let mut by_bits = [0usize; 4];
17456 for (b, _) in &presets {
17457 by_bits[usize::from(*b)] += 1;
17458 }
17459 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
17460 let on_extra: usize = presets
17461 .iter()
17462 .flat_map(|(_, c)| c.iter().skip(1))
17463 .sum();
17464 eprintln!(
17465 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
17466 on a non-default preset ({:.1}%)",
17467 by_bits[0],
17468 by_bits[1],
17469 by_bits[2],
17470 by_bits[3],
17471 on_extra,
17472 units,
17473 100.0 * on_extra as f64 / units.max(1) as f64
17474 );
17475 // How the 64x64 luma restoration units split between
17476 // RESTORE_NONE and Wiener (lane-av1lr).
17477 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
17478 eprintln!(
17479 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
17480 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
17481 );
17482 // Which chroma modes the search actually wins with, against the
17483 // unconditional DC_PRED that was the only outcome before
17484 // (gate-blind-to-feature).
17485 // Screen-content detection and the palette it turns on
17486 // (gate-blind-to-feature): how many frames set
17487 // `allow_screen_content_tools`, how many blocks took a palette,
17488 // and of what size. A film clip must print `screen frames on=0`.
17489 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
17490 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
17491 // Which tables the SEARCH priced against, per frame arming
17492 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
17493 // real starting ones. A film clip must show every inter arming on
17494 // the real side, a screen clip none of them.
17495 let (price_default, price_real) = crate::tile::take_pricing_hits();
17496 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
17497 let palette = crate::tile::take_palette_hits();
17498 eprintln!(
17499 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
17500 palette[0],
17501 (2..=8)
17502 .filter(|&n| palette[n] > 0)
17503 .map(|n| format!("{n}={}", palette[n]))
17504 .collect::<Vec<_>>()
17505 .join(" ")
17506 );
17507 // The CfL alpha histogram (lane-av1cfl): one entry per chroma
17508 // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
17509 // only ever fires at one magnitude is a search that never left
17510 // its first candidate (gate-blind-to-feature).
17511 // The luma angle-delta histogram (lane-av1cfl): how many
17512 // directional blocks won at each delta. All-zero would mean the
17513 // refinement never beat the base angle.
17514 let deltas = take_angle_delta_hits();
17515 if deltas.iter().sum::<usize>() > 0 {
17516 eprintln!(
17517 "{name}: angle_delta_y {}",
17518 deltas
17519 .iter()
17520 .enumerate()
17521 .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
17522 .collect::<Vec<_>>()
17523 .join(" ")
17524 );
17525 }
17526 let alphas = take_cfl_alpha_hits();
17527 if alphas.iter().sum::<usize>() > 0 {
17528 eprintln!(
17529 "{name}: cfl |alpha| {}",
17530 alphas
17531 .iter()
17532 .enumerate()
17533 .filter(|&(_, &n)| n > 0)
17534 .map(|(a, &n)| format!("{a}={n}"))
17535 .collect::<Vec<_>>()
17536 .join(" ")
17537 );
17538 }
17539 let palette_uv = crate::tile::take_palette_uv_hits();
17540 eprintln!(
17541 "{name}: chroma palette blocks {} sizes {}",
17542 palette_uv[0],
17543 (2..=8)
17544 .filter(|&n| palette_uv[n] > 0)
17545 .map(|n| format!("{n}={}", palette_uv[n]))
17546 .collect::<Vec<_>>()
17547 .join(" ")
17548 );
17549 let uv = take_uv_mode_hits();
17550 let uv_total: usize = uv.iter().sum();
17551 eprintln!(
17552 "{name}: uv modes {}",
17553 uv.iter()
17554 .enumerate()
17555 .filter(|&(_, &n)| n > 0)
17556 .map(|(m, &n)| format!(
17557 "{}={n} ({:.1}%)",
17558 UV_MODE_NAMES[m],
17559 100.0 * n as f64 / uv_total.max(1) as f64
17560 ))
17561 .collect::<Vec<_>>()
17562 .join(" ")
17563 );
17564 // Which transform depth the intra blocks of this clip's key
17565 // frames resolved to (lane-av1tx): depth 0 is one transform over
17566 // the whole block, 1 and 2 its halvings.
17567 let depths = take_tx_depth_hits();
17568 let depth_total: usize = depths.iter().sum();
17569 eprintln!(
17570 "{name}: intra tx depths {}",
17571 depths
17572 .iter()
17573 .enumerate()
17574 .map(|(d, &n)| format!(
17575 "{d}={n} ({:.1}%)",
17576 100.0 * n as f64 / depth_total.max(1) as f64
17577 ))
17578 .collect::<Vec<_>>()
17579 .join(" ")
17580 );
17581 print_inter_tx_census(name);
17582 // lane-av1obmc: how many blocks actually CODED a motion_mode
17583 // symbol and which value they took, by footprint -- "OBMC is on"
17584 // as a measurement rather than a claim (class
17585 // `gate-blind-to-feature`).
17586 let mm = crate::tile::take_motion_mode_hits();
17587 eprintln!(
17588 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
17589 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
17590 eligible)",
17591 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
17592 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
17593 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
17594 mm.iter().sum::<usize>(),
17595 );
17596 let (aom, aom_wall) =
17597 external_ladder(&source, width, height, "libaom-av1", &aom_points);
17598 let (rav1e, rav1e_wall) =
17599 external_ladder(&source, width, height, "librav1e", &rav1e_points);
17600 assert_monotone(&format!("{name}: ours"), &ours);
17601 assert_monotone(&format!("{name}: libaom"), &aom);
17602 assert_monotone(&format!("{name}: rav1e"), &rav1e);
17603 let points = ours
17604 .iter()
17605 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
17606 .collect::<Vec<_>>()
17607 .join(", ");
17608 println!(
17609 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
17610 bd_rate(&aom, &ours) * 100.0,
17611 bd_rate(&rav1e, &ours) * 100.0,
17612 );
17613 println!(
17614 "| references | libaom {} | rav1e {} | | |",
17615 aom.iter()
17616 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
17617 .collect::<Vec<_>>()
17618 .join(", "),
17619 rav1e
17620 .iter()
17621 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
17622 .collect::<Vec<_>>()
17623 .join(", "),
17624 );
17625 }
17626 assert_ladder_decodes();
17627 }
17628 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
17629 /// split by block class in lane-av1txdepth): depth 0 is one transform over
17630 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
17631 /// leaves and the 32x32 root, each single-reference or compound. A class
17632 /// with no counts at all never reached `commit_inter_luma` -- which is
17633 /// what its knob being off looks like (class `gate-blind-to-feature`).
17634 fn print_inter_tx_census(name: &str) {
17635 let splits = take_inter_tx_split_hits();
17636 let total: usize = splits.iter().sum();
17637 let row = |label: &str, base: usize| {
17638 let (n0, n1) = (splits[base], splits[base + 1]);
17639 format!(
17640 "{label} 0={n0} 1={n1} ({:.1}% split)",
17641 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
17642 )
17643 };
17644 eprintln!(
17645 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
17646 row("leaf single", 0),
17647 row("leaf compound", 2),
17648 row("32x32 single", 4),
17649 row("32x32 compound", 6),
17650 );
17651 // lane-txrd: which types the two searches actually COMMITTED over
17652 // this row's four encodes -- the gate could not say whether a type
17653 // search fired at all (class `gate-blind-to-feature`).
17654 const NAMES: [&str; 16] = [
17655 "IDTX", "DCT_DCT", "ADST_ADST", "ADST_DCT", "DCT_ADST", "V_DCT", "H_DCT",
17656 "FLIPADST_DCT", "DCT_FLIPADST", "FLIPADST_FLIPADST", "ADST_FLIPADST",
17657 "FLIPADST_ADST", "V_ADST", "H_ADST", "V_FLIPADST", "H_FLIPADST",
17658 ];
17659 let name_of = |t: usize| NAMES[t];
17660 for (label, hits) in [("inter", take_inter_tx_type_hits()), ("intra", take_tx_type_hits())] {
17661 let total: usize = hits.iter().sum();
17662 let live: Vec<String> = hits
17663 .iter()
17664 .enumerate()
17665 .filter(|&(_, &n)| n > 0)
17666 .map(|(t, &n)| format!("{}={n} ({:.1}%)", name_of(t), 100.0 * n as f64 / total.max(1) as f64))
17667 .collect();
17668 eprintln!("{name}: {label} tx_type of {total} units -- {}", live.join(" "));
17669 }
17670 let t = take_txrd_stats();
17671 if t[0] > 0 {
17672 eprintln!(
17673 "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \
17674 bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",
17675 t[0], t[1], t[3] as f64 / 64.0, t[2], t[4] as f64 / 64.0,
17676 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,
17677 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,
17678 );
17679 eprintln!(
17680 "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \
17681 flat: dsse {:+.2}%, dbits {:+.2}%)",
17682 t[5], t[6] as f64 / 64.0,
17683 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,
17684 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,
17685 );
17686 }
17687 }
17688
17689 /// The video stream's coded size, from ffprobe.
17690 fn probe_dims(clip: &str) -> Option<(usize, usize)> {
17691 crate::probe::dims(clip)
17692 }
17693
17694 /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
17695 /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
17696 /// superblock-aligned one, still centred and still even for 4:2:0.
17697 ///
17698 /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
17699 /// superblocks by design, so no default gate row has a block the frame
17700 /// edge cuts through -- while every arbitrary export size does (3840x1608
17701 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
17702 /// 1920x1080` is the straddling arm the edge-clipped distortion score is
17703 /// read on.
17704 fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
17705 let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
17706 let (w, h) = spec.split_once('x').expect("EC_AV1_NATIVE_CROP is <width>x<height>");
17707 let (cw, ch): (usize, usize) =
17708 (w.parse().expect("crop width"), h.parse().expect("crop height"));
17709 let (nw, nh) = crate::probe::dims(clip)?;
17710 assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
17711 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
17712 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
17713 }
17714
17715 /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
17716 /// with `probe_screen_detect` so the detector sweep measures exactly the
17717 /// clips the keep table is read off. Selector env vars as documented on
17718 /// the gate; a missing clip prints a SKIP and drops its row.
17719 fn native_gate_clips() -> Vec<(String, String, String)> {
17720 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
17721 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
17722 let (film, film4k, screen) = (
17723 on("EC_AV1_NATIVE_FILM"),
17724 on("EC_AV1_NATIVE_FILM4K"),
17725 on("EC_AV1_NATIVE_SCREEN"),
17726 );
17727 // No selector at all means every clip; any selector means that subset.
17728 let all = !(film || film4k || screen);
17729 // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
17730 // not film -- they print as "bars" so no reader takes them for real
17731 // content -- and the two rows below them are the real AV1 films.
17732 let mut clips: Vec<(String, String, String)> = Vec::new();
17733 for (want, label, file) in [
17734 (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
17735 (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
17736 ] {
17737 if !want {
17738 continue;
17739 }
17740 let path = fixtures.join("video").join(file);
17741 match path.exists() {
17742 true => {
17743 clips.push((label.to_string(), path.to_str().unwrap().to_string(), "0".into()))
17744 }
17745 false => eprintln!("SKIP {label}: {file} missing"),
17746 }
17747 }
17748 let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
17749 // The real films, taken out of the real-library manifest by codec and
17750 // coded width so no title and no home path lives in this file. Each
17751 // seek is PINNED (class `seeded fixture not reproducible`) at a
17752 // moving, non-black window -- a black leader would make every arm
17753 // read +0.000 (class `flat sample window`). Both sources are 10-bit
17754 // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
17755 // what all three encoders see, so the comparison stays
17756 // encoder-vs-encoder.
17757 let pick = |width: &str| -> Option<String> {
17758 let m = manifest.as_ref().ok()?;
17759 m.lines()
17760 .skip(1)
17761 .map(|l| l.split('\t').collect::<Vec<_>>())
17762 .find(|f| {
17763 f.len() > 4
17764 && f[2] == "av1"
17765 && f[3] == width
17766 && std::path::Path::new(f[0]).exists()
17767 })
17768 .map(|f| f[0].to_string())
17769 };
17770 for (want, label, width, seek) in [
17771 (all || film, "film A (1080p source)", "1920", "00:35:00"),
17772 (all || film4k, "film B (2160p HDR source)", "3840", "00:40:00"),
17773 ] {
17774 if !want {
17775 continue;
17776 }
17777 match pick(width) {
17778 Some(path) => clips.push((label.to_string(), path, seek.to_string())),
17779 None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
17780 }
17781 }
17782 if all || screen {
17783 match &manifest {
17784 Ok(manifest) => match manifest
17785 .lines()
17786 .skip(1)
17787 .filter_map(|l| l.split('\t').next())
17788 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
17789 {
17790 Some(p) => clips.push((
17791 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
17792 p.to_string(),
17793 "0".into(),
17794 )),
17795 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
17796 },
17797 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
17798 }
17799 }
17800 clips
17801 }
17802
17803 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
17804 /// downscales the OBS capture to 640x384, which destroys exactly the
17805 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
17806 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
17807 /// on that recipe is taken on content the tool cannot serve. This arm
17808 /// crops -- never scales -- a superblock-aligned window out of the middle
17809 /// of the capture at its own resolution (at most 1920x1024, so the wall
17810 /// stays in the minutes) and runs the same 12-frame, four-quantizer
17811 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
17812 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
17813 /// sample-exactness assertion `our_ladder` makes.
17814 ///
17815 /// It is its own `--ignored` test so the default gate's wall does not
17816 /// grow. Every variant is an environment knob, and each of those is a
17817 /// `OnceLock` read once per process, so a variant is a separate run:
17818 ///
17819 /// cargo test -p ec-av1 --release --lib -- --ignored \
17820 /// bd_rate_screen_native --nocapture # baseline
17821 /// EC_AV1_INTRABC=1 ... same command # intra block copy
17822 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
17823 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
17824 /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
17825 /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing
17826 /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
17827 ///
17828 /// The coding pyramid is the DEFAULT of the sequence path this arm codes
17829 /// through (lane-av1pyrdef); the run prints the requested and the
17830 /// effective pyramid per clip, and a screen clip's effective one is
17831 /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
17832 /// streaming facade instead, which prints the per-level frame and byte
17833 /// census and asserts ffmpeg's decode against our own decoder on all
17834 /// three planes in display order; both arms code the same bytes
17835 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
17836 ///
17837 /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
17838 /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
17839 /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
17840 /// cost -- so every "film" column in the historical tables of this file
17841 /// is that generator, not film. The real content is `film A`, `film B`
17842 /// (native crops out of the two AV1 films the real-library manifest
17843 /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
17844 /// decision only the bars rows support is not supported.
17845 ///
17846 /// Measured 2026-09-07, the five rows before and after the screen
17847 /// detector grew libaom's variance term ([`screen_var`]) -- before it,
17848 /// BOTH real films were classified as screen content on 48/48 frames, so
17849 /// their coefficients were priced against the DEFAULT CDFs and the
17850 /// palette search ran over film; after, both are non-screen (0/48) and
17851 /// the capture is unchanged at 48/48:
17852 ///
17853 /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
17854 /// |---|---|---|---|
17855 /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
17856 /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
17857 /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
17858 /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
17859 /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
17860 ///
17861 /// Both bars rows and the capture are byte-identical across that change
17862 /// (their classification never moved); the palette search over film was
17863 /// costing roughly a tenth of the film rows' wall.
17864 ///
17865 /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
17866 /// sequence path's default -- the four non-screen rows take `4:-16:8`,
17867 /// the capture is gated flat and does not move a byte:
17868 ///
17869 /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
17870 /// |---|---|---|---|---|
17871 /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
17872 /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
17873 /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
17874 /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
17875 /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
17876 ///
17877 /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
17878 /// which is the point of the shared driver: the two entry points code one
17879 /// stream. The bars rows are fixtures (recorded, never a decision); the
17880 /// two real films are what the pyramid ships for.
17881 ///
17882 /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
17883 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
17884 /// setting any one of them keeps only the selected rows (the two 1080p
17885 /// rows, the two 2160p rows, the capture row respectively). A missing
17886 /// real film SKIPs its row; it never fails the gate.
17887 #[test]
17888 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
17889 fn bd_rate_screen_native() {
17890 let _knobs = crate::speed::knob_read();
17891 native_bd_arm("bd_rate_screen_native", 12, false);
17892 }
17893
17894 /// The LONG-GOP arm of the native BD gate: the same recipe as
17895 /// [`bd_rate_screen_native`] over the two real film rows only, but 48
17896 /// pictures with `gop = 48` (`encode_sequence` sets `gop =
17897 /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which
17898 /// reaches libaom as `--kf-max-dist=48` and rav1e as
17899 /// `key_frame_interval=48`), so every encoder sees one key frame and 47
17900 /// inter pictures.
17901 ///
17902 /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop =
17903 /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key
17904 /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`]
17905 /// above 12 codes the same stream there -- the shipped `16` was measured
17906 /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture
17907 /// group (class `instrument at bound` / `gate blind to feature`). The
17908 /// user's exports are long GOPs, so the pyramid shape is decided here.
17909 ///
17910 /// cargo test -p ec-av1 --release --lib -- --ignored \
17911 /// bd_rate_film_long_gop --nocapture
17912 ///
17913 /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1`
17914 /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape.
17915 /// Read every row off the log's own "pyramid requested/effective" print,
17916 /// never off the argument order of the runs (lane-pyr3 misattributed
17917 /// three rows that way).
17918 ///
17919 /// Table: `lanes/pyr4.sweep.txt`.
17920 #[test]
17921 #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"]
17922 fn bd_rate_film_long_gop() {
17923 let _knobs = crate::speed::knob_write();
17924 native_bd_arm("bd_rate_film_long_gop", 48, true);
17925 }
17926
17927 /// The shared driver of the two native BD arms above: `frames` pictures
17928 /// per row (the sequence's `gop` is the same number, so one key frame),
17929 /// four quantizers, `films_only` dropping every row but the two real
17930 /// films.
17931 fn native_bd_arm(label: &str, frames: usize, films_only: bool) {
17932 if !have_ffmpeg() {
17933 eprintln!("SKIP {label}: no ffmpeg");
17934 return;
17935 }
17936 let mut clips = native_gate_clips();
17937 if films_only {
17938 clips.retain(|(name, _, _)| name.starts_with("film "));
17939 }
17940 if clips.is_empty() {
17941 eprintln!("SKIP {label}: no clip");
17942 return;
17943 }
17944
17945 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
17946 .iter()
17947 .map(|q| {
17948 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
17949 .map(String::from)
17950 .to_vec()
17951 })
17952 .collect();
17953 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
17954 .iter()
17955 .map(|q| {
17956 vec![
17957 "-rav1e-params".to_string(),
17958 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
17959 ]
17960 })
17961 .collect();
17962 println!(
17963 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
17964 intrabc {}, palette maxcolors {}",
17965 armed_tiles(),
17966 crate::par::tile_threads(),
17967 intrabc_enabled(),
17968 palette_max_colors(),
17969 );
17970 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |");
17971 println!("|---|---|---|---|---|");
17972 for (name, path, seek) in &clips {
17973 let fctx = &crate::decode::FrameCtx::for_encoder();
17974 if probe_dims(path).is_none() {
17975 eprintln!("SKIP {name}: ffprobe gave no size");
17976 continue;
17977 }
17978 // A whole number of 128-wide superblocks, at most 1920x1024, out
17979 // of the middle of the frame; the offsets stay even for 4:2:0.
17980 // ONE definition, shared with `examples/enc_probe` so the probe
17981 // cannot measure a different window than this gate (lane-probe).
17982 let (vf, cw, ch) = match native_crop_override(path) {
17983 Some(over) => over,
17984 None => crate::probe::gate_crop(path),
17985 };
17986 let source = clip_frames_vf(path, seek, &vf, cw, ch, frames);
17987 SCREEN_FRAMES.iter().for_each(|c| {
17988 c.store(0, std::sync::atomic::Ordering::Relaxed);
17989 });
17990 let _ = crate::tile::take_palette_hits();
17991 let _ = crate::tile::take_palette_uv_hits();
17992 let _ = crate::tile::take_intrabc_hits();
17993 let _ = take_intrabc_search();
17994 let _ = crate::tile::take_filter_intra_hits();
17995 let _ = take_edge_census();
17996 // The sequence path itself codes the pyramid now
17997 // (lane-av1pyrdef), and prints what it requested and what the
17998 // content gate left effective.
17999 let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx);
18000 // lane-sse: the blocks the true frame edge cuts through, and how
18001 // much of their RAW squared error sat in the padding the encoder
18002 // invented past it -- what the inside-only score stopped ranking
18003 // on. Empty on a superblock-aligned crop, which is every default
18004 // gate row (class `gate-blind-to-feature`).
18005 if edge_census() {
18006 for (side, n, inside, padding) in take_edge_census() {
18007 eprintln!(
18008 "{name}: edge {side}x{side} scores={n} inside_sse={inside} \
18009 padding_sse={padding} ({:.1}% of raw)",
18010 100.0 * padding as f64 / (inside + padding).max(1) as f64,
18011 );
18012 }
18013 }
18014 // gate-blind-to-feature: what the screen tools actually did at
18015 // native resolution, over this clip's four encodes.
18016 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
18017 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
18018 // Which tables the SEARCH priced against, per frame arming
18019 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
18020 // real starting ones. A film clip must show every inter arming on
18021 // the real side, a screen clip none of them.
18022 let (price_default, price_real) = crate::tile::take_pricing_hits();
18023 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
18024 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
18025 // superblocks stayed whole, and how many of those coded a
18026 // residual, split that residual's luma, or took a compound
18027 // reference (class `gate-blind-to-feature`).
18028 // lane-i64: the KEY frame's own 64x64 intra root -- how many of
18029 // the superblocks offered the trial were coded whole.
18030 let [i64_whole, i64_offered, i64_edge] = take_i64_root_hits();
18031 eprintln!(
18032 "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%), \
18033 {i64_edge} on a superblock the frame edge cuts",
18034 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
18035 );
18036 eprintln!(
18037 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
18038 take_b64_root_hits(),
18039 take_b64_residual_hits(),
18040 take_b64_var_tx_hits(),
18041 take_b64_compound_hits(),
18042 );
18043 // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan
18044 // of every priced block): what the deadzone quantiser handed the
18045 // RDOQ pass and what the pass changed, over every TRIAL block of
18046 // this row's four encodes -- not over the coded stream, so it is
18047 // the bits AT STAKE in the search, not in the bitstream.
18048 let rq = crate::tile::take_rdoq_stats();
18049 if rq[0] > 0 {
18050 eprintln!(
18051 "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \
18052 zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)",
18053 rq[0],
18054 rq[1],
18055 100.0 * rq[2] as f64 / rq[1].max(1) as f64,
18056 100.0 * rq[3] as f64 / rq[1].max(1) as f64,
18057 rq[4],
18058 rq[5],
18059 rq[7] as f64 / 64.0,
18060 rq[6] as f64 / 64.0,
18061 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64,
18062 );
18063 }
18064 // lane-av1obmc2: the same motion_mode census the 640x384 gate
18065 // prints (class `gate-blind-to-feature`) -- how many blocks coded
18066 // the symbol at each footprint and how many took OBMC. Without it
18067 // the native table, which is the standing keep table, could not
18068 // say whether the tool fired at all.
18069 let mm = crate::tile::take_motion_mode_hits();
18070 eprintln!(
18071 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
18072 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
18073 eligible)",
18074 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
18075 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
18076 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
18077 mm.iter().sum::<usize>(),
18078 );
18079 print_inter_tx_census(name);
18080 // lane-last2 (class `gate-blind-to-feature`): which reference the
18081 // 32x32-and-below inter blocks of this clip's four encodes chose.
18082 // The native table is the standing keep table, so a second past
18083 // reference that never won a block has to be visible HERE and not
18084 // only in a synthetic witness.
18085 let rh = crate::encode::take_ref_frame_hits();
18086 let rtot: usize = rh.iter().sum();
18087 eprintln!(
18088 "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \
18089 (LAST2 {:.1}%)",
18090 rh[1], rh[2], rh[4], rh[7], rtot,
18091 100.0 * rh[2] as f64 / rtot.max(1) as f64,
18092 );
18093 let palette = crate::tile::take_palette_hits();
18094 let palette_uv = crate::tile::take_palette_uv_hits();
18095 let ibc = crate::tile::take_intrabc_hits();
18096 let search = take_intrabc_search();
18097 eprintln!(
18098 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
18099 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
18100 won {})",
18101 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
18102 palette[0],
18103 palette_uv[0],
18104 ibc[0],
18105 search[0],
18106 search[1],
18107 search[2],
18108 );
18109 // gate-blind-to-feature: how often the five recursive filter-intra
18110 // modes actually won a block over this clip's four encodes -- a
18111 // tool that never fires is not measured by the row above it.
18112 let fi = crate::tile::take_filter_intra_hits();
18113 eprintln!(
18114 "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})",
18115 filter_intra_on(),
18116 fi[0],
18117 fi[1],
18118 fi[2],
18119 fi[3],
18120 fi[4],
18121 fi[5],
18122 );
18123 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
18124 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
18125 assert_monotone(&format!("{name}: ours"), &ours);
18126 assert_monotone(&format!("{name}: libaom"), &aom);
18127 assert_monotone(&format!("{name}: rav1e"), &rav1e);
18128 let points = ours
18129 .iter()
18130 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
18131 .collect::<Vec<_>>()
18132 .join(", ");
18133 println!(
18134 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
18135 bd_rate(&aom, &ours) * 100.0,
18136 bd_rate(&rav1e, &ours) * 100.0,
18137 );
18138 // lane-pareto2: the two references at THEIR fast presets, plus
18139 // SVT-AV1, measured in the SAME arm as the row above -- the only
18140 // way the wall column of a Pareto table means anything (class:
18141 // wall tables are comparable only inside one interleaved batch).
18142 // `EC_AV1_PARETO_REFS=1` only: it roughly doubles the arm.
18143 if std::env::var("EC_AV1_PARETO_REFS").ok().as_deref() == Some("1") {
18144 let rav1e_at = |sp: u32| -> Vec<Vec<String>> {
18145 [50, 100, 150, 200]
18146 .iter()
18147 .map(|q| {
18148 vec![
18149 "-rav1e-params".to_string(),
18150 format!(
18151 "speed={sp}:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"
18152 ),
18153 ]
18154 })
18155 .collect()
18156 };
18157 let aom_at = |cu: u32| -> Vec<Vec<String>> {
18158 [5, 20, 35, 45]
18159 .iter()
18160 .map(|q| {
18161 vec![
18162 "-cpu-used".to_string(),
18163 cu.to_string(),
18164 "-b:v".to_string(),
18165 "0".to_string(),
18166 "-crf".to_string(),
18167 q.to_string(),
18168 ]
18169 })
18170 .collect()
18171 };
18172 let svt_at = |pr: u32| -> Vec<Vec<String>> {
18173 [20, 35, 45, 55]
18174 .iter()
18175 .map(|q| {
18176 vec![
18177 "-preset".to_string(),
18178 pr.to_string(),
18179 "-crf".to_string(),
18180 q.to_string(),
18181 "-svtav1-params".to_string(),
18182 "lp=1".to_string(),
18183 ]
18184 })
18185 .collect()
18186 };
18187 let mut arms: Vec<(String, &str, Vec<Vec<String>>)> = vec![
18188 ("rav1e speed 8".into(), "librav1e", rav1e_at(8)),
18189 ("rav1e speed 10".into(), "librav1e", rav1e_at(10)),
18190 ("libaom cpu-used 8".into(), "libaom-av1", aom_at(8)),
18191 ];
18192 if have_encoder("libsvtav1") {
18193 arms.push(("svt-av1 preset 8".into(), "libsvtav1", svt_at(8)));
18194 arms.push(("svt-av1 preset 10".into(), "libsvtav1", svt_at(10)));
18195 } else {
18196 eprintln!("SKIP the SVT-AV1 rows: this ffmpeg has no libsvtav1");
18197 }
18198 for (label, encoder, points) in arms {
18199 let (lad, wall) = external_ladder(&source, cw, ch, encoder, &points);
18200 // A REFERENCE stream our decoder cannot read is a note in
18201 // this table, not a gate failure: these rows exist to
18202 // price the references, and `assert_ladder_decodes` keeps
18203 // its teeth for the two ladders the keep table is read off.
18204 let notes =
18205 std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
18206 if !notes.is_empty() {
18207 eprintln!("{name} {label}: {} point(s) our decoder could not read (reference row, not a gate failure)", notes.len());
18208 }
18209 assert_monotone(&format!("{name}: {label}"), &lad);
18210 println!(
18211 "| {name} {cw}x{ch} / {label} | -- | {:+.1}% | {:+.1}% | {wall:.1}s (ours {ours_wall:.1}s, rav1e s6 {rav1e_wall:.1}s) |",
18212 bd_rate(&aom, &lad) * 100.0,
18213 bd_rate(&rav1e, &lad) * 100.0,
18214 );
18215 }
18216 }
18217 }
18218 assert_ladder_decodes();
18219 }
18220
18221 /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator
18222 /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC)
18223 /// on the two film clips at their native gate crop. The 2160p clip loses
18224 /// at every arm of the propagating map and the named suspect was that its
18225 /// heavily filtered flat cells give a tiny denominator, so the dependence
18226 /// ratio explodes exactly where coding is cheap; this prints the numbers
18227 /// that confirm or refute it.
18228 #[test]
18229 #[ignore = "needs ffmpeg and the film fixtures"]
18230 fn tpl_intra_denominator_histogram() {
18231 let _knobs = crate::speed::knob_read();
18232 if !have_ffmpeg() {
18233 eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg");
18234 return;
18235 }
18236 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
18237 for (label, file) in [
18238 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
18239 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
18240 ] {
18241 let path = fixtures.join("video").join(file);
18242 if !path.exists() {
18243 eprintln!("SKIP {label}: {file} missing");
18244 continue;
18245 }
18246 let path = path.to_str().unwrap();
18247 let Some((nw, nh)) = probe_dims(path) else {
18248 eprintln!("SKIP {label}: ffprobe gave no size");
18249 continue;
18250 };
18251 let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128);
18252 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
18253 let source =
18254 clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8);
18255 let mut costs: Vec<f64> = Vec::new();
18256 for pic in &source {
18257 let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect();
18258 costs.extend(
18259 super::tpl_intra_costs(&y8, cw, ch).iter().map(|&c| f64::from(c)),
18260 );
18261 }
18262 let mean = costs.iter().sum::<f64>() / costs.len() as f64;
18263 let mut sorted = costs.clone();
18264 sorted.sort_by(f64::total_cmp);
18265 let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean;
18266 let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count();
18267 eprintln!(
18268 "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \
18269 as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \
18270 p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \
18271 below 1.0x {} ({:.1}%)",
18272 costs.len(),
18273 q(0.0),
18274 q(0.01),
18275 q(0.05),
18276 q(0.25),
18277 q(0.50),
18278 q(0.75),
18279 q(0.99),
18280 q(1.0),
18281 below(0.25),
18282 100.0 * below(0.25) as f64 / costs.len() as f64,
18283 below(0.5),
18284 100.0 * below(0.5) as f64 / costs.len() as f64,
18285 below(1.0),
18286 100.0 * below(1.0) as f64 / costs.len() as f64,
18287 );
18288 }
18289 }
18290
18291 /// The probe arms the gate's source (lane-probe, class `instrument
18292 /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
18293 /// command line and had no `-ss`, so it read film B from frame 0 -- a
18294 /// black leader -- and coded 59 kB where the gate's own ladder point
18295 /// coded 89 kB of the same title; every census taken through it was
18296 /// probe-relative. Both now call [`crate::probe::source`]; this pins that
18297 /// the shared loader honours the seek (arming the probe's way and the
18298 /// gate's way gives byte-identical streams, and dropping the seek does
18299 /// not), on a synthetic clip whose content moves over time.
18300 #[test]
18301 fn the_probe_arms_the_gates_source() {
18302 let _knobs = crate::speed::knob_write();
18303 if !have_ffmpeg() {
18304 eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg");
18305 return;
18306 }
18307 let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
18308 std::fs::create_dir_all(&dir).unwrap();
18309 let clip = dir.join("testsrc2.y4m");
18310 // 384x202: neither side is a multiple of 128, so the gate's centre
18311 // window is a real derivation and not the frame itself -- exactly the
18312 // shape film B has (3840x1608, never 3840x2160).
18313 let ok = Command::new("ffmpeg")
18314 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=384x202:rate=10"])
18315 .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
18316 .arg(&clip)
18317 .status()
18318 .expect("ffmpeg failed to run")
18319 .success();
18320 assert!(ok, "ffmpeg could not write the synthetic clip");
18321 let path = clip.to_str().unwrap();
18322
18323 // The window: superblock-aligned, centred, even offsets.
18324 let (vf, w, h) = crate::probe::gate_crop(path);
18325 assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
18326
18327 let (seek, q) = ("00:00:01", 150u8);
18328 let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
18329 let probe = crate::probe::source(path, seek, &vf, w, h, 6);
18330 assert!(
18331 gate.iter().zip(&probe).all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
18332 "the probe's source differs from the gate's at the same window"
18333 );
18334 let bytes = |src: &[Picture]| {
18335 encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
18336 .unwrap()
18337 .stream
18338 };
18339 assert_eq!(bytes(&gate), bytes(&probe), "probe and gate code different bytes");
18340 // The two witnesses that both halves of the arming reach ffmpeg: the
18341 // seek, and the crop's own offset (the film-B defect in miniature --
18342 // the probe was reading `crop=..:568` of a 1608-high frame).
18343 let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
18344 assert_ne!(
18345 bytes(&gate),
18346 bytes(&unseeked),
18347 "seeked and unseeked arming coded the same bytes -- the seek is inert"
18348 );
18349 let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
18350 assert_ne!(
18351 bytes(&gate),
18352 bytes(&offset),
18353 "centred and top-aligned windows coded the same bytes -- the crop is inert"
18354 );
18355 std::fs::remove_dir_all(&dir).ok();
18356 }
18357
18358 /// lane-probe diagnostic: the gate's own loader + ladder call for ONE
18359 /// point inside the test binary, to compare against `examples/enc_probe`.
18360 #[test]
18361 #[ignore = "diagnostic: needs ffmpeg and a clip"]
18362 fn probe_parity_point() {
18363 let _knobs = crate::speed::knob_write();
18364 let g = |k: &str| std::env::var(k).unwrap();
18365 let (w, h) = g("EC_PARITY_DIMS").split_once(':').map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap())).unwrap();
18366 let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap();
18367 let q: u8 = g("EC_PARITY_Q").parse().unwrap();
18368 let source = clip_frames_vf(&g("EC_PARITY_CLIP"), &g("EC_PARITY_SS"), &g("EC_PARITY_VF"), w, h, frames);
18369 let fctx = &crate::decode::FrameCtx::for_encoder();
18370 let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
18371 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
18372 for &b in &e.stream {
18373 hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
18374 }
18375 eprintln!("PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}",
18376 e.stream.len(), crate::speed::speed(), crate::encoder::Pyramid::from_env(), last_sequence_pyramid());
18377 }
18378 /// lane-refs: IS A SECOND PAST REFERENCE WORTH RETAINING? `encoder.rs`'s
18379 /// `ref_frame_idx` maps `LAST2`/`LAST3` onto `LAST`'s own DPB slot, so no
18380 /// block can predict from the picture before `LAST` -- while rav1e's ARFs
18381 /// read LAST@-4 plus LAST2@-8 and libaom holds up to seven distinct
18382 /// pictures. Building that (a second retained slot, the search offering
18383 /// it, a witness, a second motion search per block) is a week of wall on
18384 /// the stage that already owns most of the encode, so this census prices
18385 /// the lever FIRST (class `gate-blind-to-feature`, "count how often the
18386 /// feature would fire before building the machine").
18387 ///
18388 /// The measurement is on the gate's own window and loader (`gate_crop`,
18389 /// 12 pictures) of the two real films: every 16x16 luma block of every
18390 /// picture gets one full-pel diamond search against the NEAR reference
18391 /// and the same search against the FAR one, at the two lags the pyramid
18392 /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF
18393 /// level, rav1e's own pair. Reported per lag: the share of blocks the far
18394 /// reference wins at all and by more than 10%, and -- the number the
18395 /// decision is taken on -- the total SAD of best-of-{near, far} against
18396 /// the total SAD of near alone, which is the prediction energy a second
18397 /// reference could remove before any rate is paid for naming it.
18398 ///
18399 /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture
18400 #[test]
18401 #[ignore = "reads the real films"]
18402 fn last2_census() {
18403 if !have_ffmpeg() {
18404 eprintln!("SKIP last2_census: no ffmpeg");
18405 return;
18406 }
18407 const SIDE: usize = 16;
18408 // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or
18409 // `None` when the displaced block leaves the picture.
18410 let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
18411 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
18412 if sy < 0 || sx < 0 {
18413 return None;
18414 }
18415 let (sy, sx) = (sy as usize, sx as usize);
18416 if sy + SIDE > r.height || sx + SIDE > r.width {
18417 return None;
18418 }
18419 let mut acc = 0u64;
18420 for row in 0..SIDE {
18421 let c = &cur.y[(by + row) * cur.width + bx..][..SIDE];
18422 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
18423 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
18424 }
18425 Some(acc)
18426 };
18427 // A log-step diamond from the zero motion vector: the cheapest search
18428 // that still finds real pans. Both references get exactly this one,
18429 // so the comparison is search-fair.
18430 let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 {
18431 let mut best = (sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX), (0isize, 0isize));
18432 let mut step = 16isize;
18433 while step >= 1 {
18434 let centre = best.1;
18435 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
18436 let mv = (centre.0 + dy * step, centre.1 + dx * step);
18437 if let Some(s) = sad(cur, r, bx, by, mv) {
18438 if s < best.0 {
18439 best = (s, mv);
18440 }
18441 }
18442 }
18443 step /= 2;
18444 }
18445 best.0
18446 };
18447 println!("| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |");
18448 println!("|---|---|---|---|---|---|---|---|");
18449 for (name, path, seek) in native_gate_clips() {
18450 if !name.starts_with("film ") {
18451 continue;
18452 }
18453 let (vf, cw, ch) = crate::probe::gate_crop(&path);
18454 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12);
18455 for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] {
18456 let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64);
18457 let (mut near_sad, mut best_sad) = (0u64, 0u64);
18458 for i in far..pictures.len() {
18459 let cur = &pictures[i];
18460 let (rn, rf) = (&pictures[i - near], &pictures[i - far]);
18461 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
18462 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
18463 let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by));
18464 blocks += 1;
18465 wins += u64::from(f < n);
18466 big += u64::from(f as f64 * 1.1 < n as f64);
18467 near_sad += n;
18468 best_sad += n.min(f);
18469 }
18470 }
18471 }
18472 let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64;
18473 println!(
18474 "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |",
18475 pct(wins),
18476 pct(big),
18477 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64,
18478 );
18479 }
18480 }
18481 }
18482
18483 /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
18484 /// hardwire the REGULAR kernel, so the encoder could not have coded a
18485 /// SMOOTH or SHARP frame even if the header had said so -- the search,
18486 /// the trials, the recon and the frame header now all read
18487 /// `FrameCtx::interp_filter`. Each of the three kernels codes its own
18488 /// distinct stream (a filter that never reached the prediction would code
18489 /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg
18490 /// reconstructs every frame of each of them exactly, which is what proves
18491 /// the header and the prediction agree.
18492 #[test]
18493 fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() {
18494 let _knobs = crate::speed::knob_write();
18495 if !have_ffmpeg() {
18496 eprintln!("SKIP each_frame_interpolation_filter_codes_its_own_stream: no ffmpeg");
18497 return;
18498 }
18499 let (width, height) = (256usize, 128usize);
18500 // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so
18501 // all three kernels would code the same bytes and the test would pass
18502 // on a wiring that does nothing (class `fixture proves the symbol, not
18503 // the signal`). `panned_test_card` shifts by whole pixels, so the
18504 // search finds the sub-pel positions off the reconstruction instead:
18505 // three frames of a slow diagonal pan.
18506 let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect();
18507 let mut streams = Vec::new();
18508 for filter in [
18509 ec_av1_syntax::InterpolationFilter::Eighttap,
18510 ec_av1_syntax::InterpolationFilter::EighttapSmooth,
18511 ec_av1_syntax::InterpolationFilter::EighttapSharp,
18512 ] {
18513 set_frame_interp(Some(filter));
18514 let fctx = &crate::decode::FrameCtx::for_encoder();
18515 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
18516 .unwrap_or_else(|e| panic!("{filter:?}: {e}"));
18517 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
18518 assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count");
18519 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
18520 assert_eq!(decoded.y, frame.reconstruction.y, "{filter:?} frame {i}: luma");
18521 assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
18522 assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
18523 }
18524 streams.push((filter, encoded.stream));
18525 }
18526 set_frame_interp(None);
18527 for (i, (fa, a)) in streams.iter().enumerate() {
18528 for (fb, b) in &streams[i + 1..] {
18529 assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
18530 }
18531 }
18532 }
18533
18534}