forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB68cf7a6Tahinli2 months ago2975 commits

encode.rs21441 lines, 975.6 KiBHistoryRawDownload
1//! A key-frame picture encoder: a planar 4:2:0 picture in, an AV1 stream out.
2//!
3//! This is the layer that turns the pieces below it — the intra predictors of
4//! [`crate::intra`], the forward transform and quantizer of
5//! [`crate::transform`], and the tile writer of [`crate::tile`] — into
6//! something that takes a picture. Every block is 32x32 (its chroma 16x16),
7//! which is the subset the tile writer codes, and each one picks its luma mode
8//! from the seven non-directional ones by rate-distortion; chroma searches
9//! its own `uv_mode` over the seven that read no further than the row above
10//! and the column to the left, its transform type derived from that mode the
11//! way the decoder derives it. Block sizes are what a loop above this would
12//! choose between.
13//!
14//! The encoder carries its own reconstruction, because prediction reads it: a
15//! block predicts from the reconstructed samples above and to its left, exactly
16//! as the decoder will. That makes the reconstruction a claim about what a
17//! decoder produces, and it is gated as one — sample for sample against ffmpeg.
18
19use crate::decode::WithRef;
20use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
21use ec_av1_syntax::{
22 CdefParams, ChromaSamplePosition, FrameHeader, FrameType, LoopFilterParams,
23 LoopRestorationParams, PRIMARY_REF_NONE, QuantizationParams, TileInfo, TxMode,
24};
25use ec_core::{Error, Result};
26
27use crate::cdf;
28use crate::cdf_state::TxbSet;
29use crate::frame::frame_obu;
30use crate::intra::{
31 D67_PRED, DC_PRED, H_PRED, KEY_FRAME_MODES, PAETH_PRED, SMOOTH_H_PRED, SMOOTH_PRED,
32 SMOOTH_V_PRED, V_PRED,
33};
34use crate::mc;
35use crate::motion;
36use crate::mvstack::{MiGrid, MiInfo, MvStack, NO_REF1, find_mv_stack, mv16};
37use crate::obu::temporal_delimiter;
38use crate::quant::ac_q;
39use crate::sequence::sequence_header_obu;
40use crate::tile::{
41 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
42};
43use crate::transform::{
44 TxType, dequant_and_inverse_typed_wh, forward_and_quantize_typed,
45 forward_and_quantize_typed_scaled,
46};
47#[cfg(test)]
48use crate::transform::forward_and_quantize;
49
50/// The side of the larger of the two luma blocks this encoder codes, in
51/// samples.
52const BLOCK: usize = 32;
53
54/// The side of the smaller one, which a 32x32 block may be split into four of.
55const SUB: usize = 16;
56
57/// The side of a superblock, which is what the partition tree starts from.
58pub(crate) const SUPERBLOCK: usize = 64;
59
60// lane-sb128 r1: the superblock size in samples the intra-reach rules
61// (`has_top_right`/`has_bottom_left`) are answered against. libaom masks the
62// block's mi position with `mi_size_wide[cm->seq_params->sb_size] - 1` and
63// tests the "top row"/"rightmost column" of THAT superblock, so a 128x128
64// superblock changes every answer inside it (the tables themselves are
65// already laid out 128-relative -- see `Reach::table_stride`). [`SUPERBLOCK`]
66// stays the encoder's own fixed 64.
67
68/// Sets the superblock size [`Reach`] answers against (64 or 128).
69pub(crate) fn set_reach_superblock_px(px: usize, fctx: &crate::decode::FrameCtx) {
70 fctx.reach_sb_px.with(|c| c.set(px));
71}
72
73fn reach_sb_px(fctx: &crate::decode::FrameCtx) -> usize {
74 fctx.reach_sb_px.with(|c| c.get())
75}
76
77/// How heavily the mode search weighs rate against squared error, in units of
78/// the quantizer's reconstruction step squared per bit.
79///
80/// Swept three times over his clips and three synthetic pictures
81/// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in
82/// the three lane reports). The first sweep, before the mode symbol was
83/// costed, put the best point at 0.05; costing it moved the point to 0.1. The
84/// third sweep, after the levels were costed through the writer's own CDFs
85/// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98%
86/// on film and -0.20% against -0.14% on screen capture.
87///
88/// The fourth sweep (lane-av1lambda) ran the BD gates themselves rather than
89/// those ladders, and 0.1 was far off the point: the rate term was carrying
90/// roughly twice the weight it is worth. 640x384 gate, BD-rate vs libaom /
91/// vs rav1e for 1080p film, 2160p film, screen capture:
92///
93/// | lambda | 1080p | 2160p | screen |
94/// |--------|-------|-------|--------|
95/// | 0.0125 | +78.0 / +31.3 | +90.8 / +46.5 | +57.2 / -0.3 |
96/// | 0.025 | +71.5 / +28.4 | +87.0 / +46.5 | +50.4 / -3.8 |
97/// | 0.0375 | +71.2 / +28.5 | +84.3 / +45.4 | +48.7 / -4.4 |
98/// | 0.05 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
99/// | 0.075 | +74.8 / +32.7 | +91.3 / +52.8 | +51.4 / -1.3 |
100/// | 0.1 | +79.2 / +36.9 | +97.7 / +58.8 | +53.1 / -0.4 |
101/// | 0.125 | +84.0 / +41.1 | +100.7 / +61.5 | +56.8 / +2.3 |
102/// | 0.15 | +86.0 / +42.9 | +104.4 / +65.2 | +59.5 / +4.2 |
103/// | 0.2 | +89.6 / +45.5 | +109.9 / +69.8 | +62.3 / +7.3 |
104///
105/// and on the native 1920x1024 crops, which is the table that decides:
106///
107/// | lambda | film 1080p | film 2160p | screen |
108/// |--------|------------|------------|--------|
109/// | 0.025 | +17.1 / -0.5 | +49.0 / +21.1 | +51.5 / -15.1 |
110/// | 0.0375 | +16.3 / -1.0 | +47.5 / +19.7 | +50.7 / -15.1 |
111/// | 0.05 | +17.0 / -0.3 | +47.0 / +19.2 | +51.6 / -14.2 |
112/// | 0.1 | +18.1 / +0.9 | +47.1 / +19.0 | +58.3 / -9.8 |
113///
114/// 0.0375 was the best point on two clips of three there and cost the "2160p
115/// film" row +0.4/+0.7, outside the +-0.3 band every other lever here is kept
116/// inside, so 0.05 shipped. BOTH of those tables' "film" rows are the
117/// `testsrc2` COLOUR BARS fixtures (see [`bd_rate_screen_native`]), ~90% of
118/// whose cells have no intra cost -- no real film supported the point.
119///
120/// FIFTH SWEEP (lane-av1resweep, 2026-09-07), on the native gate's two REAL
121/// film crops (film A 1080p, film B 2160p HDR) plus the capture, BD-rate vs
122/// libaom / vs rav1e, everything else at the shipped defaults:
123///
124/// | lambda | bars 1080p | bars 2160p | film A | film B | screen |
125/// |--------|------------|------------|--------|--------|--------|
126/// | 0.02 | +17.5 / -0.2 | +49.7 / +21.7 | +65.8 / +35.0 | +91.2 / +55.4 | +53.4 / -14.1 |
127/// | 0.0275 | +16.6 / -0.9 | +48.3 / +20.5 | +65.5 / +34.7 | +91.6 / +55.1 | +51.3 / -15.0 |
128/// | 0.035 | +16.1 / -1.3 | +47.5 / +19.7 | +66.4 / +35.2 | +94.2 / +56.9 | +50.8 / -15.1 |
129/// | 0.05 | +15.6 / -1.7 | +46.5 / +18.8 | +69.0 / +37.5 | +100.0 / +61.5 | +51.0 / -14.5 |
130/// | 0.07 | +16.6 / -0.5 | +46.8 / +18.8 | +72.3 / +40.4 | +108.5 / +68.8 | +54.4 / -12.4 |
131/// | 0.1 | +16.5 / -0.7 | +46.6 / +18.7 | +76.9 / +44.4 | +118.2 / +77.1 | +57.3 / -10.1 |
132///
133/// Real film wants roughly HALF the rate weight the bars asked for: the bowl
134/// on both film rows bottoms between 0.02 and 0.0275 and is 5-11 points deep
135/// against the shipped 0.05, while the bars rows walk the other way (they are
136/// recorded, not decided on). 0.02 breaks the capture (+2.4 vs libaom), so
137/// 0.0275 ships -- both films 3.5/8.4 points down vs libaom, the capture
138/// +0.3/-0.5 (at the +-0.3 band, and better than baseline once the var-tx
139/// defaults below are on: +50.1 / -15.4). It spends ~5% more encode wall.
140const LAMBDA_SCALE: f64 = 0.0275;
141
142/// The rate weight a HIDDEN frame (a pyramid ARF, coded but not shown) codes
143/// under, as a multiple of [`LAMBDA_SCALE`] (lane-arfcen).
144///
145/// The ARF-vs-ARF census says our top ARF codes residual over HALF its area
146/// (rav1e's, at the same display position, over 26-30%) and comes out 1.4-2.5x
147/// its bytes at the same PSNR, while every leaf that predicts from it is
148/// still 0.4 dB behind rav1e's -- i.e. the ARF's extra fidelity is bought at
149/// a rate weight fitted on shown frames and does not propagate. This is the
150/// one knob that prices a hidden frame's rate differently from its q, which
151/// the pyramid's q offsets cannot do (they move lambda and step together).
152const HIDDEN_LAMBDA_FACTOR: f64 = 1.0;
153
154/// [`HIDDEN_LAMBDA_FACTOR`], swept by `EC_AV1_LAMBDA_HIDDEN` in any build.
155fn hidden_lambda_factor() -> f64 {
156 match std::env::var("EC_AV1_LAMBDA_HIDDEN").ok().and_then(|v| v.parse().ok()) {
157 Some(f) => f,
158 None => HIDDEN_LAMBDA_FACTOR,
159 }
160}
161
162/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
163/// picks it is the thing running. A release build has no such knob.
164fn lambda_scale() -> f64 {
165 let swept = std::env::var("EC_AV1_LAMBDA")
166 .ok()
167 .and_then(|v| v.parse::<f64>().ok());
168 match swept {
169 Some(scale) if cfg!(test) => scale,
170 _ => LAMBDA_SCALE,
171 }
172}
173
174/// How a key frame's lambda differs from an inter frame's: libaom weighs the
175/// two apart (`rd_frame_type_factor`, key 128 against an inter frame's 144 out
176/// of 128), because every later frame predicts from the key frame, so an error
177/// left in it is paid for over the whole group. This encoder has no temporal
178/// propagation model at all, and this factor is the cheapest stand-in for one.
179/// Swept by `EC_AV1_LAMBDA_KEY` in a test build, like [`lambda_scale`].
180///
181/// MEASURED and NOT KEPT. 640x384 gate at [`LAMBDA_SCALE`] 0.05, BD vs
182/// libaom / vs rav1e:
183///
184/// | k_key | 1080p | 2160p | screen |
185/// |---|---|---|---|
186/// | 1.0 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
187/// | 0.85 | +71.5 / +29.4 | +87.0 / +48.3 | +49.7 / -3.9 |
188/// | 0.7 | +71.3 / +28.9 | +87.2 / +48.6 | +49.4 / -4.1 |
189/// | 0.5 | +71.4 / +28.9 | +88.7 / +49.6 | +50.1 / -3.4 |
190///
191/// The two films want the key frame coded finer and the screen capture wants
192/// the opposite, by about the same amount, and at native the whole lever is
193/// inside the +-0.3 band that decides nothing: k_key 0.7 reads +16.9 / -0.3,
194/// +47.2 / +19.2, +51.4 / -14.7 against 1.0's +17.0 / -0.3, +47.0 / +19.2,
195/// +51.6 / -14.2. A gate whose GOP is one key frame in twelve cannot see a
196/// per-frame-type weight; the real lever here is temporal propagation
197/// (libaom's `tpl`), which weighs each BLOCK by how much of it later frames
198/// predict from, not each frame.
199const KEY_LAMBDA_FACTOR: f64 = 1.0;
200
201/// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build.
202fn key_lambda_factor() -> f64 {
203 match std::env::var("EC_AV1_LAMBDA_KEY").ok().and_then(|v| v.parse::<f64>().ok()) {
204 Some(k) if cfg!(test) => k,
205 _ => KEY_LAMBDA_FACTOR,
206 }
207}
208
209// Every frame's predicted coefficient bits since the last
210// `take_predicted_bits`, in coding order -- the encoder half of
211// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement.
212#[cfg(test)]
213thread_local! {
214 static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) };
215}
216
217/// Records one frame's predicted coefficient bits.
218#[cfg(test)]
219fn record_predicted_bits(bits: f64) {
220 PREDICTED_BITS.with(|p| p.borrow_mut().push(bits));
221}
222
223/// Takes (and clears) what the frames encoded on this thread were predicted to
224/// spend on coefficients.
225#[cfg(test)]
226pub(crate) fn take_predicted_bits() -> Vec<f64> {
227 PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut()))
228}
229
230/// Whether a 16x16 inter leaf may split into four 8x8 ones of its own.
231pub(crate) const SPLIT_INTER_8: bool = true;
232
233/// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
234/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
235/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0`
236/// turns it off for an A/B on one build.
237/// Whether an INTER frame also carries `TxMode::Select`: an inter block's
238/// residual as one transform over the whole block or as the four transforms
239/// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every
240/// intra block inside the inter frame. ON since lane-av1tx2, which found why
241/// the streams desynced -- the writer counted the [`crate::decode::
242/// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the
243/// reader drops the term -- and measured the split search: BD-rate vs libaom
244/// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the
245/// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an
246/// A/B on one build.
247fn tx_select_inter() -> bool {
248 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
249 crate::envflags::var("EC_AV1_TX_SELECT_INTER")
250 .ok()
251 .map(|v| !matches!(v.as_str(), "0" | "off"))
252 });
253 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER))
254}
255
256/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`, control
257/// vs arm): the capture row goes +27.8/-26.0 -> +20.8/-30.1 -- seven points
258/// against libaom -- while BOTH film rows LOSE (film A +21.7/-4.4 ->
259/// +22.1/-4.0, film B +26.9/-0.6 -> +28.1/+0.7) and 2160p bars lose 0.8/1.1.
260/// The keep rule wants both films down, so this takes the same content gate
261/// palette, intrabc and the angle-delta refinement already stand behind: a
262/// non-screen frame is byte-identical to the encoder before the lane.
263///
264/// The transform types an intra luma transform unit of `set` may be coded
265/// with -- exactly the alphabet the writer's `tx_type` symbol names for that
266/// set, so a searched type is always one the tile can express (lane-txset).
267/// `DCT_DCT` first: it is the incumbent every other candidate has to beat.
268///
269/// Under this encoder's `reduced_tx_set` header bit every intra set at 16x16
270/// and below is `TX_SET_INTRA_2` (spec `get_tx_set`), the five types
271/// [`TxType::from_symbol`] names; 32x32 and 64x64 luma code no symbol at all,
272/// and inter luma reads the two-type `TX_SET_INTER_3`, left at `DCT_DCT`
273/// here.
274pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
275 const DCT: [TxType; 1] = [TxType::DctDct];
276 const INTRA1: [TxType; 7] = [
277 TxType::DctDct,
278 TxType::AdstAdst,
279 TxType::AdstDct,
280 TxType::DctAdst,
281 TxType::Idtx,
282 TxType::VDct,
283 TxType::HDct,
284 ];
285 const INTRA2: [TxType; 5] = [
286 TxType::DctDct,
287 TxType::AdstAdst,
288 TxType::AdstDct,
289 TxType::DctAdst,
290 TxType::Idtx,
291 ];
292 match set {
293 TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4
294 if intra_tx_search_on(screen) =>
295 {
296 &INTRA2
297 }
298 // lane-txi: a `reduced_tx_set == 0` frame's intra 8x8/4x4 reads the
299 // SEVEN-type `TX_SET_INTRA_1` (`decode::txbset_for`'s `Luma{8,4}Set1`;
300 // 16x16 stays `TX_SET_INTRA_2`, there is no `Luma16Set1`). The two
301 // extra members are the 1-D DCTs, and the order is the reader's own
302 // map (`decode::tx_type_from_symbol`, 8-wide CDF).
303 TxbSet::Luma8Set1 | TxbSet::Luma4Set1
304 if intra_tx_search_on(screen) =>
305 {
306 &INTRA1
307 }
308 _ => &DCT,
309 }
310}
311
312/// The transform types an INTER luma transform unit of `set` may be coded
313/// with (lane-txset2). Under this encoder's `reduced_tx_set` header bit every
314/// inter luma set at 16x16 and below is the two-type `TX_SET_INTER_3`
315/// (`IDTX`, `DCT_DCT`) and 32x32 is `EXT_TX_SET_DCT_IDTX` -- the same two
316/// types, a symbol the writer already codes and never varied. 64x64 codes no
317/// `tx_type` symbol at all, so it is not offered one.
318/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`): the
319/// capture row goes +20.8/-30.1 -> +20.1/-30.4 while the two synthetic bars
320/// rows lose TWENTY points (-1.0/-16.8 -> +23.1/+3.3 and +9.4/-12.7 ->
321/// +31.2/+3.7) and film B 0.3 -- the `local-rd-on-references` class at its
322/// loudest, and restricting the offer to 16x16 and below does not soften it
323/// (`le16`: +22.9/+3.1, +31.6/+4.0). So this takes the same content gate the
324/// intra search, palette and intrabc stand behind: a non-screen frame is
325/// byte-identical to the encoder before the lane.
326///
327/// `EC_AV1_TXSET_INTER`: `0`/`off`, `screen` (screen frames only), `le16`
328/// (16x16 and below, the sizes libaom's own census picks a non-`DCT_DCT`
329/// inter type on -- it never takes `IDTX` at 32x32 on film B), anything else
330/// on for every frame at every size.
331pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
332 const DCT: [TxType; 1] = [TxType::DctDct];
333 const INTER3: [TxType; 2] = [TxType::DctDct, TxType::Idtx];
334 const INTER_WIDE: [TxType; 7] = [
335 TxType::DctDct,
336 TxType::AdstAdst,
337 TxType::AdstDct,
338 TxType::DctAdst,
339 TxType::Idtx,
340 TxType::VDct,
341 TxType::HDct,
342 ];
343 let mode = inter_tx_type_search();
344 let on = match mode {
345 InterTxSearch::Off => false,
346 InterTxSearch::Screen => screen,
347 InterTxSearch::All | InterTxSearch::Le16 => true,
348 };
349 match set {
350 TxbSet::Luma32Inter if on && mode != InterTxSearch::Le16 => &INTER3,
351 TxbSet::Luma16Inter | TxbSet::Luma8Inter | TxbSet::Luma4Inter if on => &INTER3,
352 // lane-txi: a `reduced_tx_set == 0` frame's inter 16x16 reads the
353 // TWELVE-type `TX_SET_INTER_2` and its 8x8/4x4 `ALL16` (inter 32x32
354 // stays the two-type `DCT_IDTX`). The seven offered here are the
355 // members those two alphabets SHARE with the intra set -- the four
356 // DTT combinations, `IDTX` and the two 1-D DCTs -- which is the
357 // candidate list rav1e's speed 6 prunes to; the FLIPADST family and
358 // the 1-D ADSTs are codable and left unoffered (deferred).
359 TxbSet::Luma16InterSet1 | TxbSet::Luma8InterSet1 | TxbSet::Luma4InterSet1 if on => {
360 &INTER_WIDE
361 }
362 _ => &DCT,
363 }
364}
365
366/// lane-txi: does THIS frame code `reduced_tx_set = 0` (spec 5.9.2), i.e.
367/// the wider `tx_type` alphabets at intra 8x8/4x4 and inter 16x16 and below?
368/// `EC_AV1_TXSET_WIDE`: `0`/`off`, `screen` (screen frames only), anything
369/// else every frame; unset takes [`crate::speed::WIDE_TX_SET`], screen-gated
370/// like both halves of the type search itself.
371pub(crate) fn wide_tx_set(screen: bool) -> bool {
372 match WIDE_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
373 0 => return false,
374 1 => return true,
375 _ => {}
376 }
377 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
378 crate::envflags::var("EC_AV1_TXSET_WIDE").ok().map(|v| match v.as_str() {
379 "0" | "off" => InterTxSearch::Off,
380 "screen" => InterTxSearch::Screen,
381 _ => InterTxSearch::All,
382 })
383 });
384 match ENV.unwrap_or(if crate::speed::at(&crate::speed::WIDE_TX_SET) {
385 InterTxSearch::Screen
386 } else {
387 InterTxSearch::Off
388 }) {
389 InterTxSearch::Off => false,
390 InterTxSearch::Screen => screen,
391 _ => true,
392 }
393}
394
395/// A PROCESS-GLOBAL [`wide_tx_set`] override that wins over both the
396/// environment and the preset (`u8::MAX` = unset), the shape
397/// [`set_inter_tx_search`] has: the lever is OFF at every preset, so the
398/// witness that has to see the wider alphabets turns it on through this while
399/// holding [`crate::speed::knob_write`].
400static WIDE_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
401 std::sync::atomic::AtomicU8::new(u8::MAX);
402
403/// Sets [`WIDE_TX_OVERRIDE`]; `None` clears it.
404#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
405pub(crate) fn set_wide_tx_set(on: Option<bool>) {
406 WIDE_TX_OVERRIDE.store(
407 on.map_or(u8::MAX, u8::from),
408 std::sync::atomic::Ordering::Relaxed,
409 );
410}
411
412/// The luma [`TxbSet`] the SEARCH and its pricer name for a frame that codes
413/// `reduced_tx_set = 0`: the writer reads the bit once, off the frame's own
414/// [`crate::cdf_state::Cdfs`], but the trial that prices a type has to read
415/// the same alphabet or the two disagree on what a `tx_type` symbol costs.
416pub(crate) fn luma_set_for(set: TxbSet, screen: bool) -> TxbSet {
417 if wide_tx_set(screen) {
418 set.wide()
419 } else {
420 set
421 }
422}
423
424#[derive(Clone, Copy, PartialEq)]
425pub(crate) enum InterTxSearch {
426 Off,
427 Screen,
428 /// 16x16 and below only.
429 Le16,
430 All,
431}
432
433/// A PROCESS-GLOBAL [`inter_tx_type_search`] override that wins over both the
434/// environment and the preset (`u8::MAX` = unset), the shape
435/// [`set_deltaq_res`] has: the lever is OFF at every preset, so the witness
436/// that has to see a non-`DCT_DCT` inter unit turns it on through this while
437/// holding [`crate::speed::knob_write`].
438static INTER_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
439 std::sync::atomic::AtomicU8::new(u8::MAX);
440
441/// Sets [`INTER_TX_OVERRIDE`]; `None` clears it.
442#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
443pub(crate) fn set_inter_tx_search(on: Option<bool>) {
444 INTER_TX_OVERRIDE.store(
445 on.map_or(u8::MAX, u8::from),
446 std::sync::atomic::Ordering::Relaxed,
447 );
448}
449
450fn inter_tx_type_search() -> InterTxSearch {
451 match INTER_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
452 0 => return InterTxSearch::Off,
453 1 => return InterTxSearch::All,
454 _ => {}
455 }
456 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
457 crate::envflags::var("EC_AV1_TXSET_INTER").ok().map(|v| match v.as_str() {
458 "0" | "off" => InterTxSearch::Off,
459 "screen" => InterTxSearch::Screen,
460 "le16" => InterTxSearch::Le16,
461 _ => InterTxSearch::All,
462 })
463 });
464 ENV.unwrap_or_else(|| {
465 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH_INTER) {
466 InterTxSearch::Screen
467 } else {
468 InterTxSearch::Off
469 }
470 })
471}
472
473/// The inter luma [`TxbSet`] a `tx`-sided transform unit reads, `None` for the
474/// 64-point one (it codes no `tx_type` symbol).
475/// lane-txw history, resolved by lane-intertx: the INTER half of the
476/// widening was blocked by `refusal-from-own-desync` twice over. Half of it
477/// was this writer coding a `V_DCT`/`H_DCT` unit as `TX_CLASS_2D`
478/// (`tile::write_coeffs`, fixed by lane-txw, which unblocked the intra
479/// half). The other half was the CHROMA inheritance: an inter block's
480/// chroma transform type is the luma type reduced to the chroma size's set
481/// (`decode::reduce_inherited_chroma_tx_type`), and (a) the encoder never
482/// set `FrameCtx::reduced_tx_set_inter`, so [`recode_inter_chroma`] reduced
483/// against a STALE allowance, and (b) `tile::write_block_planes` coded
484/// every chroma plane as `DCT_DCT`, so an inherited 1-D type desynced the
485/// chroma exactly as luma did. lane-intertx fixed both -- the frame sets
486/// its own bit on the context (`encode_inter_frame`), the writer derives
487/// the chroma type from this frame's own header bit
488/// (`reduce_inherited_chroma_tx_type_flagged`) -- and the widened SEARCH
489/// names these sets through [`luma_set_for`] at its call sites, so the
490/// wider candidates are reachable and honestly priced. The intra half
491/// never needed either (an intra block's chroma type comes off its own UV
492/// mode, never off luma).
493fn inter_luma_set(tx: usize) -> Option<TxbSet> {
494 Some(match tx {
495 4 => TxbSet::Luma4Inter,
496 8 => TxbSet::Luma8Inter,
497 16 => TxbSet::Luma16Inter,
498 32 => TxbSet::Luma32Inter,
499 _ => return None,
500 })
501}
502
503fn tx_type_search() -> bool {
504 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
505 crate::envflags::var("EC_AV1_TXSET")
506 .ok()
507 .map(|v| !matches!(v.as_str(), "0" | "off"))
508 });
509 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH))
510}
511
512/// Whether an intra luma unit of this frame searches its own type at all:
513/// the preset lever ([`tx_type_search`]) under the screen content gate, which
514/// `EC_AV1_TXSET=all` ([`intra_tx_all_frames`]) lifts and the process-global
515/// [`set_intra_tx_search`] override wins over (the witness needs the search
516/// on a frame the detector called non-screen).
517fn intra_tx_search_on(screen: bool) -> bool {
518 match INTRA_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
519 0 => return false,
520 1 => return true,
521 _ => {}
522 }
523 (screen || intra_tx_all_frames()) && tx_type_search()
524}
525
526/// A PROCESS-GLOBAL [`intra_tx_search_on`] override (`u8::MAX` = unset), the
527/// shape [`set_inter_tx_search`] has.
528static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 =
529 std::sync::atomic::AtomicU8::new(u8::MAX);
530
531/// Sets [`INTRA_TX_OVERRIDE`]; `None` clears it.
532#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
533pub(crate) fn set_intra_tx_search(on: Option<bool>) {
534 INTRA_TX_OVERRIDE.store(
535 on.map_or(u8::MAX, u8::from),
536 std::sync::atomic::Ordering::Relaxed,
537 );
538}
539
540/// lane-txi: `EC_AV1_TXSET=all` offers the five-type intra set on EVERY
541/// frame -- the unconditional arm the gate measures -- instead of the screen
542/// content gate [`tx_type_candidates`] ships behind. Any other value keeps
543/// the gate (`0`/`off` still switches the search off entirely).
544fn intra_tx_all_frames() -> bool {
545 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
546 crate::envflags::var("EC_AV1_TXSET").is_ok_and(|v| v == "all")
547 });
548 *ENV
549}
550
551fn tx_select() -> bool {
552 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
553 crate::envflags::var("EC_AV1_TX_SELECT")
554 .ok()
555 .map(|v| !matches!(v.as_str(), "0" | "off"))
556 });
557 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY))
558}
559
560fn split_inter_8() -> bool {
561 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
562 Some(v) if cfg!(test) => v != "0",
563 _ => crate::speed::at(&crate::speed::SPLIT_8),
564 }
565}
566
567/// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
568/// NEARESTMV candidate it always had.
569pub(crate) const LEAF_NEW_MV: bool = true;
570
571/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
572/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
573/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
574/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
575pub(crate) const EXTRA_REF_NEW_MV: bool = true;
576
577/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
578/// own best vector before that reference's `NEWMV` search is skipped: a
579/// factor on the search cost scale, `1.0` meaning "as good or better".
580/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
581/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
582/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
583/// extra searches drop from +27% to +4% of the base count -- and on screen
584/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
585/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
586/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: 0.25
587/// reads +16.6/-0.6, +47.0/+19.1, +51.3/-14.3 and 0.5 reads +16.6/-0.7,
588/// +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, +47.0/+19.1,
589/// +51.3/-14.3 -- one row 0.1-0.2 down, two flat, inside the measurement's
590/// own noise. 0.35 stays; the lever that did move at the new rate weight is
591/// [`LEAF_SECOND_NEW_MARGIN`], not this one.
592const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
593
594/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
595fn extra_new_skip_margin() -> f64 {
596 match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
597 Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
598 _ => EXTRA_NEW_SKIP_MARGIN,
599 }
600}
601
602/// The margin on a LEAF's SECOND-reference motion search, the same early-out
603/// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference
604/// `NEWMV`: the search is skipped when that reference's own
605/// `NEAREST_NEARESTMV` vector already prices this many times better than the
606/// leaf's `LAST` search found. `0.0` never skips.
607///
608/// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs
609/// libaom (1080p/2160p/screen) against the extra `motion::search` calls at
610/// 2160p (38195 with no second-reference search at all):
611/// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093,
612/// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at
613/// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the
614/// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter
615/// of its extra searches; past it the calls double for another -0.3/-0.5.
616/// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is
617/// all `NEAREST_NEARESTMV` and no searched second vector ever wins there --
618/// so the margin is pure wall on that content (+10% searches at 0.8).
619///
620/// RE-SWEPT on lane-av1rejudge after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, on
621/// the native gate with local warp on, BD vs libaom / vs rav1e:
622///
623/// | margin | film 1080p | film 2160p | screen |
624/// |---|---|---|---|
625/// | 0.6 | +16.9 / -0.4 | +47.0 / +19.1 | +51.2 / -14.4 |
626/// | 0.8 (was) | +16.7 / -0.5 | +47.0 / +19.1 | +51.3 / -14.3 |
627/// | 1.2 | +16.2 / -1.1 | +46.6 / +18.8 | +51.3 / -14.4 |
628/// | 1.6 | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
629/// | 0.0 (never skip) | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
630///
631/// 1.2 is the floor of that bowl -- two rows 0.3-0.6 down on BOTH columns
632/// with screen flat -- and it beats never-skipping, i.e. the early-out is
633/// still worth having, just at a looser margin than the old rate weight
634/// wanted. It costs about 10% encoder wall on the two film clips (36.6s vs
635/// 32.6s at 2160p), which is the price of the extra second-reference
636/// searches.
637const LEAF_SECOND_NEW_MARGIN: f64 = 1.2;
638
639/// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the
640/// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`.
641fn leaf_second_new_margin() -> f64 {
642 match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() {
643 Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN),
644 None => LEAF_SECOND_NEW_MARGIN,
645 }
646}
647
648/// Whether a leaf searches its SECOND reference at all (lane-av1comp4).
649fn leaf_second_new_mv() -> bool {
650 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
651 Some(v) => v != "0",
652 None => crate::speed::at(&crate::speed::LEAF_SECOND),
653 }
654}
655
656/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
657/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
658/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
659/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
660/// was missing was the encoder ever forming one below 32x32.
661pub(crate) const LEAF_COMPOUND: bool = true;
662
663/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
664fn leaf_compound() -> bool {
665 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
666 Some(v) => v != "0",
667 None => crate::speed::at(&crate::speed::LEAF_COMPOUND),
668 }
669}
670
671/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
672fn leaf_new_mv() -> bool {
673 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
674 Some(v) if cfg!(test) => v != "0",
675 _ => LEAF_NEW_MV,
676 }
677}
678
679/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
680/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
681/// the true frame edge cut through was ever split there; inside the frame
682/// every block was coded whole, which left the partition decision the key
683/// frame already makes unmade for eleven frames out of twelve.
684pub(crate) const SPLIT_INTER_BLOCKS: bool = true;
685
686/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
687/// measurement that keeps it is running (test builds only, like
688/// [`lambda_scale`]).
689fn split_inter_blocks() -> bool {
690 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
691 Some(v) if cfg!(test) => v != "0",
692 _ => crate::speed::at(&crate::speed::SPLIT_INTER),
693 }
694}
695
696/// Whether the inter search offers the whole superblock as ONE 64x64 block
697/// (`PARTITION_NONE` at `BLOCK_64X64`), coded SKIP, against the four 32x32
698/// quadrants it would otherwise always split into.
699///
700/// The census (`lanes/census-filmB.md`) is what points here: rav1e speed 6
701/// codes 45.2% of its blocks at 64x64 -- 73.8% of its LEAF blocks, 99.2% of
702/// them skip at 328 bytes a frame -- while every block this encoder wrote was
703/// 32x32 or smaller, which put our mode+mv+partition+tx_size spend at 162,669
704/// bits against rav1e's 61,988, about 46% of the film B gap.
705///
706/// lane-tx64: no longer skip-only. The root also prices a REAL residual --
707/// one TX_64X64 luma transform (`transform.rs`'s forward network has always
708/// reached 64 points; what was missing was the block coder and the writer
709/// around it) and one TX_32X32 per chroma plane -- see [`b64_residual`],
710/// which carries that arm's own gate table. Still refused at the 64 root:
711/// compound references, a depth-1 4x32x32 var-tx tree, intra, and a
712/// superblock the true frame edge cuts through.
713///
714/// Switched off by `EC_AV1_B64=0` in any build; `EC_AV1_B64RES=0` keeps the
715/// root and restores the skip-only shape lane-b64 shipped.
716pub(crate) const B64_ROOT: bool = true;
717
718/// How many superblocks took the 64x64 root since the last
719/// [`take_b64_root_hits`], so a gate reports how often it fires rather than
720/// assuming it does (class `gate-blind-to-feature`).
721static B64_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
722
723/// The 64x64-root count since the last call, and zero it.
724pub fn take_b64_root_hits() -> usize {
725 B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
726}
727
728/// Whether the 128 superblock root offers its `PARTITION_NONE` candidate at
729/// all ([`search_root_128`]). On by default; `EC_AV1_B128=0` turns it off,
730/// which is the attribution arm for a 128-superblock stream: it separates
731/// what the SIZE costs from what the 128x128 BLOCK buys.
732fn b128_root() -> bool {
733 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
734 crate::envflags::var("EC_AV1_B128").ok().is_none_or(|v| v != "0")
735 });
736 *ENV
737}
738
739/// lane-b128r: whether the 128 root prices a REAL residual as well as the
740/// skip arm -- four TX_64X64 luma units interleaved with a TX_32X32 chroma
741/// pair per 64x64 mu chunk, var-tx depth 0 (the shape
742/// [`crate::tile::write_inter_block_128`] codes and `decode_inter_block`
743/// reads). Written, witnessed and byte-exact through both decoders, and
744/// **off by default** (`EC_AV1_B128RES=1` turns it on) because it is INERT
745/// on content: the RD takes it 0.7-1.9 times per frame against thousands of
746/// whole 128 roots (lane-b128res census, native 12-frame gate, every clip),
747/// and the BD effect is inside the noise on both gates -- long-GOP films
748/// -0.1/+0.1 and all five 12-frame rows within 0.1 of the off default.
749///
750/// The historical reason for the parking is CLOSED: the bars 2160p q=90
751/// frame 11 disagreement with ffmpeg (8 luma samples at the rows above a
752/// 128-superblock horizontal edge) was the CDEF search pricing a preset per
753/// 64x64 unit under a root that codes ONE literal for all four -- lane-
754/// edge128's `crate::tile::cdef_unit_owner` collapses the four to the one
755/// the decoder derives, and on this HEAD the same row re-measures three-way
756/// EXACT (encoder reconstruction == ffmpeg == `decode_stream`, every frame,
757/// every plane, both gates). The knob stays as the arm's gate, not as a
758/// defect flag.
759fn b128_residual() -> bool {
760 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
761 crate::envflags::var("EC_AV1_B128RES").ok().map(|v| v != "0")
762 });
763 (ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
764 && b128_root()
765}
766/// lane-rectres: whether the 128 root's RECTANGULAR pieces -- the two
767/// HORZ/VERT halves and the four AB shapes' three pieces (two 64x64 squares
768/// plus one half) -- price a REAL residual in the RD as well as the skip arm
769/// ([`search_root_128_rect`] / [`search_root_128_ab`], written through
770/// [`crate::tile::write_inter_block_128_rect`]). **Off by default**
771/// (`EC_AV1_RECTRES=1` turns it on): OFF is today's behavior bit for bit --
772/// no rect/AB piece can come out non-skip, so the writer's refusal is never
773/// reached. The residual shape is the whole 128 block's, halved or quartered
774/// per piece: one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
775/// mu chunk, var-tx depth 0 (exactly what the decoder's mu-chunk loop reads
776/// for any inter partition shape).
777fn rectres() -> bool {
778 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
779 crate::envflags::var("EC_AV1_RECTRES")
780 .ok()
781 .map(|v| v != "0")
782 });
783 ENV.unwrap_or(false) || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed)
784}
785
786/// Test-only: take the rect/AB pieces' residual arm whatever it costs, so a
787/// witness clip codes the shape rather than waiting for content on which the
788/// RD picks it (the same role [`FORCE_B128_RESIDUAL`] plays at the NONE
789/// root). Never read outside `#[cfg(test)]` builds.
790static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =
791 std::sync::atomic::AtomicBool::new(false);
792
793/// Arms [`FORCE_B128_RECTRES`] for the rest of the process.
794#[cfg(test)]
795pub(crate) fn force_b128_rectres(on: bool) {
796 FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed);
797}
798
799/// How many rect/AB pieces the search left WITH a residual rather than
800/// skipped, since the last [`take_b128_rectres_hits`] (class
801/// `gate-blind-to-feature`).
802static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize =
803 std::sync::atomic::AtomicUsize::new(0);
804
805/// The rect/AB-piece-residual count since the last call, and zero it.
806pub fn take_b128_rectres_hits() -> usize {
807 B128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
808}
809
810/// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64
811/// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`,
812/// `NEW_NEARESTMV` over the LAST+GOLDEN / LAST+ALTREF pairs), at the block's
813/// own 32x32-mi window. `EC_AV1_B128COMP=0` turns it off, which is this
814/// arm's attribution control; the writer has always had the path
815/// (`write_inter_block_128` calls `write_compound_block` for a block that
816/// names a second reference).
817fn b128_compound() -> bool {
818 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
819 crate::envflags::var("EC_AV1_B128COMP").ok().map(|v| v != "0")
820 });
821 ENV.unwrap_or(true) && b128_root()
822}
823
824/// How many 128 roots came out COMPOUND since the last
825/// [`take_b128_compound_hits`] (class `gate-blind-to-feature`).
826static B128_COMPOUND_HITS: std::sync::atomic::AtomicUsize =
827 std::sync::atomic::AtomicUsize::new(0);
828
829/// The compound-128 count since the last call, and zero it.
830pub fn take_b128_compound_hits() -> usize {
831 B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
832}
833
834/// lane-b128hv: whether the 128 superblock root offers its `PARTITION_HORZ`
835/// and `PARTITION_VERT` candidates -- two 128x64 / 64x128 inter blocks, the
836/// same skip-only single-reference/compound machinery the NONE arm ships,
837/// halved ([`search_root_128_rect`], `crate::tile::write_inter_block_128_rect`).
838/// `EC_AV1_B128HV=0` is this arm's attribution control.
839fn b128_rect() -> bool {
840 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
841 crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0")
842 });
843 ENV.unwrap_or(true) && b128_root()
844}
845
846/// lane-rectdq: whether the delta_q symbol group is priced on the root
847/// candidates that really code it. `EC_AV1_RECTDQ=0` is this fix's
848/// attribution control (the pre-lane pricing, where a 128 rect root and the
849/// four-superblock arm were both priced as if the group were free).
850fn rectdq() -> bool {
851 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
852 crate::envflags::var("EC_AV1_RECTDQ").ok().map(|v| v != "0")
853 });
854 ENV.unwrap_or(true)
855}
856
857/// lane-rectdq: what `crate::tile::write_delta_q` spends to move
858/// `CurrentQIndex` from `cur` to `target` at `1 << delta_q_res` steps of
859/// `res` -- the same three pieces that writer codes, in its order: the
860/// `delta_q_abs` symbol of `min(abs, 3)` against the DEFAULT table (the
861/// writer's own `cdfs.delta_q`, which every tile arms fresh, adapts from
862/// exactly this row), the escape literal pair when `abs >= 3`, and the sign
863/// bit when `abs != 0`. Zero when the plan is disarmed (`res <= 0`).
864pub(crate) fn delta_q_bits(target: i32, cur: i32, res: i32) -> f64 {
865 if res <= 0 {
866 return 0.0;
867 }
868 /// spec `DELTA_Q_SMALL`, as in the writer.
869 const DELTA_Q_SMALL: usize = 3;
870 let reduced = (target - cur) / res;
871 let abs = reduced.unsigned_abs() as usize;
872 // A pricing coder, not a sum of table entries: the escape's literal bits
873 // are equiprobable SYMBOLS whose narrowing carries the `EC_MIN_PROB`
874 // floor, so each really costs a little over one bit (class
875 // `price-the-narrowing-not-the-table`). Read off the same
876 // `SymbolEncoder::bits` account the writer's own coder keeps.
877 let mut enc = crate::msac::SymbolEncoder::pricer();
878 enc.reset_bits();
879 enc.symbol_fixed(abs.min(DELTA_Q_SMALL), &cdf::DELTA_Q);
880 if abs >= DELTA_Q_SMALL {
881 let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
882 enc.literal(rem_bits - 1, 3);
883 enc.literal(abs as u32 - ((1u32 << rem_bits) + 1), rem_bits);
884 }
885 if abs != 0 {
886 enc.literal(u32::from(reduced < 0), 1);
887 }
888 enc.bits()
889}
890
891/// [`delta_q_bits`] for the 128 superblock root at `(root_r, root_c)` (in 64
892/// superblock units): the group every root shape but a SKIPPED
893/// `PARTITION_NONE` root codes, since decode.rs' `whole_sb` asks for
894/// `side == write_w == write_h == sb_px` and neither a rect half nor a 64
895/// superblock under a 128 grid is that.
896///
897/// The target is the root's own cell of the `sb_q` grid, exactly the entry
898/// `write_delta_q` indexes. `CurrentQIndex` is NOT knowable in the search --
899/// the writer's `plan.cur` only advances at the roots that really code a
900/// group, and which those are is decided by this very comparison -- so the
901/// PREVIOUS 128 root's target in raster order stands in for it (the frame's
902/// `base_q_idx` at the first root of the frame, which is also the writer's
903/// own per-tile reset). Wrong only where a neighbouring root came out a
904/// skipped NONE block, and then only by the difference of two adjacent tpl
905/// cells.
906fn delta_q_bits_at_root(
907 sb_q: Option<&Vec<u8>>,
908 sb_cols: usize,
909 base_q_idx: u8,
910 res: i32,
911 (root_r, root_c): (usize, usize),
912) -> f64 {
913 if !rectdq() || res <= 0 {
914 return 0.0;
915 }
916 let Some(q) = sb_q.filter(|q| !q.is_empty()) else {
917 return 0.0;
918 };
919 let at = |r: usize, c: usize| i32::from(q[(r * sb_cols + c).min(q.len() - 1)]);
920 let target = at(root_r, root_c);
921 let cur = if root_c >= 2 {
922 at(root_r, root_c - 2)
923 } else if root_r >= 2 {
924 // The last 128 root of the row above, i.e. the previous one in the
925 // writer's raster walk.
926 at(root_r - 2, (sb_cols.saturating_sub(1)) & !1)
927 } else {
928 i32::from(base_q_idx)
929 };
930 delta_q_bits(target, cur, res)
931}
932
933/// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT)
934/// halves since the last take (class `gate-blind-to-feature`).
935static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
936/// The VERT twin of [`B128_HORZ_HITS`].
937static B128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
938
939/// The HORZ-128-root count since the last call, and zero it.
940pub fn take_b128_horz_hits() -> usize {
941 B128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
942}
943
944/// The VERT-128-root count since the last call, and zero it.
945pub fn take_b128_vert_hits() -> usize {
946 B128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
947}
948
949/// Test-only: force the 128 root's rect partition whatever it costs -- 0 off,
950/// 1 `PARTITION_HORZ`, 2 `PARTITION_VERT`. The witness needs it because
951/// synthetic content is where the shape is cheapest to decode-check and the
952/// RD there prefers one whole block; the gate census is the unforced count.
953static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
954
955/// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT).
956#[cfg(test)]
957pub(crate) fn force_b128_rect(which: u8) {
958 FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed);
959}
960
961/// lane-ab128: whether the 128 superblock root offers its four AB shapes --
962/// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one
963/// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128
964/// right) and `_VERT_B` (one 64x128 left, two 64x64 right). Every piece is
965/// the same skip-only single-reference/compound block the NONE and HORZ/VERT
966/// arms ship, at its own footprint ([`search_root_128_ab`],
967/// `crate::tile::write_inter_block_128_rect`). `EC_AV1_B128AB=0` is this
968/// arm's attribution control.
969///
970/// **Off by default** (`EC_AV1_B128AB=1` turns it on): measured on both gates
971/// and it does not pay. The shapes fire 0-2 roots a frame against ~1000 coded
972/// blocks (`EC_AV1_B128_CENSUS`), and every row is flat or 0.1 worse --
973/// long-GOP film A +22.0/-8.5 against a +21.9/-8.6 control, film B +75.8/+0.8
974/// against the same, 12-frame film A +18.1/-6.2 against +18.0/-6.3, film B
975/// +23.1/-3.3 against +23.0/-3.5, screen byte-identical (lane-ab128). The
976/// machinery is written, witnessed sample-exact through both decoders on all
977/// four shapes, and kept for the arm that makes it pay: a non-skip piece (the
978/// 64x64 pieces could carry the 64 root's residual, which is where libaom's
979/// AB shapes earn their keep) or a cheaper partition price.
980fn b128_ab() -> bool {
981 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
982 crate::envflags::var("EC_AV1_B128AB").ok().map(|v| v != "0")
983 });
984 ENV.unwrap_or(false) && b128_root()
985}
986
987/// How many 128 roots the search left as each AB shape since the last take,
988/// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order (class
989/// `gate-blind-to-feature`).
990static B128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
991 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
992
993/// The four per-shape AB-root counts since the last call, and zero them.
994pub fn take_b128_ab_hits() -> [usize; 4] {
995 std::array::from_fn(|i| B128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
996}
997
998/// Test-only: force the 128 root's AB shape whatever it costs -- 0 off, then
999/// 4..=7, the partition symbol itself ([`force_b128_rect`]'s twin; synthetic
1000/// content is where the shapes are cheapest to decode-check and the RD there
1001/// prefers one whole block).
1002static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1003
1004/// Arms [`FORCE_B128_AB`] for the rest of the process (0 off, else 4..=7).
1005#[cfg(test)]
1006pub(crate) fn force_b128_ab(which: u8) {
1007 FORCE_B128_AB.store(which, std::sync::atomic::Ordering::Relaxed);
1008}
1009
1010/// lane-ab128: the three pieces of an AB shape at a 128 root, in the order
1011/// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm
1012/// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B =
1013/// top half, BL, BR; VERT_A = TL, BL, right half; VERT_B = left half, TR, BR.
1014/// Each entry is the piece's own top-left in mode-info units and its
1015/// footprint in samples.
1016pub(crate) fn ab128_pieces(
1017 symbol: usize,
1018 (mi_row, mi_col): (usize, usize),
1019) -> [((usize, usize), (usize, usize)); 3] {
1020 const S: usize = SUPERBLOCK;
1021 let (r, c) = (mi_row, mi_col);
1022 let (r1, c1) = (mi_row + 16, mi_col + 16);
1023 match symbol {
1024 // PARTITION_HORZ_A
1025 4 => [((r, c), (S, S)), ((r, c1), (S, S)), ((r1, c), (S * 2, S))],
1026 // PARTITION_HORZ_B
1027 5 => [((r, c), (S * 2, S)), ((r1, c), (S, S)), ((r1, c1), (S, S))],
1028 // PARTITION_VERT_A
1029 6 => [((r, c), (S, S)), ((r1, c), (S, S)), ((r, c1), (S, S * 2))],
1030 // PARTITION_VERT_B
1031 _ => [((r, c), (S, S * 2)), ((r, c1), (S, S)), ((r1, c1), (S, S))],
1032 }
1033}
1034
1035/// Test-only: take the 128 root's residual arm whatever it costs, so a
1036/// witness clip codes the shape rather than waiting for content on which the
1037/// RD picks it (the same role [`force_sb128`] plays for the superblock size).
1038/// Never read outside `#[cfg(test)]` builds.
1039static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool =
1040 std::sync::atomic::AtomicBool::new(false);
1041
1042/// Test-only twin of [`FORCE_B128_RESIDUAL`] for the PARTITION decision: take
1043/// the 128 root whenever it produced a candidate at all, whatever its four
1044/// cells cost, so a witness codes the block it is about rather than waiting
1045/// for content on which the root also wins its own comparison.
1046static FORCE_B128_ROOT: std::sync::atomic::AtomicBool =
1047 std::sync::atomic::AtomicBool::new(false);
1048
1049/// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a
1050/// forced residual block only reaches the writer if its root is taken.
1051#[cfg(test)]
1052pub(crate) fn force_b128_residual(on: bool) {
1053 FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed);
1054 force_b128_root(on);
1055}
1056
1057/// Arms [`FORCE_B128_ROOT`] for the rest of the process.
1058#[cfg(test)]
1059pub(crate) fn force_b128_root(on: bool) {
1060 FORCE_B128_ROOT.store(on, std::sync::atomic::Ordering::Relaxed);
1061}
1062
1063/// How many 128 roots came out cheaper WITH a residual than skipped, since
1064/// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).
1065static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize =
1066 std::sync::atomic::AtomicUsize::new(0);
1067
1068/// The 128-residual count since the last call, and zero it.
1069pub fn take_b128_residual_hits() -> usize {
1070 B128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1071}
1072
1073/// How many 128x128 `PARTITION_NONE` roots the search took since the last
1074/// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result
1075/// is only attributable once the fire count is known.
1076static B128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1077
1078/// The 128x128-root count since the last call, and zero it.
1079pub fn take_b128_none_hits() -> usize {
1080 B128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1081}
1082
1083/// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq).
1084/// Preset-gated: it re-prices the block once per candidate level, so it buys
1085/// bits with wall (see `crate::speed::RDOQ` for the per-preset table).
1086///
1087/// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser --
1088/// which is what the byte pins are taken under when they name it.
1089fn rdoq_on() -> bool {
1090 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1091 crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0")
1092 });
1093 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ))
1094}
1095
1096/// The rate weight [`crate::tile::rdoq`] trades bits for squared error at, in
1097/// units of one squared AC quantiser step -- the search's own
1098/// [`LAMBDA_SCALE`], so the quantiser and the mode search speak one currency.
1099///
1100/// The per-frame factors the search multiplies onto it ([`key_lambda_factor`],
1101/// [`hidden_lambda_factor`], both 1.0 as shipped) and the per-superblock
1102/// temporal map ([`tpl_lambda_factors`]) are NOT threaded down here:
1103/// corner-cut, ceiling = a superblock the temporal map weighs away from the
1104/// frame average has its coefficients optimised at the frame's weight. The
1105/// upgrade is one `lambda` field on the trial call sites, which is the whole
1106/// mode-search argument list.
1107///
1108/// SWEPT (lane-rdoq, 12-frame `bd_rate_screen_native`, BD vs libaom
1109/// `cpu-used 6` on the three real rows). The bowl is a factor of TWO above
1110/// the mode search's own weight, and it is the same multiplier on all three
1111/// rows:
1112///
1113/// | `EC_AV1_RDOQ_LAMBDA` | film A | film B | screen |
1114/// |---|---|---|---|
1115/// | 0.7 | +27.6 | +39.5 | +29.6 |
1116/// | 1.0 | +26.3 | +37.5 | +29.1 |
1117/// | 1.3 | +25.6 | +37.0 | +28.8 |
1118/// | 1.6 | +24.6 | +35.9 | +28.7 |
1119/// | 2.2 (shipped) | +24.4 | +35.5 | +28.1 |
1120/// | 3.2 | +24.7 | +36.1 | +29.4 |
1121///
1122/// A coefficient's rate is worth twice here what the mode search prices it
1123/// at, and the likeliest reason is that the price is taken against tables
1124/// that have not adapted yet ([`crate::tile::coeff_bits`]): a block coded
1125/// late in a frame whose `txb_skip`/`base` tables have narrowed really costs
1126/// less than the pricer says, and this pass is the one decision taken per
1127/// COEFFICIENT, so it feels that error most. The honest fix is an adapted
1128/// price, not a fitted multiplier; this is the fitted multiplier, and its
1129/// bowl is measured rather than assumed.
1130const RDOQ_LAMBDA_MULT: f64 = 2.2;
1131
1132/// [`RDOQ_LAMBDA_MULT`], or what `EC_AV1_RDOQ_LAMBDA` names (the rate-term
1133/// calibration sweep).
1134fn rdoq_lambda() -> f64 {
1135 static MULT: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
1136 crate::envflags::var("EC_AV1_RDOQ_LAMBDA")
1137 .ok()
1138 .and_then(|v| v.parse().ok())
1139 .unwrap_or(RDOQ_LAMBDA_MULT)
1140 });
1141 lambda_scale() * *MULT
1142}
1143
1144/// [`B64_ROOT`], or what `EC_AV1_B64` names.
1145fn b64_root() -> bool {
1146 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1147 crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0")
1148 });
1149 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))
1150}
1151
1152/// The KEY frame's own 64x64 root (lane-i64): the whole superblock searched
1153/// as ONE intra block -- every mode the 32x32 search offers, one TX_64X64
1154/// luma transform (`TxbSet::Luma64`, whose coded quarter is the 32x32 corner)
1155/// and one TX_32X32 per chroma plane -- and compared against the four 32x32
1156/// quadrants at the same lambda, exactly the shape the inter root
1157/// ([`B64_ROOT`]) takes on an inter frame. The writer has always been able to
1158/// code one (`crate::tile::sb_coeff_key_frame_tile`'s `Superblock::Whole`);
1159/// nothing produced one, so the key frame -- 21.6% of a real film stream --
1160/// coded every superblock split while libaom and rav1e leave 45-54% of theirs
1161/// whole.
1162///
1163/// No CfL (spec `is_cfl_allowed` stops at 32x32, and `search_chroma` gates on
1164/// it), no filter intra (`filter_intra_size_class` has no 64 row) and no
1165/// transform-depth split (the writer's `Superblock::Whole` arm takes a 32x32
1166/// level grid, so only depth 0 is representable) -- the root is refused
1167/// outright on an `allow_intrabc` frame, whose quadrant searches carry DV
1168/// state a discarded trial would desync.
1169///
1170/// Switched off by `EC_AV1_I64=0` in any build.
1171pub(crate) const I64_ROOT: bool = true;
1172
1173/// How many key-frame superblocks were coded as one 64x64 intra block since
1174/// the last [`take_i64_root_hits`], so a gate reports the fire rate rather
1175/// than assuming it (class `gate-blind-to-feature`).
1176/// Index 1 is how many were OFFERED the trial at all, so a gate reads a
1177/// SHARE and not a bare count, and index 2 how many of the whole ones sat on
1178/// a superblock the true frame edge CUTS THROUGH (lane-corner) -- the
1179/// `gate-blind-to-feature` guard for the edge path, which no
1180/// superblock-aligned clip fires at all.
1181static I64_HITS: [std::sync::atomic::AtomicUsize; 3] =
1182 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
1183
1184/// The key-frame `(whole, offered, edge)` 64x64-intra-root counts since the
1185/// last call, and zero them.
1186pub fn take_i64_root_hits() -> [usize; 3] {
1187 std::array::from_fn(|i| I64_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1188}
1189
1190/// [`I64_ROOT`], or what `EC_AV1_I64` names.
1191fn i64_root() -> bool {
1192 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1193 crate::envflags::var("EC_AV1_I64").ok().map(|v| v != "0")
1194 });
1195 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::I64_ROOT))
1196}
1197
1198/// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the
1199/// winner's prediction through one TX_64X64 luma transform and two TX_32X32
1200/// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root
1201/// lane-b64 shipped, so the two can be measured against each other on the
1202/// same build.
1203///
1204/// MEASURED on the native gate (two arms of one build, baseline reproduced to
1205/// the tenth): both film rows improve on both columns -- film A
1206/// +43.0/+15.0 -> +42.9/+14.8, film B +64.7/+34.0 -> +63.3/+31.5 -- and
1207/// SCREEN CAPTURE loses +33.4/-23.8 -> +34.3/-23.4, outside the keep rule's
1208/// +-0.3 screen clause. So the caller gates this off on a screen frame
1209/// (`allow_screen_content_tools`), the same content gate the coding pyramid
1210/// takes: a desktop capture's 64x64 superblocks are flat runs whose skip arm
1211/// already codes them for nothing, and a residual there only spends bits the
1212/// intra/palette tools would have spent better.
1213///
1214/// CENSUS on film B (12 frames, q120, `EC_AV1_BITCENSUS=1` +
1215/// `examples/syntax_census.rs`, both streams read by OUR decoder), off vs on:
1216///
1217/// | | skip-only | + residual |
1218/// |---|---|---|
1219/// | 64x64 share, all frames | 36.4% | 38.3% |
1220/// | 64x64 share, leaf frames | 53.3% | 56.0% |
1221/// | skip area, all frames | 80.4% | 78.8% |
1222/// | skip area, leaf frames | 90.2% | 88.5% |
1223/// | stream bytes | 34,366 | 34,295 |
1224/// | encoder wall | 13.4s | 9.6s |
1225///
1226/// `base_luma_64` enters the leaf frames' top tables at 5.7%, i.e. the
1227/// TX_64X64 coefficients are really being coded. The root wins MORE often
1228/// with a residual to offer (rav1e speed 6's own 64x64 share on this clip is
1229/// 45.2%), which is also why the arm is 28% FASTER despite costing three more
1230/// transforms per superblock: a root that wins is four quadrant searches that
1231/// never run.
1232fn b64_residual() -> bool {
1233 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1234 crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0")
1235 });
1236 ENV.unwrap_or(true) && b64_root()
1237}
1238
1239/// How many 64x64 roots came out cheaper with a residual than skipped, since
1240/// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate
1241/// rather than assuming one (class `gate-blind-to-feature`).
1242static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1243
1244/// The non-skip 64x64-root count since the last call, and zero it.
1245pub fn take_b64_residual_hits() -> usize {
1246 B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1247}
1248
1249/// Whether the 64x64 root also prices COMPOUND candidates (lane-b64b): the
1250/// `LAST` + extra-reference pairs the 32x32 level already offers, at the
1251/// three modes a root can form without a second 64x64 motion search --
1252/// `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` (whose NEW half
1253/// is the vector `search_skip_64`'s own single-reference search already
1254/// found). `NEAREST_NEWMV`/`NEW_NEWMV` need the SECOND reference's own
1255/// `NEWMV` vector, which only a second search per superblock produces -- the
1256/// wall this root exists to save -- so they are not offered here.
1257///
1258/// Off by `EC_AV1_B64COMP=0`, so both arms measure on one build.
1259fn b64_compound() -> bool {
1260 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1261 crate::envflags::var("EC_AV1_B64COMP").ok().map(|v| v != "0")
1262 });
1263 ENV.unwrap_or(true) && b64_root()
1264}
1265
1266/// How many 64x64 roots took a COMPOUND candidate since the last
1267/// [`take_b64_compound_hits`] (class `gate-blind-to-feature`).
1268static B64_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1269
1270/// The compound 64x64-root count since the last call, and zero it.
1271pub fn take_b64_compound_hits() -> usize {
1272 B64_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1273}
1274
1275/// Whether a 64x64 root that codes a residual may SPLIT its luma transform
1276/// (lane-b64b): four TX_32X32 units instead of the one TX_64X64, decided by
1277/// [`commit_inter_luma`] like every other inter block's var-tx, and coded by
1278/// the writer's `Whole64` arm as `txfm_split = 1`. It exists because
1279/// TX_64X64 zeroes everything outside its 32x32 corner, so a root whose
1280/// residual has detail in the other three quadrants cannot code it at all.
1281///
1282/// Off by `EC_AV1_B64VARTX=0`.
1283fn b64_var_tx() -> bool {
1284 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1285 crate::envflags::var("EC_AV1_B64VARTX").ok().map(|v| v != "0")
1286 });
1287 ENV.unwrap_or(true) && b64_root()
1288}
1289
1290/// How many 64x64 roots split their luma transform since the last
1291/// [`take_b64_var_tx_hits`].
1292static B64_VAR_TX_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1293
1294/// The split-luma 64x64-root count since the last call, and zero it.
1295pub fn take_b64_var_tx_hits() -> usize {
1296 B64_VAR_TX_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1297}
1298
1299/// Whether a superblock the true frame edge CUTS THROUGH may be left whole
1300/// (lane-b64b). AV1 asks only that the block's own half is inside
1301/// (`has_cols`/`has_rows`, spec `decode_partition`), and the writer already
1302/// codes that case; what was missing was a trial whose SSE is scored over the
1303/// INSIDE part alone ([`Plane::block_sse`], which clips since lane-sse)
1304/// instead of over the padding the encoder
1305/// invented past the edge. Both gate films are superblock-aligned, so this
1306/// only reaches the user's own arbitrary export sizes.
1307///
1308/// Off by `EC_AV1_B64EDGE=0`.
1309fn b64_edge() -> bool {
1310 edge_root_enabled() && b64_root()
1311}
1312
1313/// What `EC_AV1_B64EDGE` names on its own, without the inter root's own
1314/// preset switch -- the key frame's root ([`I64_ROOT`]) reads the same flag
1315/// but is gated by [`i64_root`].
1316fn edge_root_enabled() -> bool {
1317 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1318 crate::envflags::var("EC_AV1_B64EDGE").ok().map(|v| v != "0")
1319 });
1320 ENV.unwrap_or(true)
1321}
1322
1323/// How many 64x64 roots the frame edge cut through since the last
1324/// [`take_b64_edge_hits`] (class `gate-blind-to-feature`: both gate films are
1325/// superblock-aligned, so nothing but a synthetic size fires this).
1326static B64_EDGE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1327
1328/// The edge 64x64-root count since the last call, and zero it.
1329pub fn take_b64_edge_hits() -> usize {
1330 B64_EDGE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1331}
1332
1333/// Whether the encoder searches loop restoration at all (spec 7.17): one
1334/// Wiener filter per 64x64 luma restoration unit, picked from
1335/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
1336/// test build, like [`lambda_scale`].
1337pub(crate) const RESTORATION: bool = true;
1338
1339/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
1340fn restoration_enabled() -> bool {
1341 match std::env::var("EC_AV1_LR").ok() {
1342 Some(v) if cfg!(test) => v != "0",
1343 _ => crate::speed::at(&crate::speed::RESTORATION),
1344 }
1345}
1346
1347/// libaom's `partition_search_breakout` shape: how many non-zero luma
1348/// coefficients per 256 luma samples a block may code and still be judged
1349/// well enough predicted that the split below it is not worth trying. `0`
1350/// disables the breakout (only the existing all-skip prune applies), which
1351/// is the default until the sweep below justifies otherwise.
1352///
1353/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
1354/// is where this lane's wall would have gone: 1 cuts the three clips'
1355/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
1356/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
1357/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
1358/// encoder's inter quality lives, so `0` ships and the knob stays for a
1359/// future explicit speed preset.
1360pub(crate) const SPLIT_BREAKOUT_COEFFS: usize = 0;
1361
1362/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
1363/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
1364/// out under `threshold * lambda` is not offered the split at all, and a
1365/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
1366/// always, as before this lever.
1367///
1368/// The census is what points here: the split trial runs on nearly every
1369/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
1370/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
1371/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
1372/// points, so the gate has to read the block's own RD cost, not its levels.
1373///
1374/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
1375/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
1376/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
1377/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
1378/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
1379/// the largest threshold whose BD stays inside the +0.3 keep rule on every
1380/// clip.
1381/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on (base
1382/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3): 0.0625 is +16.9/-0.4, +47.0/+19.1,
1383/// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is
1384/// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off
1385/// the screen wall). Neither clears the keep rule; 0.125 stays.
1386pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125;
1387
1388/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
1389fn split_rd_threshold() -> f64 {
1390 static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| {
1391 crate::envflags::var("EC_AV1_SPLIT_RD").ok().and_then(|v| v.parse().ok())
1392 });
1393 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD))
1394}
1395
1396/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
1397/// [`split_rd_threshold`] withholds the split trial.
1398fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
1399 split_rd_breakout_at(split_rd_threshold(), cost, side, lambda)
1400}
1401
1402/// [`split_rd_breakout`] at an explicit threshold -- what the 64x64 root's own
1403/// early-out reads.
1404fn split_rd_breakout_at(t: f64, cost: f64, side: usize, lambda: f64) -> bool {
1405 t > 0.0 && cost < t * lambda * (side * side) as f64
1406}
1407
1408/// The threshold the 64x64 root's early-out uses: [`split_rd_threshold`]
1409/// CLAMPED at the shipped [`SPLIT_RD_THRESHOLD`] (lane-tx64).
1410///
1411/// The 32x32 level is allowed to loosen its breakout with the speed preset
1412/// (`crate::speed::SPLIT_RD` steps to 0.5 at preset 6), but lane-b64 measured
1413/// what that does one size up: at 0.5 a whole superblock is taken at 64x64
1414/// without its four quadrants ever being searched, and film B goes
1415/// +91.5/+53.4 -> +114.6/+71.5. A 64x64 block is four times the area, so the
1416/// same per-pixel threshold withholds four times as much search -- the
1417/// preset's step is priced for the 32 level and does not carry up here.
1418fn b64_breakout_threshold() -> f64 {
1419 split_rd_threshold().min(SPLIT_RD_THRESHOLD)
1420}
1421
1422/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
1423/// build.
1424fn split_breakout_coeffs() -> usize {
1425 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
1426 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
1427 _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT),
1428 }
1429}
1430
1431/// How often each partition decision was taken since the last
1432/// [`take_partition_hits`], so a gate can report how often a new partition
1433/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
1434/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
1435/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
1436static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
1437 std::sync::atomic::AtomicUsize::new(0),
1438 std::sync::atomic::AtomicUsize::new(0),
1439 std::sync::atomic::AtomicUsize::new(0),
1440 std::sync::atomic::AtomicUsize::new(0),
1441];
1442
1443/// Records one such decision.
1444fn partition_hit(which: usize) {
1445 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1446}
1447
1448/// Takes (and clears) the counts.
1449#[cfg(test)]
1450pub(crate) fn take_partition_hits() -> [usize; 4] {
1451 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1452}
1453
1454/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
1455/// rate-distortion trials the block search actually runs, by kind, and where
1456/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
1457/// default, and a measurement build rather than a speed one -- the census
1458/// runs the SAD pre-pass the unpruned search otherwise skips.
1459pub fn census_on() -> bool {
1460 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1461 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
1462}
1463
1464/// What each [`CENSUS`] counter counts.
1465pub const CENSUS_KINDS: [&str; 11] = [
1466 "intra blocks searched (key frame + inter leaves)",
1467 "intra luma mode trials",
1468 "chroma searches",
1469 "chroma mode trials (each = 2 plane trials)",
1470 "tx-depth trials (transform units, depth >= 1)",
1471 "inter 32x32 blocks searched",
1472 "inter block intra-mode trials",
1473 "inter mv candidates (each = 3 mc trials)",
1474 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
1475 " of those, intra won",
1476 " of those, the NEARESTMV trial coded no residual",
1477];
1478
1479/// The census counters themselves, indexed by [`CENSUS_KINDS`].
1480static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
1481 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
1482
1483/// Where the RD winner sat in the SAD ranking, for the luma intra search and
1484/// the chroma mode search -- what says whether a top-N prune would have kept
1485/// the block the search actually chose.
1486static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
1487 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
1488static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
1489 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1490
1491fn census_add(kind: usize, n: usize) {
1492 if census_on() {
1493 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
1494 }
1495}
1496
1497/// Reads (and clears) the census, so a driver can attribute it to its own encode.
1498pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
1499 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
1500 (
1501 std::array::from_fn(|i| take(&CENSUS[i])),
1502 std::array::from_fn(|i| take(&LUMA_RANK[i])),
1503 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
1504 )
1505}
1506
1507/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
1508/// first -- the census's one shared rule, so the luma and chroma histograms
1509/// mean the same thing.
1510fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
1511 scored
1512 .iter()
1513 .filter(|&&(score, mode)| {
1514 mode != winner
1515 && score
1516 < scored
1517 .iter()
1518 .find(|&&(_, m)| m == winner)
1519 .map_or(f64::INFINITY, |&(s, _)| s)
1520 })
1521 .count()
1522}
1523
1524/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
1525/// four cost less. Set from the measurement in the lane report.
1526const SPLIT_BLOCKS: bool = true;
1527
1528/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
1529/// by calling [`encode_key_frame_inner`] both ways.
1530pub(crate) fn split_blocks() -> bool {
1531 SPLIT_BLOCKS
1532}
1533
1534/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
1535/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
1536/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
1537/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
1538/// stream's decode output actually carries 10-bit precision instead of
1539/// silently losing its low 2 bits). The encoder only ever produces values in
1540/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
1541/// decision); `Plane::source` narrows right back to `u8` at its two
1542/// construction sites, a lossless round trip for that range.
1543#[derive(Clone, Debug, PartialEq, Eq)]
1544pub struct Picture {
1545 /// The picture's width in luma samples.
1546 pub width: usize,
1547 /// Its height in luma samples.
1548 pub height: usize,
1549 /// The luma plane, `width * height` samples in raster order.
1550 pub y: Vec<u16>,
1551 /// The U plane, at half the width and half the height.
1552 pub u: Vec<u16>,
1553 /// The V plane, the same shape as U.
1554 pub v: Vec<u16>,
1555}
1556
1557impl Picture {
1558 /// A mid-grey picture of the given size.
1559 #[must_use]
1560 pub fn grey(width: usize, height: usize) -> Self {
1561 Self {
1562 width,
1563 height,
1564 y: vec![128; width * height],
1565 u: vec![128; width * height / 4],
1566 v: vec![128; width * height / 4],
1567 }
1568 }
1569
1570 pub(crate) fn check(&self) -> Result<()> {
1571 if self.width == 0
1572 || !self.width.is_multiple_of(BLOCK)
1573 || !self.height.is_multiple_of(BLOCK)
1574 || !self.height.is_multiple_of(BLOCK)
1575 {
1576 return Err(Error::unsupported(
1577 "AV1 encode",
1578 "the picture must be a whole number of 32x32 blocks in each direction",
1579 ));
1580 }
1581 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1582 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1583 return Err(Error::unsupported(
1584 "AV1 encode",
1585 "each plane must carry one sample per position at 4:2:0",
1586 ));
1587 }
1588 Ok(())
1589 }
1590
1591 /// What the public entry points require of the picture they are handed,
1592 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
1593 /// needs a whole chroma sample per two luma ones) and one sample per
1594 /// position on each plane.
1595 pub(crate) fn check_even(&self) -> Result<()> {
1596 if self.width == 0
1597 || self.height == 0
1598 || !self.width.is_multiple_of(2)
1599 || !self.height.is_multiple_of(2)
1600 {
1601 return Err(Error::unsupported(
1602 "AV1 encode",
1603 "the picture's width and height must each be even and nonzero",
1604 ));
1605 }
1606 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1607 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1608 return Err(Error::unsupported(
1609 "AV1 encode",
1610 "each plane must carry one sample per position at 4:2:0",
1611 ));
1612 }
1613 Ok(())
1614 }
1615
1616 /// This picture, padded by edge replication to the next whole number of
1617 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
1618 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
1619 /// sequence (what the inter tile writer's partition needs on top of
1620 /// that). Identity (a plain clone, not a copy through the replication
1621 /// loop) when the picture is already that size — the multiple-of-32 (or
1622 /// -64) fast path is unchanged.
1623 pub(crate) fn padded_to(&self, align: usize) -> Picture {
1624 let padded_width = self.width.next_multiple_of(align);
1625 let padded_height = self.height.next_multiple_of(align);
1626 if padded_width == self.width && padded_height == self.height {
1627 return self.clone();
1628 }
1629 Picture {
1630 width: padded_width,
1631 height: padded_height,
1632 y: pad_plane(
1633 &self.y,
1634 self.width,
1635 self.height,
1636 padded_width,
1637 padded_height,
1638 ),
1639 u: pad_plane(
1640 &self.u,
1641 self.width / 2,
1642 self.height / 2,
1643 padded_width / 2,
1644 padded_height / 2,
1645 ),
1646 v: pad_plane(
1647 &self.v,
1648 self.width / 2,
1649 self.height / 2,
1650 padded_width / 2,
1651 padded_height / 2,
1652 ),
1653 }
1654 }
1655}
1656
1657/// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8`
1658/// (8-bit only, unchanged this round -- widening the encoder is out of this
1659/// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that
1660/// lets it keep calling [`crate::intra::predict`] now that shape is `u16`
1661/// in and out. A block-sized round-trip through `u16` is exact for 8-bit
1662/// content (every value fits both ways), so this changes no encoder output.
1663#[allow(clippy::too_many_arguments)]
1664fn intra_predict_u8(
1665 mode: u8,
1666 angle_delta: i32,
1667 above: Option<&[u8]>,
1668 left: Option<&[u8]>,
1669 corner: Option<u8>,
1670 bw: usize,
1671 bh: usize,
1672 enable_edge_filter: bool,
1673 smooth_neighbor: bool,
1674 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
1675) {
1676 // Three heap allocations per call became three stack buffers: this runs
1677 // once per mode per trial, and an edge is at most `bw + bh` samples while
1678 // a block is at most `SUPERBLOCK * SUPERBLOCK` (lane-i64: the key frame's
1679 // 64x64 intra root predicts through here too, and reads up to `2 * bw`
1680 // samples above).
1681 let mut above_buf = [0u16; 2 * SUPERBLOCK];
1682 let mut left_buf = [0u16; 2 * SUPERBLOCK];
1683 // lane-av1speed2: a `BLOCK * BLOCK` scratch is 2 KB zeroed on every mode
1684 // trial of every block, and a 4x4 block writes 32 bytes of it. The
1685 // predictor fills every sample it is handed, so the zeros are dead
1686 // either way -- size the scratch to the block instead of to the largest
1687 // block there is.
1688
1689 let widen = |src: &[u8], buf: &mut [u16; 2 * SUPERBLOCK]| {
1690 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1691 *d = u16::from(v);
1692 }
1693 };
1694 if let Some(s) = above {
1695 widen(s, &mut above_buf);
1696 }
1697 if let Some(s) = left {
1698 widen(s, &mut left_buf);
1699 }
1700 let above16 = above.map(|s| &above_buf[..s.len()]);
1701 let left16 = left.map(|s| &left_buf[..s.len()]);
1702 let mut run = |dst16: &mut [u16]| {
1703 crate::intra::predict(
1704 mode,
1705 angle_delta,
1706 above16,
1707 left16,
1708 corner.map(u16::from),
1709 bw,
1710 bh,
1711 enable_edge_filter,
1712 smooth_neighbor,
1713 dst16, fctx,
1714 );
1715 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
1716 *d = s as u8;
1717 }
1718 };
1719 let n = bw * bh;
1720 if n <= 64 {
1721 run(&mut [0u16; 64][..n]);
1722 } else if n <= 256 {
1723 run(&mut [0u16; 256][..n]);
1724 } else if n <= BLOCK * BLOCK {
1725 run(&mut [0u16; BLOCK * BLOCK][..n]);
1726 } else {
1727 run(&mut [0u16; SUPERBLOCK * SUPERBLOCK][..n]);
1728 }
1729}
1730
1731/// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same
1732/// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one
1733/// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode.
1734fn filter_intra_predict_u8(
1735 mode: usize,
1736 above: Option<&[u8]>,
1737 left: Option<&[u8]>,
1738 corner: Option<u8>,
1739 side: usize,
1740 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
1741) {
1742 let mut above_buf = [0u16; 2 * BLOCK];
1743 let mut left_buf = [0u16; 2 * BLOCK];
1744 let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
1745 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1746 *d = u16::from(v);
1747 }
1748 };
1749 if let Some(a) = above {
1750 widen(a, &mut above_buf);
1751 }
1752 if let Some(l) = left {
1753 widen(l, &mut left_buf);
1754 }
1755 let mut dst16 = [0u16; BLOCK * BLOCK];
1756 let n = side * side;
1757 crate::intra::predict_filter_intra(
1758 mode,
1759 above.map(|a| &above_buf[..a.len()]),
1760 left.map(|l| &left_buf[..l.len()]),
1761 corner.map(u16::from),
1762 side,
1763 side,
1764 &mut dst16[..n], fctx,
1765 );
1766 for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) {
1767 *d = v as u8;
1768 }
1769}
1770
1771/// Pads one plane to `(padded_width, padded_height)` by repeating its last
1772/// row and column, so the block coder always sees a whole number of blocks.
1773/// [`crop_plane`] undoes this on the way back out.
1774fn pad_plane<T: Copy + Default>(
1775 source: &[T],
1776 width: usize,
1777 height: usize,
1778 padded_width: usize,
1779 padded_height: usize,
1780) -> Vec<T> {
1781 let mut out = vec![T::default(); padded_width * padded_height];
1782 for row in 0..padded_height {
1783 let src = source[row.min(height - 1) * width..][..width].as_ref();
1784 let dst = &mut out[row * padded_width..][..padded_width];
1785 dst[..width].copy_from_slice(src);
1786 dst[width..].fill(src[width - 1]);
1787 }
1788 out
1789}
1790
1791/// The top-left `width` x `height` region of a plane that is `padded_width`
1792/// wide, which is the render-size crop [`Picture::padded`]'s replication
1793/// exists to let a decoder undo.
1794fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
1795 let mut out = Vec::with_capacity(width * height);
1796 for row in 0..height {
1797 out.extend_from_slice(&source[row * padded_width..][..width]);
1798 }
1799 out
1800}
1801
1802/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
1803/// region a decoder produces, which is the public contract for what a caller
1804/// sees back — the padded planes the encoder coded against never leave this
1805/// module. Identity when the reconstruction is already that size.
1806pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
1807 let reconstruction = &encoded.reconstruction;
1808 let cropped = if reconstruction.width == width && reconstruction.height == height {
1809 reconstruction.clone()
1810 } else {
1811 Picture {
1812 width,
1813 height,
1814 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
1815 u: crop_plane(
1816 &reconstruction.u,
1817 reconstruction.width / 2,
1818 width / 2,
1819 height / 2,
1820 ),
1821 v: crop_plane(
1822 &reconstruction.v,
1823 reconstruction.width / 2,
1824 width / 2,
1825 height / 2,
1826 ),
1827 }
1828 };
1829 Encoded {
1830 stream: encoded.stream.clone(),
1831 modes: encoded.modes.clone(),
1832 inter_block_share: encoded.inter_block_share,
1833 reconstruction: cropped,
1834 tile: encoded.tile.clone(),
1835 mi_cols: encoded.mi_cols,
1836 mi_rows: encoded.mi_rows,
1837 base_q_idx: encoded.base_q_idx,
1838 tx_select: encoded.tx_select,
1839 switchable_motion_mode: encoded.switchable_motion_mode,
1840 screen: encoded.screen,
1841 reduced_tx_set: encoded.reduced_tx_set,
1842 start_cdfs: encoded.start_cdfs.clone(),
1843 next_cdfs: encoded.next_cdfs.clone(),
1844 loop_filter: encoded.loop_filter,
1845 loop_restoration: encoded.loop_restoration,
1846 allow_intrabc: encoded.allow_intrabc,
1847 delta: encoded.delta.clone(),
1848 cdef: encoded.cdef,
1849 }
1850}
1851
1852/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
1853/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
1854#[derive(Clone)]
1855pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
1856
1857impl std::fmt::Debug for CdfSnapshot {
1858 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1859 f.write_str("CdfSnapshot")
1860 }
1861}
1862
1863/// What one call to [`encode_key_frame`] produced.
1864#[derive(Clone, Debug)]
1865pub struct Encoded {
1866 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
1867 /// OBU carrying one tile.
1868 pub stream: Vec<u8>,
1869 /// What a decoder will produce from `stream` — the encoder's own
1870 /// reconstruction, which its prediction was built on.
1871 pub reconstruction: Picture,
1872 /// The luma intra mode each block was coded under, in the order the blocks
1873 /// are coded — raster order among the quadrants of each superblock, and
1874 /// among the four 16x16 blocks of a quadrant that was split.
1875 pub modes: Vec<u8>,
1876 /// The fraction of this frame's 32x32 blocks that were coded inter (any
1877 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
1878 /// for a key frame, which has no such choice — so a caller can tell a
1879 /// frame with no motion worth coding from one that never got the chance.
1880 pub inter_block_share: f64,
1881 /// The tile payload alone, undecorated by any OBU framing, and the frame
1882 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
1883 /// `crate::decode`'s tests are the only reader; a real decoder gets these
1884 /// off the wire by parsing `stream`'s OBUs instead.
1885 pub(crate) tile: Vec<u8>,
1886 pub(crate) mi_cols: u32,
1887 pub(crate) mi_rows: u32,
1888 pub(crate) base_q_idx: u8,
1889 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
1890 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
1891 /// and reading it off `stream`'s header is what `decode_stream` does. A
1892 /// test that decodes `tile` directly must pass this one along, or it reads
1893 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
1894 /// block.
1895 pub(crate) tx_select: bool,
1896 /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the
1897 /// bit that makes every eligible single-reference inter block carry a
1898 /// `motion_mode` symbol. Same contract as `tx_select` above: a test
1899 /// decoding `tile` directly must pass it along or it desyncs at the
1900 /// first eligible block.
1901 pub(crate) switchable_motion_mode: bool,
1902 /// The CDF state this frame's tile writer started from -- the defaults
1903 /// for a key frame and for the first inter frame, and the previous
1904 /// frame's stored tables after that. A test that decodes `tile` directly
1905 /// must feed the decoder this, exactly as `decode_stream` feeds it what
1906 /// the frame's `primary_ref_frame` slot holds (same class as
1907 /// `tx_select`: a header bit a raw tile decode cannot guess).
1908 pub(crate) start_cdfs: CdfSnapshot,
1909 /// What this frame stores into the slots it refreshes (spec 7.20,
1910 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
1911 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
1912 /// started from when it is on.
1913 pub(crate) next_cdfs: CdfSnapshot,
1914 /// This frame header's chosen deblocking parameters
1915 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
1916 /// picture the decoder produces UNDER them, so a test that decodes
1917 /// `tile` directly must pass these along, exactly as it must `tx_select`
1918 /// (class: test asserts against a stale header).
1919 pub(crate) loop_filter: LoopFilterParams,
1920 /// This frame header's chosen CDEF parameters, threaded for the same
1921 /// reason as `loop_filter`.
1922 pub(crate) cdef: CdefParams,
1923 /// This frame header's `allow_screen_content_tools`
1924 /// ([`screen_content`]) -- every intra block of the tile carries the two
1925 /// palette-mode symbols under it, so a raw tile decode that guessed
1926 /// `false` would desync at the first block (same class as `tx_select`).
1927 pub(crate) screen: bool,
1928 /// This frame header's own `reduced_tx_set` (spec 5.9.2) -- the bit that
1929 /// picks the inter `tx_type` alphabets AND, on an inter block, the
1930 /// allowance the chroma transform's inherited type reduces against
1931 /// ([`crate::decode::reduce_inherited_chroma_tx_type`]). A raw tile
1932 /// decode that guesses `true` here mis-derives every inherited chroma
1933 /// type on a `reduced_tx_set = 0` frame (lane-intertx; same class as
1934 /// `tx_select`/`screen` above).
1935 pub(crate) reduced_tx_set: bool,
1936 /// This frame header's chosen loop restoration parameters, threaded for
1937 /// the same reason as `loop_filter` -- and doubly so: the per-unit
1938 /// filters themselves are coded in `tile`, so a decode of it under a
1939 /// stale `RESTORE_NONE` header desyncs at the first superblock.
1940 pub(crate) loop_restoration: LoopRestorationParams,
1941 /// This frame header's `allow_intrabc` -- every intra block of the tile
1942 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
1943 /// guessed `false` would desync at the first block (same class as
1944 /// `screen`/`tx_select`).
1945 pub(crate) allow_intrabc: bool,
1946 /// This frame header's `delta_q_params`/`delta_lf_params` (spec
1947 /// 5.9.17/5.9.18) -- with `delta_q_present` every superblock's first
1948 /// coded block carries a `delta_qindex` symbol group, so a raw tile
1949 /// decode that guessed the defaults desyncs at the first superblock
1950 /// (same class as `screen`/`tx_select`).
1951 pub(crate) delta: ec_av1_syntax::DeltaParams,
1952}
1953
1954thread_local! {
1955 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
1956 /// for on the last key frame encoded on this thread -- read by the gates,
1957 /// which print it beside the block counts (class `gate-blind-to-feature`).
1958 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
1959}
1960
1961/// [`IBC_SHARE`] for the last key frame encoded on this thread.
1962#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
1963pub(crate) fn intrabc_source_share() -> f64 {
1964 IBC_SHARE.with(std::cell::Cell::get)
1965}
1966
1967thread_local! {
1968 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
1969 /// header offers the per-frame `allow_screen_content_tools` bit at all.
1970 /// Armed once by the key frame ([`encode_key_frame_inner`], from
1971 /// [`screen_content`]) and read by every header builder after it, so that
1972 /// the inter frames of a screen sequence lay their headers out the same
1973 /// way the sequence header the key frame wrote says they do -- a per-call
1974 /// parameter would have to thread through `inter_frame_headers`' four
1975 /// public entry points and every hand-built-stream test that calls them.
1976 /// A sequence with no screen content leaves this false and writes exactly
1977 /// the bits it wrote before this lane.
1978 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1979}
1980
1981thread_local! {
1982 /// Overrides [`screen_content`] for the calling thread, which is what the
1983 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
1984 /// codes every block losslessly, so both arms of a mode ablation reach
1985 /// infinite PSNR and the ablation measures nothing at all (the
1986 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
1987 /// variable cannot do this -- the tests run in one process, in parallel.
1988 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
1989}
1990
1991thread_local! {
1992 /// What the last [`encode_sequence_with_ctx`] call on this thread coded
1993 /// under, AFTER the content gate: the pyramid, or `None` for a stream
1994 /// that stayed flat. Read by the BD gates, which print the requested and
1995 /// the effective pyramid side by side -- a screen clip requests one and
1996 /// codes flat, and that difference is the gate (class
1997 /// `gate-blind-to-feature`).
1998 static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> =
1999 const { std::cell::Cell::new(None) };
2000}
2001
2002/// The pyramid the last sequence coded on this thread was EFFECTIVELY under.
2003#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2004pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> {
2005 LAST_SEQ_PYRAMID.with(std::cell::Cell::get)
2006}
2007
2008#[cfg(test)]
2009pub(crate) fn force_screen(value: Option<bool>) {
2010 SCREEN_FORCE.with(|c| c.set(value));
2011}
2012
2013// lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE
2014// ablation can measure the mode search alone. Setting it also clears the
2015// sequence header's own `enable_filter_intra` bit, so the stream the arm
2016// writes is exactly the one this encoder wrote before the lane.
2017#[cfg(test)]
2018thread_local! {
2019 static FILTER_INTRA_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
2020}
2021
2022#[cfg(test)]
2023pub(crate) fn force_filter_intra(value: Option<bool>) {
2024 FILTER_INTRA_FORCE.with(|c| c.set(value));
2025}
2026
2027pub(crate) fn arm_seq_screen(on: bool) {
2028 SEQ_SCREEN.with(|c| c.set(on));
2029}
2030
2031fn seq_screen() -> bool {
2032 SEQ_SCREEN.with(std::cell::Cell::get)
2033}
2034
2035/// How many distinct colours a 16x16 luma block may hold and still count as
2036/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
2037/// `av1_set_screen_content_options` bound is 4, which separates nothing on
2038/// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against
2039/// the variance floor below on the five gate clips at BOTH the native crop
2040/// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of
2041/// the frame is the widest-margin split of those ten rows -- every
2042/// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5
2043/// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6%
2044/// native and 17.9% scaled.
2045fn screen_colors() -> usize {
2046 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2047 *N.get_or_init(|| {
2048 std::env::var("EC_AV1_SCREEN_COLORS")
2049 .ok()
2050 .and_then(|v| v.parse().ok())
2051 .unwrap_or(16)
2052 })
2053}
2054
2055/// The reciprocal of the frame area those blocks must cover, in tenths --
2056/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth;
2057/// 8 (an eighth) is the midpoint of the two populations
2058/// `probe_screen_detect` measures at the colour bound and variance floor
2059/// around it. `EC_AV1_SCREEN_PCT`.
2060fn screen_pct() -> usize {
2061 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2062 *N.get_or_init(|| {
2063 std::env::var("EC_AV1_SCREEN_PCT")
2064 .ok()
2065 .and_then(|v| v.parse().ok())
2066 .unwrap_or(10)
2067 })
2068}
2069
2070/// The per-pixel variance a few-colour block must clear before it counts as
2071/// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its
2072/// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it
2073/// a smooth dark film frame is all few-colour blocks and reads as a desktop
2074/// capture -- which is exactly what this detector did until 2026-09-07, when
2075/// it called BOTH real films screen content on 48/48 frames, priced every
2076/// coefficient against the default CDFs and ran the palette search over
2077/// film. `probe_screen_detect`: at 16 colours the floor takes both films
2078/// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to
2079/// 23.6%.
2080fn screen_var() -> u64 {
2081 static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
2082 *N.get_or_init(|| {
2083 std::env::var("EC_AV1_SCREEN_VAR")
2084 .ok()
2085 .and_then(|v| v.parse().ok())
2086 .unwrap_or(16)
2087 })
2088}
2089
2090/// How many frames [`screen_content`] said yes/no to, so a gate can print
2091/// whether the detector fired at all (class `gate-blind-to-feature`).
2092pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
2093 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
2094
2095/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
2096/// the distinct colours of every 16x16 block and turn the screen-content
2097/// tools on when the blocks holding between 2 and [`screen_colors`] of them
2098/// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the
2099/// frame. `width` is the plane's
2100/// stride, `true_*` the frame's real (decodable) extent.
2101fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
2102 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
2103 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2104 return forced;
2105 }
2106 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
2107 let on = v != "0";
2108 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2109 return on;
2110 }
2111 let (blk, limit, floor) = (16usize, screen_colors(), screen_var());
2112 let mut counted = 0usize;
2113 for by in (0..true_height).step_by(blk) {
2114 for bx in (0..true_width).step_by(blk) {
2115 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
2116 let mut seen = [false; 256];
2117 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
2118 for row in 0..h {
2119 for col in 0..w {
2120 let v = y[(by + row) * width + bx + col];
2121 sum += u64::from(v);
2122 sq += u64::from(v) * u64::from(v);
2123 if !seen[usize::from(v)] {
2124 seen[usize::from(v)] = true;
2125 colors += 1;
2126 }
2127 }
2128 }
2129 // Per-pixel variance over the block's real (edge-clipped) extent.
2130 let n = (h * w) as u64;
2131 let var = (sq - sum * sum / n) / n;
2132 if colors > 1 && colors <= limit && var > floor {
2133 counted += 1;
2134 }
2135 }
2136 }
2137 let on = counted * blk * blk * screen_pct() > true_width * true_height;
2138 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2139 on
2140}
2141
2142/// Whether this SOURCE picture reads as screen content, for a caller that has
2143/// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`]
2144/// gates its coding pyramid on this (a desktop capture keeps the flat
2145/// one-in-one-out structure the BD gate measured it on, camera material takes
2146/// the mini-GOP). The key frame runs the same detector again when it builds
2147/// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to
2148/// count, so this probe undoes its own tick and leaves the gate prints
2149/// reading one detection per coded frame.
2150pub(crate) fn picture_is_screen(picture: &Picture) -> bool {
2151 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
2152 let on = screen_content(&y, picture.width, picture.width, picture.height);
2153 SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2154 on
2155}
2156
2157/// The sequence and frame headers a picture of this size is coded under: one
2158/// tile, one transform size per block, no in-loop filter parameters yet
2159/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
2160/// CDEF strengths in once the tile is coded), no CDF adaptation
2161/// and no tool the tile writer does not code.
2162///
2163/// # Errors
2164/// Returns an error when the picture is larger than the 16-bit frame size the
2165/// sequence header carries.
2166pub fn key_frame_headers(
2167 width: usize,
2168 height: usize,
2169 base_q_idx: u8,
2170) -> Result<(SequenceHeader, FrameHeader)> {
2171 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
2172}
2173
2174/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
2175/// studio (limited) range: what this crate's sequence header carried before
2176/// [`crate::encoder`]'s facade could configure it, and what
2177/// [`key_frame_headers`] still asks for.
2178fn unspecified_color_config() -> ColorConfig {
2179 ColorConfig {
2180 bit_depth: 8,
2181 mono_chrome: false,
2182 num_planes: 3,
2183 color_primaries: 2,
2184 transfer_characteristics: 2,
2185 matrix_coefficients: 2,
2186 color_range: false,
2187 subsampling_x: 1,
2188 subsampling_y: 1,
2189 chroma_sample_position: ChromaSamplePosition::Unknown,
2190 separate_uv_delta_q: false,
2191 }
2192}
2193
2194/// [`key_frame_headers`] with the sequence header's colour config named
2195/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
2196/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
2197/// which is all a player picks a colour transform from and which
2198/// [`crate::encoder::Colour`] is the facade's own name for.
2199///
2200/// # Errors
2201/// The same as [`key_frame_headers`].
2202pub(crate) fn key_frame_headers_colour(
2203 width: usize,
2204 height: usize,
2205 base_q_idx: u8,
2206 color_config: ColorConfig,
2207) -> Result<(SequenceHeader, FrameHeader)> {
2208 let bits = |n: usize| -> Result<u32> {
2209 let n = u32::try_from(n).map_err(|_| too_large())?;
2210 if n == 0 || n > 1 << 16 {
2211 return Err(too_large());
2212 }
2213 Ok((32 - (n - 1).leading_zeros()).max(1))
2214 };
2215 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
2216 let (w, h) = (width as u32, height as u32);
2217 let seq = SequenceHeader {
2218 seq_profile: 0,
2219 operating_points: vec![OperatingPoint {
2220 seq_level_idx: 8,
2221 ..OperatingPoint::default()
2222 }],
2223 frame_width_bits,
2224 frame_height_bits,
2225 max_frame_width: w,
2226 max_frame_height: h,
2227 use_128x128_superblock: sb128_on(),
2228 // lane-fintra: the encoder's intra search offers the five recursive
2229 // filter-intra modes on eligible blocks, so the sequence bit is set
2230 // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both
2231 // off and restores the streams this encoder wrote before the lane).
2232 enable_filter_intra: filter_intra_on(),
2233 enable_intra_edge_filter: false,
2234 enable_order_hint: true,
2235 order_hint_bits: 7,
2236 enable_superres: false,
2237 // spec 5.9.19: with the sequence bit set every frame header carries
2238 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
2239 // pair for the whole frame, chosen by `crate::filter_search` -- so no
2240 // `cdef_idx` literal is coded in the tile and a frame that wants no
2241 // CDEF simply carries zero strengths.
2242 enable_cdef: true,
2243 enable_restoration: true,
2244 // SELECT (2) when this sequence's key frame detected screen content
2245 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
2246 // is then coded in every frame header, and only the frames that want
2247 // the palette syntax set it. 0 -- the forced-off form, no bit at all
2248 // -- otherwise, which is what every non-screen stream this encoder
2249 // writes still carries.
2250 seq_force_screen_content_tools: if seq_screen() {
2251 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
2252 } else {
2253 0
2254 },
2255 seq_force_integer_mv: 0,
2256 color_config,
2257 still_picture: false,
2258 reduced_still_picture_header: false,
2259 timing_info: None,
2260 decoder_model_info: None,
2261 initial_display_delay_present_flag: false,
2262 operating_point: 0,
2263 operating_point_idc: 0,
2264 frame_id_numbers_present_flag: false,
2265 delta_frame_id_length: 0,
2266 additional_frame_id_length: 0,
2267 enable_interintra_compound: false,
2268 enable_masked_compound: false,
2269 // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
2270 // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
2271 // header is byte-identical to the streams before this lane.
2272 enable_warped_motion: warp_on(),
2273 enable_dual_filter: false,
2274 enable_jnt_comp: false,
2275 enable_ref_frame_mvs: false,
2276 film_grain_params_present: false,
2277 };
2278 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
2279 // own (true, unpadded) width and height, not from any block-grid
2280 // alignment — a decoder derives these straight from `frame_width`/
2281 // `frame_height` below, so this must match it exactly.
2282 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
2283 let header = FrameHeader {
2284 frame_type: FrameType::Key,
2285 frame_is_intra: true,
2286 show_frame: true,
2287 error_resilient_mode: true,
2288 // The tile writer keeps the same CDF state the decoder does and
2289 // updates it in the same order, so the frame lets the decoder adapt.
2290 disable_cdf_update: false,
2291 // Nothing reads the state this frame leaves behind: a key frame always
2292 // starts from the defaults, and this encoder emits one frame.
2293 disable_frame_end_update_cdf: true,
2294 force_integer_mv: true,
2295 refresh_frame_flags: 0xFF,
2296 primary_ref_frame: PRIMARY_REF_NONE,
2297 frame_width: w,
2298 frame_height: h,
2299 upscaled_width: w,
2300 render_width: w,
2301 render_height: h,
2302 mi_cols,
2303 mi_rows,
2304 tile_info: TileInfo {
2305 uniform_spacing: true,
2306 cols: 1,
2307 rows: 1,
2308 mi_col_starts: vec![0, mi_cols],
2309 mi_row_starts: vec![0, mi_rows],
2310 tile_size_bytes: 1,
2311 ..TileInfo::default()
2312 },
2313 quantization: QuantizationParams {
2314 base_q_idx,
2315 ..QuantizationParams::default()
2316 },
2317 tx_mode: TxMode::Largest,
2318 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
2319 // intra transform below 32x32, not only 16x16 -- the set this crate
2320 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
2321 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
2322 // so a decoder honouring the header picks the same CDF the writer
2323 // used only if this is set here too, not only on the inter variant
2324 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
2325 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
2326 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
2327 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
2328 // the arithmetic coder's `rng` register from the very first 8x8-leaf
2329 // luma transform onward with no symbol value ever differing.
2330 reduced_tx_set: true,
2331 ..FrameHeader::default()
2332 };
2333 Ok((seq, header))
2334}
2335
2336/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
2337/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
2338/// 1 still holds the key frame however long the GOP runs.
2339pub const GOLDEN_SLOT: u8 = 1;
2340
2341/// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every inter
2342/// frame this encoder writes carries. `EC_AV1_INTERP=smooth|sharp` codes the
2343/// EIGHTTAP_SMOOTH / EIGHTTAP_SHARP kernel instead of the default REGULAR --
2344/// one filter for the whole frame, which is what libaom does on this content
2345/// too (`lanes/obmc3.report.md` read `switchable_interp 0/0` out of its own
2346/// stream, so a per-BLOCK filter search has no bits to win). The kernel
2347/// reaches the search, the trials and the recon through
2348/// `FrameCtx::interp_filter`, so the stream a decoder reads and the
2349/// prediction the search priced are the same one.
2350/// A PROCESS-GLOBAL [`frame_interp_filter`] override that wins over the
2351/// environment (`u8::MAX` = unset), the shape [`set_inter_tx_search`] has:
2352/// the witness that has to see a non-REGULAR kernel coded and decoded turns
2353/// it on through this while holding [`crate::speed::knob_write`].
2354static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 =
2355 std::sync::atomic::AtomicU8::new(u8::MAX);
2356
2357/// Sets [`INTERP_OVERRIDE`]; `None` clears it.
2358#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
2359pub(crate) fn set_frame_interp(filter: Option<ec_av1_syntax::InterpolationFilter>) {
2360 INTERP_OVERRIDE.store(
2361 filter.map_or(u8::MAX, |f| f as u8),
2362 std::sync::atomic::Ordering::Relaxed,
2363 );
2364}
2365
2366fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter {
2367 use ec_av1_syntax::InterpolationFilter as F;
2368 match INTERP_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
2369 0 => return F::Eighttap,
2370 1 => return F::EighttapSmooth,
2371 2 => return F::EighttapSharp,
2372 _ => {}
2373 }
2374 static ENV: std::sync::LazyLock<Option<F>> = std::sync::LazyLock::new(|| {
2375 crate::envflags::var("EC_AV1_INTERP").ok().map(|v| match v.as_str() {
2376 "smooth" => F::EighttapSmooth,
2377 "sharp" => F::EighttapSharp,
2378 _ => F::Eighttap,
2379 })
2380 });
2381 ENV.unwrap_or(F::Eighttap)
2382}
2383
2384/// The frame header for a shown inter frame that predicts from the single
2385/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
2386/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
2387/// reused verbatim: an inter frame never changes the sequence.
2388///
2389/// # Errors
2390/// Returns an error under the same conditions as [`key_frame_headers`].
2391pub fn inter_frame_headers(
2392 width: usize,
2393 height: usize,
2394 base_q_idx: u8,
2395 order_hint: u32,
2396 last_slot: u8,
2397) -> Result<(SequenceHeader, FrameHeader)> {
2398 inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
2399}
2400
2401/// [`inter_frame_headers`] with the three slots named apart: the one read as
2402/// `LAST_FRAME`, the one this frame refreshes, and the one read as
2403/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
2404/// so that the frame two back is still intact in the slot this one is about
2405/// to overwrite -- read before write, spec 7.20's decode order.
2406///
2407/// # Errors
2408/// As [`inter_frame_headers`].
2409pub fn inter_frame_headers_slots(
2410 width: usize,
2411 height: usize,
2412 base_q_idx: u8,
2413 order_hint: u32,
2414 last_slot: u8,
2415 self_slot: u8,
2416 altref_slot: u8,
2417) -> Result<(SequenceHeader, FrameHeader)> {
2418 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
2419 let header = FrameHeader {
2420 frame_type: FrameType::Inter,
2421 frame_is_intra: false,
2422 show_frame: true,
2423 error_resilient_mode: false,
2424 disable_cdf_update: false,
2425 // The tile writer hands its end-of-tile tables to the next frame
2426 // (`encode_sequence_with_ctx`), so the frame stores them the way the
2427 // decoder will load them (spec 7.20).
2428 disable_frame_end_update_cdf: false,
2429 force_integer_mv: false,
2430 order_hint,
2431 primary_ref_frame: 0,
2432 refresh_frame_flags: 1 << self_slot,
2433 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
2434 // names the slot this frame both predicts from and refreshes;
2435 // GOLDEN names slot 1, which the key frame wrote when it refreshed
2436 // all eight and which no inter frame ever overwrites, so it holds
2437 // the key frame's own picture for the whole GOP.
2438 ref_frame_idx: {
2439 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
2440 idx[3] = GOLDEN_SLOT;
2441 idx[6] = altref_slot;
2442 idx
2443 },
2444 // lane-hpmv: libaom's own rule (`av1_pick_and_set_high_precision_mv`:
2445 // `use_hp = qindex < HIGH_PRECISION_MV_QTHRESH`), with this crate's
2446 // threshold in [`HP_MV_QTHRESH`]. `force_integer_mv` is false in
2447 // every frame this constructor builds, so no further guard is needed.
2448 allow_high_precision_mv: high_precision_mv_at(base_q_idx),
2449 // A FIXED frame-level filter, so no block codes an `interp_filter`
2450 // symbol. lane-obmc3 instrumented whether that costs anything: a
2451 // libaom `cpu-used 6` crf 41 stream of the long-GOP film B window
2452 // (45941 B, the same point `lanes/libcen.report.md` matched) read
2453 // back through `EC_AV1_BITCENSUS=1 syntax_census` codes
2454 // `switchable_interp 0/0` in EVERY frame -- libaom picks a fixed
2455 // frame filter here too, so there are ZERO per-block filter bits at
2456 // stake on this content and the per-block switchable search was not
2457 // built (the charter's premise that libaom codes switchable interp
2458 // per block on film B is refuted by its own stream).
2459 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
2460 // lane-av1obmc: with this bit set every single-reference inter block
2461 // libaom's `motion_mode_allowed` accepts carries a `motion_mode`
2462 // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion`
2463 // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied
2464 // to the OBMC knob rather than always on: with every block choosing
2465 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
2466 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
2467 // and stays byte-identical to the streams before this lane.
2468 // lane-av1obmc2: the warp knob joins that disjunction, and turns on
2469 // `allow_warped_motion` besides -- which is what makes an eligible
2470 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
2471 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
2472 is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC")
2473 || warp_on(),
2474 allow_warped_motion: warp_on(),
2475 use_ref_frame_mvs: false,
2476 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
2477 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
2478 // set this crate carries a table for at 16x16 (see
2479 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
2480 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
2481 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
2482 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
2483 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
2484 // path) -- with this flag set, `get_tx_set`'s intra branch returns
2485 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
2486 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
2487 reduced_tx_set: true,
2488 ..key
2489 };
2490 Ok((seq, header))
2491}
2492
2493fn too_large() -> Error {
2494 Error::unsupported(
2495 "AV1 encode",
2496 "the picture is larger than a frame size can carry",
2497 )
2498}
2499
2500/// One plane of the picture being coded, and the reconstruction being built
2501/// beside it.
2502/// What one committed 4x4 cell left behind for the coefficient contexts of
2503/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
2504/// is the same state decode.rs records.
2505#[derive(Clone, Copy, Default, PartialEq, Eq)]
2506struct CoefCtx {
2507 /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
2508 level: u8,
2509 /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
2510 /// the DC itself was zero (tile.rs `dc_vote`).
2511 dc: i8,
2512}
2513
2514/// One plane's coefficient contexts, committed in CODING ORDER: the search
2515/// prices partition TREES, so the neighbour state a candidate reads has to be
2516/// whatever the blocks coded before it left -- the parent's committed
2517/// neighbours for a tree's first child, the just-committed sibling for the
2518/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
2519/// writer's two running bands is what makes that fall out: a trial commits
2520/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
2521/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
2522/// to its left is exactly what the tile writer's `Neighbours` bands will hold
2523/// when it gets there.
2524///
2525/// Before this map the pricer took both contexts as zero, which is exact for
2526/// a luma transform covering its whole block and the largest remaining row of
2527/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
2528#[derive(Default)]
2529struct CoefCtxMap {
2530 cells: Vec<CoefCtx>,
2531 stride: usize,
2532 /// Whether the transforms being priced right now are SMALLER than the
2533 /// block they sit in -- a `TxMode::Select` depth split
2534 /// ([`Plane::code_tx_depth`]) or an inter var-tx split
2535 /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
2536 /// trial cannot tell, and it is what decides whether luma reads context 0
2537 /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
2538 tu_split: bool,
2539}
2540
2541/// Whether [`Plane::block_sse`] scores a block the true frame edge cuts
2542/// through over its INSIDE part alone. On; `EC_AV1_EDGESSE=0` restores the
2543/// padding-inclusive score the search used before lane-sse, which is how the
2544/// before/after arms of the straddling gate rows are read off ONE binary.
2545fn edge_sse() -> bool {
2546 static ENV: std::sync::LazyLock<Option<bool>> =
2547 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGESSE").ok().map(|v| v != "0"));
2548 ENV.unwrap_or(true)
2549}
2550
2551/// Whether [`Plane::block_sse`] counts the blocks the true frame edge cuts
2552/// through and the share of their raw squared error that sat in the padding
2553/// (`EC_AV1_EDGE_CENSUS=1`). Off by default: only edge blocks would pay for
2554/// it, but the numbers are an instrument, not a decision (class
2555/// `gate-blind-to-feature` -- both gate films are superblock-aligned, so
2556/// without this census no gate row can say the clip fires at all).
2557fn edge_census() -> bool {
2558 static ENV: std::sync::LazyLock<bool> =
2559 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_EDGE_CENSUS").ok().as_deref() == Some("1"));
2560 *ENV
2561}
2562
2563/// Per block side (indexed by `side.trailing_zeros()`, so 2 is 4x4 and 7 is
2564/// 128x128): how many scores clipped, the inside squared error they kept and
2565/// the padding squared error they dropped.
2566static EDGE_SCORES: [[std::sync::atomic::AtomicU64; 3]; 8] =
2567 [const { [const { std::sync::atomic::AtomicU64::new(0) }; 3] }; 8];
2568
2569/// One clipped score, for [`take_edge_census`].
2570fn record_edge_score(side: usize, inside: u64, padding: u64) {
2571 let row = &EDGE_SCORES[(side.trailing_zeros() as usize).min(7)];
2572 row[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2573 row[1].fetch_add(inside, std::sync::atomic::Ordering::Relaxed);
2574 row[2].fetch_add(padding, std::sync::atomic::Ordering::Relaxed);
2575}
2576
2577/// The straddling-block census since the last call, and zero it: one
2578/// `(side, scores, inside_sse, padding_sse)` row per block size that fired.
2579#[must_use]
2580pub fn take_edge_census() -> Vec<(usize, u64, u64, u64)> {
2581 EDGE_SCORES
2582 .iter()
2583 .enumerate()
2584 .filter_map(|(log2, row)| {
2585 let n = row[0].swap(0, std::sync::atomic::Ordering::Relaxed);
2586 let inside = row[1].swap(0, std::sync::atomic::Ordering::Relaxed);
2587 let padding = row[2].swap(0, std::sync::atomic::Ordering::Relaxed);
2588 (n != 0).then_some((1usize << log2, n, inside, padding))
2589 })
2590 .collect()
2591}
2592
2593struct Plane<'a> {
2594 source: &'a [u8],
2595 reconstruction: Vec<u8>,
2596 width: usize,
2597 height: usize,
2598 /// The frame's true, decodable extent in this plane's own units --
2599 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
2600 /// not `width`/`height` above, which is the padded coding-surface size.
2601 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
2602 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
2603 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
2604 /// this bound, even though the padded reconstruction buffer holds real
2605 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
2606 /// those instead of stopping here is what desyncs prediction at the true
2607 /// edge.
2608 true_width: usize,
2609 true_height: usize,
2610 /// This plane's own tile's pixel bounds, in this plane's units -- the
2611 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
2612 /// prediction never reaches across a tile edge even though the
2613 /// neighbouring tile's real samples sit right there in the shared
2614 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
2615 /// leaves every edge exactly as it was before tiles existed.
2616 tile_x0: usize,
2617 tile_y0: usize,
2618 tile_x1: usize,
2619 tile_y1: usize,
2620 /// [`CoefCtxMap`]: what the blocks already committed left for the
2621 /// coefficient contexts of the ones still being priced. Sized on the
2622 /// first commit, so a plane literal does not have to know its own extent
2623 /// twice.
2624 ctx: CoefCtxMap,
2625}
2626
2627impl Plane<'_> {
2628 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
2629 /// called at every superblock of the frame-raster search with the rect
2630 /// of the tile that superblock belongs to.
2631 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
2632 self.tile_x0 = x0;
2633 self.tile_y0 = y0;
2634 self.tile_x1 = x1.min(self.width);
2635 self.tile_y1 = y1.min(self.height);
2636 }
2637 /// The reconstructed samples a block at `(x, y)` predicts from: the row
2638 /// above it, the column to its left and the sample between them, each
2639 /// missing where the block sits against an edge of the frame.
2640 ///
2641 /// `reach` says whether the samples above the block's right and below its
2642 /// left are decoded, which is what a directional mode reads into; where
2643 /// they are not, or where the frame ends first, the edge is shorter and
2644 /// the predictor repeats its last sample, exactly as the decoder's clamp
2645 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
2646 /// lane-av1speed2: the two edges used to be a `Vec` each -- a malloc and
2647 /// a free per mode per block, on the search's hottest path -- while an
2648 /// edge is at most `2 * side` samples, which is `2 * BLOCK`. Same
2649 /// samples, on the caller's stack.
2650 fn edges_into<'a>(
2651 &self,
2652 x: usize,
2653 y: usize,
2654 side: usize,
2655 reach: Reach,
2656 above_buf: &'a mut [u8; 2 * SUPERBLOCK],
2657 left_buf: &'a mut [u8; 2 * SUPERBLOCK],
2658 ) -> (Option<&'a [u8]>, Option<&'a [u8]>, Option<u8>) {
2659 // Even a block's *own* edge is clamped to the true frame bound, not
2660 // just a `reach` extension: libaom's `av1_predict_intra_block`
2661 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
2662 // this block's own right/bottom to the frame edge -- from
2663 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
2664 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
2665 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
2666 // samples the row/column above/left holds before the decoder starts
2667 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
2668 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
2669 // extent straddles that edge legally (`has_half`) -- the transform
2670 // still covers the whole block, but prediction does not get to read
2671 // real reconstructed pixels past the true edge for its own row/column,
2672 // only for the padded tail it invents.
2673 let own_across = x + side.min(self.true_width.saturating_sub(x));
2674 let across = if reach.above_right {
2675 own_across + side.min(self.true_width.saturating_sub(own_across))
2676 } else {
2677 own_across
2678 }
2679 .min(self.width);
2680 let own_down = y + side.min(self.true_height.saturating_sub(y));
2681 let down = if reach.below_left {
2682 own_down + side.min(self.true_height.saturating_sub(own_down))
2683 } else {
2684 own_down
2685 }
2686 .min(self.height);
2687 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
2688 // whose own origin already sits past the true edge -- only reachable
2689 // through a partition trial priced for comparison on a split this
2690 // frame's straddling quadrant will go on to refuse (see
2691 // `a_picture_off_the_block_grid_is_refused`), never through a block
2692 // this encoder actually commits. Such a block has no true-edge
2693 // samples above or left of it at all, same as `y == 0`/`x == 0`.
2694 let across = across.min(self.tile_x1);
2695 let down = down.min(self.tile_y1);
2696 let above_n = (y > self.tile_y0 && across > x).then(|| across - x);
2697 if let Some(n) = above_n {
2698 above_buf[..n]
2699 .copy_from_slice(&self.reconstruction[(y - 1) * self.width + x..][..n]);
2700 }
2701 let left_n = (x > self.tile_x0 && down > y).then(|| down - y);
2702 if let Some(n) = left_n {
2703 for (d, row) in left_buf[..n].iter_mut().zip(y..down) {
2704 *d = self.reconstruction[row * self.width + x - 1];
2705 }
2706 }
2707 let corner = (x > self.tile_x0 && y > self.tile_y0)
2708 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
2709 (
2710 above_n.map(|n| &above_buf[..n]),
2711 left_n.map(|n| &left_buf[..n]),
2712 corner,
2713 )
2714 }
2715
2716 /// Codes one block under one mode without committing it: hands back the
2717 /// levels, the block the decoder would reconstruct, the squared error
2718 /// against the source and an estimate of what the levels cost in bits.
2719 fn trial(&self, at: At, mode: u8, angle_delta: i32, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
2720 self.trial_typed(at, mode, angle_delta, base_q_idx, deadzone, TxType::DctDct, fctx)
2721 }
2722
2723 /// [`Self::trial`] under a named transform type -- what an intra chroma
2724 /// block gets, since chroma codes no `tx_type` symbol and the decoder
2725 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
2726 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
2727 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
2728 #[allow(clippy::too_many_arguments)]
2729 /// Sum of absolute differences between the source block at `(x, y)` and a
2730 /// `side x side` prediction, as the whole number it is.
2731 ///
2732 /// Bit-identical to the `f64` accumulation it replaces: every partial sum
2733 /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
2734 /// exactly, so no add here rounds and the order of the adds cannot change
2735 /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
2736 /// integer division per sample -- is what lets the row walk vectorize.
2737 fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
2738 let mut sad = 0u32;
2739 for row in 0..side {
2740 let source = &self.source[(y + row) * self.width + x..][..side];
2741 for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
2742 sad += u32::from(s.abs_diff(p));
2743 }
2744 }
2745 f64::from(sad)
2746 }
2747
2748 /// Squared error between the source block at `(x, y)` and a reconstruction
2749 /// of it, over the part of the block that is INSIDE the true frame.
2750 /// Exact for the same reason [`Self::block_sad`] is: the largest total is
2751 /// `255^2 * 64 * 64`, under 2^28.
2752 ///
2753 /// A block the frame edge cuts through is still coded whole -- the
2754 /// decoder reconstructs its outside samples too and the display crop
2755 /// throws them away -- so scoring the padding would rank a mode, a
2756 /// transform or a partition tree by how well it codes samples the source
2757 /// does not have (libaom clips the same way: `av1_dist_block` measures
2758 /// over `max_blocks_wide`/`max_blocks_high`). The padding is replicated
2759 /// edge pixels, so predicting it is nearly free, but coding coefficients
2760 /// for it spends real bits. Both gate films are superblock-aligned; this
2761 /// only reaches arbitrary export sizes (lane-sse, generalising
2762 /// lane-b64b's 64-root-only rescore of the 64 root).
2763 fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
2764 let inside_rows = side.min(self.true_height.saturating_sub(y));
2765 let inside_cols = side.min(self.true_width.saturating_sub(x));
2766 let straddles = inside_rows < side || inside_cols < side;
2767 // The knob is read only for a block the edge cuts, so the interior
2768 // path -- the hot one -- carries no extra load at all.
2769 let (rows, cols) = match straddles && !edge_sse() {
2770 true => (side, side),
2771 false => (inside_rows, inside_cols),
2772 };
2773 let mut sse = 0u64;
2774 for row in 0..rows {
2775 let source = &self.source[(y + row) * self.width + x..][..cols];
2776 for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..cols]) {
2777 let d = u32::from(s.abs_diff(r));
2778 sse += u64::from(d * d);
2779 }
2780 }
2781 if straddles && edge_census() {
2782 let (mut inside, mut whole) = (0u64, 0u64);
2783 for row in 0..side {
2784 let source = &self.source[(y + row) * self.width + x..][..side];
2785 for (col, (&s, &r)) in
2786 source.iter().zip(&reconstruction[row * side..][..side]).enumerate()
2787 {
2788 let d = u64::from(u32::from(s.abs_diff(r)).pow(2));
2789 whole += d;
2790 if row < inside_rows && col < inside_cols {
2791 inside += d;
2792 }
2793 }
2794 }
2795 record_edge_score(side, inside, whole - inside);
2796 }
2797 sse as f64
2798 }
2799
2800 fn trial_typed(
2801 &self,
2802 at: At,
2803 mode: u8,
2804 // This block's `angle_delta_y`/`angle_delta_uv` (spec
2805 // `read_intra_angle_info`, -3..=3), zero for every non-directional
2806 // mode -- the predictor's own `angle_delta` argument.
2807 angle_delta: i32,
2808 base_q_idx: u8,
2809 deadzone: f64,
2810 tx_type: TxType,
2811 fctx: &crate::decode::FrameCtx,
2812 ) -> Trial {
2813 let At {
2814 x, y, side, reach, ..
2815 } = at;
2816 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
2817 let (above, left, corner) =
2818 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
2819 // Per-candidate scratch on the search's hottest path, so both buffers
2820 // live on the stack -- `side` is at most `BLOCK` -- rather than
2821 // costing a malloc/free pair per trial (`mc_trial` already does this).
2822 let mut prediction = [0u8; BLOCK * BLOCK];
2823 let prediction = &mut prediction[..side * side];
2824 intra_predict_u8(
2825 mode,
2826 angle_delta,
2827 above,
2828 left,
2829 corner,
2830 side,
2831 side,
2832 false,
2833 false,
2834 prediction, fctx,
2835 );
2836
2837 let mut residual = [0i32; BLOCK * BLOCK];
2838 let residual = &mut residual[..side * side];
2839 for row in 0..side {
2840 for col in 0..side {
2841 residual[row * side + col] =
2842 i32::from(self.source[(y + row) * self.width + x + col])
2843 - i32::from(prediction[row * side + col]);
2844 }
2845 }
2846 #[cfg(test)]
2847 let t = stage_start();
2848 // lane-rdoq: the levels the writer takes are the RDOQ pass's, so the
2849 // reconstruction below and the price further down are both of the
2850 // grid this trial would really code.
2851 let (levels, rdoq_bits) = if rdoq_on() {
2852 let (mut levels, scaled) = forward_and_quantize_typed_scaled(
2853 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2854 );
2855 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2856 let bits = crate::tile::rdoq(
2857 &mut levels, &scaled, side, base_q_idx, at.set, skip_ctx, sign_ctx, rdoq_lambda(),
2858 tx_type,
2859 );
2860 (levels, Some(bits))
2861 } else {
2862 (
2863 forward_and_quantize_typed(
2864 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
2865 ),
2866 None,
2867 )
2868 };
2869 // lane-av1speed2: 60% of the transform units of an inter stream carry
2870 // no coefficient at all, and the square entry point re-inflates that
2871 // case into `side * side` zeros (one allocate-and-memset per trial)
2872 // only for the sum below to add them to the prediction. The `_wh`
2873 // entry hands back the empty all-zero marker instead, and a zero
2874 // residual reconstructs to the prediction itself -- `clamp(p + 0)` is
2875 // `p` for a `u8`, so the bytes are the same.
2876 let coded = dequant_and_inverse_typed_wh(
2877 &levels, side, side, 8, i32::from(base_q_idx), 0, 0, tx_type,
2878 );
2879 #[cfg(test)]
2880 stage_since(2, t);
2881
2882 let reconstruction: Vec<u8> = if coded.is_empty() {
2883 prediction.to_vec()
2884 } else {
2885 prediction
2886 .iter()
2887 .zip(&coded)
2888 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
2889 .collect()
2890 };
2891 let sse = self.block_sse(x, y, side, &reconstruction);
2892 // What the levels cost is priced through the same CDFs the tile writer
2893 // will code them with, so the search ranks modes -- and the partition
2894 // trial ranks trees -- by the bits they actually spend.
2895 #[cfg(test)]
2896 let t = stage_start();
2897 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
2898 // What the search used before it could price a block exactly: a
2899 // level costs its magnitude's width plus a sign and a run. Kept
2900 // reachable from the sweep so the two rate terms can be compared
2901 // on one build.
2902 levels
2903 .iter()
2904 .filter(|&&level| level != 0)
2905 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
2906 .sum()
2907 } else if let Some(bits) = rdoq_bits {
2908 // Already priced, against the grid the pass settled on.
2909 bits
2910 } else {
2911 {
2912 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
2913 crate::tile::coeff_bits_typed(
2914 &levels,
2915 at.set,
2916 crate::decode::q_ctx_of(base_q_idx),
2917 skip_ctx,
2918 sign_ctx,
2919 tx_type,
2920 )
2921 }
2922 };
2923 #[cfg(test)]
2924 stage_since(3, t);
2925 Trial {
2926 levels,
2927 reconstruction,
2928 sse,
2929 bits,
2930 }
2931 }
2932
2933 /// [`Self::trial`] with the prediction already built, so that an inter
2934 /// block's motion-compensated prediction can go through the same
2935 /// residual/quantize/reconstruct path an intra block's does. `skip`
2936 /// takes the prediction as the reconstruction outright, coding no
2937 /// residual at all — what a `NEARESTMV` block that names no coefficients
2938 /// codes.
2939 #[allow(clippy::too_many_arguments)]
2940 fn code_from_prediction(
2941 &self,
2942 x: usize,
2943 y: usize,
2944 side: usize,
2945 prediction: &[u8],
2946 skip: bool,
2947 base_q_idx: u8,
2948 deadzone: f64,
2949 set: TxbSet,
2950 ) -> Trial {
2951 self.code_from_prediction_typed(
2952 x, y, side, prediction, skip, base_q_idx, deadzone, set, TxType::DctDct,
2953 )
2954 }
2955
2956 /// [`Self::code_from_prediction`] coding the residual with a NAMED
2957 /// transform type (lane-txset2): the inter luma sets carry a two-type
2958 /// alphabet (`TX_SET_INTER_3`, `IDTX`/`DCT_DCT`) the writer already codes
2959 /// a symbol for, and [`commit_inter_luma`] prices both through this.
2960 #[allow(clippy::too_many_arguments)]
2961 fn code_from_prediction_typed(
2962 &self,
2963 x: usize,
2964 y: usize,
2965 side: usize,
2966 prediction: &[u8],
2967 skip: bool,
2968 base_q_idx: u8,
2969 deadzone: f64,
2970 set: TxbSet,
2971 tx_type: TxType,
2972 ) -> Trial {
2973 if skip {
2974 let sse = self.block_sse(x, y, side, prediction);
2975 return Trial {
2976 levels: vec![0i32; side * side],
2977 reconstruction: prediction.to_vec(),
2978 sse,
2979 bits: 0.0,
2980 };
2981 }
2982 // A 64x64 root's residual is four times the scratch every other
2983 // block coder here sizes for [`BLOCK`]; only that one case pays for
2984 // a heap buffer, so the 4x4..32x32 path keeps its stack array.
2985 let mut small = [0i32; BLOCK * BLOCK];
2986 let mut big = if side > BLOCK {
2987 vec![0i32; side * side]
2988 } else {
2989 Vec::new()
2990 };
2991 let residual: &mut [i32] = if side > BLOCK {
2992 &mut big
2993 } else {
2994 &mut small[..side * side]
2995 };
2996 for row in 0..side {
2997 for col in 0..side {
2998 residual[row * side + col] =
2999 i32::from(self.source[(y + row) * self.width + x + col])
3000 - i32::from(prediction[row * side + col]);
3001 }
3002 }
3003 #[cfg(test)]
3004 let t = stage_start();
3005 // lane-rdoq, as in [`Self::trial_typed`].
3006 let (levels, rdoq_bits) = if rdoq_on() {
3007 let (mut levels, scaled) =
3008 forward_and_quantize_typed_scaled(
3009 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
3010 );
3011 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3012 let bits = crate::tile::rdoq(
3013 &mut levels, &scaled, side, base_q_idx, set, skip_ctx, sign_ctx, rdoq_lambda(),
3014 tx_type,
3015 );
3016 (levels, Some(bits))
3017 } else {
3018 (
3019 forward_and_quantize_typed(
3020 residual, side, 8, i32::from(base_q_idx), deadzone, tx_type,
3021 ),
3022 None,
3023 )
3024 };
3025 // The same all-zero shortcut [`Self::trial_typed`] takes.
3026 let coded = dequant_and_inverse_typed_wh(
3027 &levels,
3028 side,
3029 side,
3030 8,
3031 i32::from(base_q_idx),
3032 0,
3033 0,
3034 tx_type,
3035 );
3036 #[cfg(test)]
3037 stage_since(2, t);
3038 let reconstruction: Vec<u8> = if coded.is_empty() {
3039 prediction.to_vec()
3040 } else {
3041 prediction
3042 .iter()
3043 .zip(&coded)
3044 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
3045 .collect()
3046 };
3047 let sse = self.block_sse(x, y, side, &reconstruction);
3048 // A 64-point transform codes only its top-left 32x32 corner (spec
3049 // 5.11.39's zero-out; `TxbSet::Luma64`'s tables are 32-sided and the
3050 // key frame writer takes a 32x32 level grid for one). The inverse
3051 // above reads the whole 64x64 array, but the price below and the
3052 // levels the writer takes are that corner.
3053 let levels = if side > BLOCK {
3054 coded_corner(&levels, side, BLOCK)
3055 } else {
3056 levels
3057 };
3058 #[cfg(test)]
3059 let t = stage_start();
3060 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
3061 levels
3062 .iter()
3063 .filter(|&&level| level != 0)
3064 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
3065 .sum()
3066 } else if let Some(bits) = rdoq_bits {
3067 bits
3068 } else {
3069 {
3070 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
3071 crate::tile::coeff_bits_typed(
3072 &levels,
3073 set,
3074 crate::decode::q_ctx_of(base_q_idx),
3075 skip_ctx,
3076 sign_ctx,
3077 tx_type,
3078 )
3079 }
3080 };
3081 #[cfg(test)]
3082 stage_since(3, t);
3083 Trial {
3084 levels,
3085 reconstruction,
3086 sse,
3087 bits,
3088 }
3089 }
3090
3091 /// Codes this block's luma at transform depth `depth`: the
3092 /// `(side >> depth)^2` transform units in raster order, each predicted
3093 /// from the reconstruction the units before it left behind -- exactly
3094 /// what the decoder's multi-transform-unit branch does (decode.rs
3095 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
3096 /// reconstructed on its own. Commits the result and hands back the
3097 /// block-coordinate levels, the block's squared error and what its
3098 /// coefficients cost.
3099 #[allow(clippy::too_many_arguments)]
3100 fn code_tx_depth(
3101 &mut self,
3102 at: At,
3103 mode: u8,
3104 angle_delta: i32,
3105 depth: usize,
3106 // This block's `filter_intra_mode` when it is coded with one, in
3107 // which case every transform unit predicts recursively off the
3108 // reconstruction the units before it left -- what the decoder does
3109 // per unit (decode.rs `decode_block`, `push_intra_rect`'s
3110 // `filter_intra`), not once over the whole block.
3111 filter_intra: Option<u8>,
3112 search: &Search, fctx: &crate::decode::FrameCtx,
3113 ) -> (Vec<i32>, f64, f64, Vec<TxType>) {
3114 let At { x, y, side, reach, .. } = at;
3115 let tx = side >> depth;
3116 let n = 1usize << depth;
3117 let set = luma_set_for(
3118 match tx {
3119 32 => TxbSet::Luma32,
3120 16 => TxbSet::Luma16,
3121 8 => TxbSet::Luma8,
3122 _ => TxbSet::Luma4,
3123 },
3124 search.screen,
3125 );
3126 let mut levels = vec![0i32; side * side];
3127 census_add(4, n * n);
3128 // A unit smaller than its block reads the neighbour magnitude table
3129 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
3130 self.ctx.tu_split = n > 1;
3131 let (mut sse, mut bits) = (0.0, 0.0);
3132 // One entry per unit at its own `tu_row * n + tu_col`, which is how
3133 // the writer indexes them (tile.rs `write_luma_tus`) -- a unit the
3134 // frame edge cuts away is never coded there, so a compacted list
3135 // would slide every later unit's type onto the wrong transform.
3136 let mut tx_types = vec![TxType::DctDct; n * n];
3137 for tu_row in 0..n {
3138 for tu_col in 0..n {
3139 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
3140 let tu = At {
3141 x: x + col_off,
3142 y: y + row_off,
3143 side: tx,
3144 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
3145 set,
3146 };
3147 let trial = match filter_intra {
3148 Some(fi) => {
3149 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3150 let (above, left, corner) =
3151 self.edges_into(tu.x, tu.y, tx, tu.reach, &mut above_buf, &mut left_buf);
3152 let mut prediction = vec![0u8; tx * tx];
3153 filter_intra_predict_u8(
3154 usize::from(fi),
3155 above,
3156 left,
3157 corner,
3158 tx,
3159 &mut prediction,
3160 fctx,
3161 );
3162 self.code_from_prediction(
3163 tu.x,
3164 tu.y,
3165 tx,
3166 &prediction,
3167 false,
3168 search.base_q_idx,
3169 search.deadzone,
3170 set,
3171 )
3172 }
3173 None => {
3174 // lane-txset: the unit picks its own transform type
3175 // out of the set the writer can name it in, priced
3176 // through the same RDOQ'd trial path (its `bits`
3177 // already carry the `tx_type` symbol itself).
3178 let mut best: Option<(f64, TxType, Trial)> = None;
3179 for &tx_type in tx_type_candidates(set, search.screen) {
3180 let candidate = self.trial_typed(
3181 tu, mode, angle_delta, search.base_q_idx, search.deadzone,
3182 tx_type, fctx,
3183 );
3184 // lane-txi: a non-`DCT_DCT` type is charged its
3185 // bits at `EC_AV1_TXRD_LAMBDA` times the mode
3186 // search's weight (default 1 = unchanged). The
3187 // film rows buy 0.04 dB for 1.2% more bytes at
3188 // weight 1 on every frame and every PLANE, key
3189 // frame included -- a rate term this decision
3190 // under-charges (class
3191 // `rd-rate-term-calibration`), not the
3192 // propagation loss the leaves would have shown.
3193 let cost = candidate.sse
3194 + search.lambda * candidate.bits
3195 + non_dct_surcharge(search.lambda, tx_type, candidate.bits);
3196 if best.as_ref().is_none_or(|(best, _, _)| cost < *best) {
3197 best = Some((cost, tx_type, candidate));
3198 }
3199 }
3200 let (_, tx_type, trial) =
3201 best.expect("the candidate list is never empty");
3202 tx_types[tu_row * n + tu_col] = tx_type;
3203 TX_TYPE_HITS[tx_type as usize]
3204 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3205 trial
3206 }
3207 };
3208 sse += trial.sse;
3209 bits += trial.bits;
3210 self.commit(tu.x, tu.y, tx, &trial);
3211 for row in 0..tx {
3212 levels[(row_off + row) * side + col_off..][..tx]
3213 .copy_from_slice(&trial.levels[row * tx..][..tx]);
3214 }
3215 }
3216 }
3217 self.ctx.tu_split = false;
3218 (levels, sse, bits, tx_types)
3219 }
3220
3221 /// Writes a trial's reconstruction back into the plane, and the
3222 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
3223 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
3224 for row in 0..side {
3225 self.reconstruction[(y + row) * self.width + x..][..side]
3226 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
3227 }
3228 self.commit_ctx(x, y, side, &trial.levels);
3229 }
3230
3231 /// Publishes one committed transform's own context over every 4x4 cell it
3232 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
3233 /// which is what the writer will read when it reaches the next block.
3234 fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
3235 if self.ctx.cells.is_empty() {
3236 self.ctx.stride = self.width.div_ceil(4);
3237 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
3238 }
3239 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
3240 let state = CoefCtx {
3241 level: cul,
3242 dc: match levels[0].signum() {
3243 0 => 0,
3244 -1 => -1,
3245 _ => 1,
3246 },
3247 };
3248 let n = (side / 4).max(1);
3249 // Only up to the frame's TRUE extent: the writer's own
3250 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
3251 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
3252 // and leaves the cells past it uncoded even mid-block, so a
3253 // straddling block publishes context for its inside part only.
3254 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
3255 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
3256 for row in 0..rows {
3257 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3258 let end = (start + cols).min(self.ctx.cells.len());
3259 if start < end {
3260 self.ctx.cells[start..end].fill(state);
3261 }
3262 }
3263 }
3264
3265 /// A block committed without any residual at all ([`ibc_commit`]): the
3266 /// cells it covers coded nothing, and leaving an earlier trial's state
3267 /// there would price its neighbours off a block that was never coded.
3268 fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
3269 self.commit_ctx(x, y, side, &[0i32]);
3270 }
3271
3272 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
3273 /// plane reads, off what the blocks before it in coding order committed
3274 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
3275 /// the above/left neighbours coded anything (tile.rs
3276 /// `write_block_planes`), luma reads context 0 when its transform covers
3277 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
3278 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
3279 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
3280 /// the same neighbours (tile.rs `dc_sign_ctx`).
3281 ///
3282 /// A neighbour outside this plane's own TILE does not exist, exactly as
3283 /// the writer's per-tile `Neighbours` bands start blank.
3284 ///
3285 /// CLOSED (lane-av1straddle): the decisions this price changes used to
3286 /// make `decode_stream_round_trips_an_odd_size_gop` and
3287 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
3288 /// fail at 216x96. Never this map: the writer coded the phantom
3289 /// transform units of a right-edge-straddling 32x32 (tile.rs
3290 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
3291 /// like decode.rs and libaom), which libdav1d and libaom both refused
3292 /// outright while a decision change was what first walked into it.
3293 fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
3294 if self.ctx.cells.is_empty() {
3295 return (0, 0);
3296 }
3297 let n = (side / 4).max(1);
3298 let (cx, cy) = (x / 4, y / 4);
3299 let (mut top, mut left) = (0u8, 0u8);
3300 let mut vote = 0i32;
3301 if y > self.tile_y0 && cy > 0 {
3302 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
3303 top |= cell.level;
3304 vote += i32::from(cell.dc);
3305 }
3306 }
3307 if x > self.tile_x0 && cx > 0 {
3308 for row in 0..n {
3309 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
3310 left |= cell.level;
3311 vote += i32::from(cell.dc);
3312 }
3313 }
3314 let skip_ctx = if set.is_chroma() {
3315 usize::from(top != 0) + usize::from(left != 0)
3316 } else if self.ctx.tu_split {
3317 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
3318 } else {
3319 0
3320 };
3321 let sign_ctx = match vote.signum() {
3322 0 => 0,
3323 -1 => 1,
3324 _ => 2,
3325 };
3326 (skip_ctx, sign_ctx)
3327 }
3328
3329 /// The source samples of one square, contiguous — what a motion search
3330 /// compares its candidates' predictions against ([`motion::search`]'s
3331 /// `source`), since [`Self::source`] itself is the whole plane, strided
3332 /// by [`Self::width`].
3333 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
3334 rows_of(self.source, self.width, x, y, side)
3335 }
3336
3337 /// lane-b128hv: [`Self::source_block`] over a rectangle, for the 128
3338 /// root's own HORZ/VERT motion search.
3339 fn source_block_rect(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> {
3340 let mut out = vec![0u8; w * h];
3341 for row in 0..h {
3342 out[row * w..][..w]
3343 .copy_from_slice(&self.source[(y + row) * self.width + x..][..w]);
3344 }
3345 out
3346 }
3347
3348 /// The reconstructed samples of one square, so that a partition trial can
3349 /// be undone.
3350 /// The reconstructed samples of one square AND the coefficient contexts
3351 /// its cells hold, so that a partition trial can be undone whole: a
3352 /// losing trial that left its own nz/DC state behind would price the
3353 /// blocks after it off a block the tile writer never codes.
3354 fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
3355 (
3356 rows_of(&self.reconstruction, self.width, x, y, side),
3357 self.ctx_rows(x, y, side),
3358 )
3359 }
3360
3361 fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
3362 if self.ctx.cells.is_empty() {
3363 return Vec::new();
3364 }
3365 let n = (side / 4).max(1);
3366 (0..n)
3367 .flat_map(|row| {
3368 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3369 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
3370 })
3371 .collect()
3372 }
3373
3374 /// Puts a snapshot back.
3375 fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
3376 for row in 0..side {
3377 self.reconstruction[(y + row) * self.width + x..][..side]
3378 .copy_from_slice(&saved.0[row * side..][..side]);
3379 }
3380 if saved.1.is_empty() {
3381 return;
3382 }
3383 let n = (side / 4).max(1);
3384 for row in 0..n {
3385 let start = (y / 4 + row) * self.ctx.stride + x / 4;
3386 let end = (start + n).min(self.ctx.cells.len());
3387 if start < end {
3388 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
3389 }
3390 }
3391 }
3392
3393 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
3394 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
3395 /// prescreen by the identical rule rather than a second one that could
3396 /// drift from it.
3397 fn intra_scores(
3398 &self,
3399 at: At,
3400 modes: &[u8],
3401 mode_bits: &[f64; 13],
3402 lambda: f64, fctx: &crate::decode::FrameCtx,
3403 ) -> Vec<(f64, u8)> {
3404 let At {
3405 x, y, side, reach, ..
3406 } = at;
3407 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3408 let (above, left, corner) =
3409 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3410 modes
3411 .iter()
3412 .map(|&mode| {
3413 let mut prediction = vec![0u8; side * side];
3414 intra_predict_u8(
3415 mode,
3416 0,
3417 above,
3418 left,
3419 corner,
3420 side,
3421 side,
3422 false,
3423 false,
3424 &mut prediction, fctx,
3425 );
3426 let sad = self.block_sad(x, y, side, &prediction);
3427 (sad + lambda * mode_bits[usize::from(mode)], mode)
3428 })
3429 .collect()
3430 }
3431
3432 /// Codes one block under every mode the search offers (or, when
3433 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
3434 /// pre-pass plus DC) and commits the one whose squared error and
3435 /// estimated rate come out cheapest.
3436 ///
3437 /// The prediction is built once per mode regardless -- the full RD trial
3438 /// needs it too -- so ranking modes by SAD on that same prediction before
3439 /// running the expensive part (forward transform, quantize, reconstruct,
3440 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
3441 /// only to sum.
3442 fn search_block(
3443 &mut self,
3444 at: At,
3445 search: &Search,
3446 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
3447 ) -> (Vec<Coeff>, u8, i32, f64, TxType) {
3448 let At {
3449 x, y, side, reach, ..
3450 } = at;
3451 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
3452 let (above, left, corner) =
3453 self.edges_into(x, y, side, reach, &mut above_buf, &mut left_buf);
3454 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
3455 // the census reports it), so summing it under the default unpruned
3456 // search is `side * side` absolute differences per mode spent on a
3457 // number no one reads.
3458 let want_sad = search.top_k.is_some() || census_on();
3459 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
3460 .modes
3461 .iter()
3462 .map(|&mode| {
3463 let mut prediction = vec![0u8; side * side];
3464 intra_predict_u8(
3465 mode,
3466 0,
3467 above,
3468 left,
3469 corner,
3470 side,
3471 side,
3472 false,
3473 false,
3474 &mut prediction, fctx,
3475 );
3476 let sad = if want_sad {
3477 self.block_sad(x, y, side, &prediction)
3478 } else {
3479 0.0
3480 };
3481 (
3482 sad + search.lambda * mode_bits[usize::from(mode)],
3483 mode,
3484 prediction,
3485 )
3486 })
3487 .collect();
3488 if let Some(k) = search.top_k {
3489 if k < scored.len() {
3490 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
3491 let dc_entry = dc_pos.map(|i| scored.remove(i));
3492 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
3493 scored.truncate(if dc_entry.is_some() {
3494 k.saturating_sub(1)
3495 } else {
3496 k
3497 });
3498 if let Some(dc_entry) = dc_entry {
3499 scored.push(dc_entry);
3500 }
3501 }
3502 }
3503 let ranking: Vec<(f64, u8)> = if census_on() {
3504 scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
3505 } else {
3506 Vec::new()
3507 };
3508 census_add(0, 1);
3509 census_add(1, scored.len());
3510 let mut best: Option<(f64, u8, Trial)> = None;
3511 for (_, mode, prediction) in scored {
3512 let trial = self.code_from_prediction(
3513 x,
3514 y,
3515 side,
3516 &prediction,
3517 false,
3518 search.base_q_idx,
3519 search.deadzone,
3520 at.set,
3521 );
3522 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
3523 if best
3524 .as_ref()
3525 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
3526 {
3527 best = Some((cost, mode, trial));
3528 }
3529 }
3530 let (mut cost, mode, mut trial) = best.expect("the search offers at least one mode");
3531 // `angle_delta_y` (spec `read_intra_angle_info`): the eight
3532 // directional modes each carry a -3..=3 delta, three degrees a step,
3533 // which the writer has always coded as ZERO because nothing searched
3534 // it. Refined on the winning mode only -- libaom's own ordering, and
3535 // six extra trials on the directional blocks instead of on every
3536 // block times every mode. The edges are the ones the base angle
3537 // already read (`enable_intra_edge_filter` is off in this encoder's
3538 // sequence header, so no delta changes which samples exist), and the
3539 // predictor is the decoder's, `angle_delta` argument and all.
3540 let mut angle_delta = 0i32;
3541 // Not on a screen frame: measured on the 5-row native gate, the
3542 // refinement is worth -0.6/-0.6 on the 2160p film row and flat on the
3543 // 1080p one, but +0.7/+0.3 the WRONG way on the screen capture --
3544 // synthetic edges land on the base angles, so every delta there buys
3545 // a symbol and no prediction. Same `search.screen` gate palette and
3546 // intrabc already stand behind.
3547 if angle_delta_on() && !search.screen && (V_PRED..=D67_PRED).contains(&mode) {
3548 let row = &cdf::ANGLE_DELTA[usize::from(mode - V_PRED)];
3549 let zero_bits = symbol_bits(row, crate::tile::ANGLE_DELTA_ZERO);
3550 let mut prediction = vec![0u8; side * side];
3551 for delta in [-3i32, -2, -1, 1, 2, 3] {
3552 intra_predict_u8(
3553 mode,
3554 delta,
3555 above,
3556 left,
3557 corner,
3558 side,
3559 side,
3560 false,
3561 false,
3562 &mut prediction, fctx,
3563 );
3564 let candidate = self.code_from_prediction(
3565 x,
3566 y,
3567 side,
3568 &prediction,
3569 false,
3570 search.base_q_idx,
3571 search.deadzone,
3572 at.set,
3573 );
3574 let bits = symbol_bits(row, (crate::tile::ANGLE_DELTA_ZERO as i32 + delta) as usize)
3575 - zero_bits;
3576 let cost_d = candidate.sse
3577 + search.lambda * (candidate.bits + mode_bits[usize::from(mode)] + bits);
3578 if cost_d < cost {
3579 cost = cost_d;
3580 angle_delta = delta;
3581 trial = candidate;
3582 }
3583 }
3584 ANGLE_DELTA_HITS[(crate::tile::ANGLE_DELTA_ZERO as i32 + angle_delta) as usize]
3585 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3586 }
3587 // lane-txset: the block's own transform type, searched on the mode
3588 // and angle the trials above settled -- the same ordering the angle
3589 // refinement uses, and the same RD terms.
3590 let mut tx_type = TxType::DctDct;
3591 for &candidate_type in tx_type_candidates(at.set, search.screen).iter().skip(1) {
3592 let candidate = self.trial_typed(
3593 at, mode, angle_delta, search.base_q_idx, search.deadzone, candidate_type, fctx,
3594 );
3595 let cost_t =
3596 candidate.sse + search.lambda * (candidate.bits + mode_bits[usize::from(mode)]);
3597 // lane-txi's surcharge, as in `code_tx_depth`: the incumbent is
3598 // `DCT_DCT` and pays none of it, so the returned `cost` stays the
3599 // block's true one for the caller's own decision.
3600 if cost_t + non_dct_surcharge(search.lambda, candidate_type, candidate.bits) < cost {
3601 cost = cost_t;
3602 tx_type = candidate_type;
3603 trial = candidate;
3604 }
3605 }
3606 TX_TYPE_HITS[tx_type as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3607 if census_on() {
3608 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
3609 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3610 }
3611 self.commit(x, y, side, &trial);
3612 // A 64-point transform codes only its top-left 32x32 corner, which is
3613 // the grid `code_from_prediction` hands back (lane-i64).
3614 (coeffs(&trial.levels, side.min(BLOCK)), mode, angle_delta, cost, tx_type)
3615 }
3616}
3617
3618/// Where one block sits in its plane, and how far past its own edges its
3619/// prediction may read.
3620#[derive(Clone, Copy)]
3621struct At {
3622 x: usize,
3623 y: usize,
3624 side: usize,
3625 reach: Reach,
3626 /// Which of the tile writer's coefficient tables this block's levels are
3627 /// coded with, and so which the search prices them through.
3628 set: TxbSet,
3629}
3630
3631/// Which of the samples past a block's own edges the decoder has decoded by
3632/// the time it predicts the block, and so which a directional mode may read.
3633///
3634/// The decoder derives these from its `BlockDecoded` flags, which are cleared
3635/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
3636/// that map, this reads the answer the same way libaom and rav1e do: for a
3637/// block whose transform covers it whole, whether the samples above its right
3638/// (or below its left) are decoded depends only on where the block sits inside
3639/// its 64x64 superblock, which is a pinned table per block size.
3640#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3641pub(crate) struct Reach {
3642 pub(crate) above_right: bool,
3643 pub(crate) below_left: bool,
3644}
3645
3646/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
3647/// libaom): for a block that is neither in the superblock's top row nor its
3648/// rightmost column, whether the block above and to its right is coded before
3649/// it. Indexed by the block's position in the superblock, in blocks of its own
3650/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
3651/// 128, not this crate's 64 superblock -- bit by bit from the low end.
3652const HAS_TOP_RIGHT: [&[u8]; 4] = [
3653 &[255, 85, 119, 85, 127, 85, 119, 85],
3654 &[95, 87],
3655 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
3656 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
3657 &[
3658 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
3659 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
3660 ],
3661
3662 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
3663 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
3664 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
3665 // with side 4 outside a TX4 split; without their own row they clamped
3666 // into the 8x8 table and read above-right samples the decoder has not
3667 // written yet (all-zero pixels in the bottom-right triangle of a
3668 // directional 4x4 leaf).
3669 &[
3670 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
3671 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
3672 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
3673 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
3674 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
3675 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
3676 119, 119, 119, 119, 85, 85, 85, 85,
3677 ],
3678];
3679
3680/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
3681/// left.
3682const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
3683 &[84, 16, 84, 0, 84, 16, 84, 0],
3684 &[4, 4],
3685 // has_bl_8x8 (libaom av1/common/reconintra.c)
3686 &[
3687 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
3688 84, 85, 16, 17, 84, 85, 0, 0,
3689 ],
3690
3691 // has_bl_4x4 (same source, same order).
3692 &[
3693 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
3694 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84,
3695 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
3696 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 1, 0, 84, 85,
3697 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
3698 85, 85, 0, 0, 0, 0,
3699 ],
3700];
3701
3702/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
3703/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
3704/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
3705/// rather than in raster order, so the bottom-left square's top-right
3706/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
3707/// libaom switches tables on the partition type (`get_has_tr_table`); the
3708/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
3709/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
3710/// lane-part32 r5 caught reading undecoded samples.
3711const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
3712 // has_tr_vert_16x16
3713 &[255, 0, 119, 0, 127, 0, 119, 0],
3714 // has_tr_vert_32x32
3715 &[15, 7],
3716 // has_tr_vert_8x8
3717 &[
3718 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
3719 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
3720 ],
3721];
3722
3723/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
3724const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
3725 // has_bl_vert_16x16
3726 &[254, 16, 254, 0, 254, 16, 254, 0],
3727 // has_bl_vert_32x32
3728 &[14, 14],
3729 // has_bl_vert_8x8
3730 &[
3731 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
3732 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
3733 ],
3734];
3735
3736thread_local! {
3737 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
3738 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
3739 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
3740 /// threading one bool through this crate's already twenty-argument
3741 /// `decode_block` would touch every call site instead of the two arms
3742 /// that need it.
3743 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
3744}
3745
3746/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
3747pub(crate) struct VertAbGuard(bool);
3748
3749impl Drop for VertAbGuard {
3750 fn drop(&mut self) {
3751 VERT_AB_PARTITION.with(|c| c.set(self.0));
3752 }
3753}
3754
3755/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
3756/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
3757/// so no byte is retyped). Each is indexed by
3758/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
3759/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
3760/// superblock grid; on this crate's 64-pixel superblock the highest index a
3761/// shape can reach stays inside its own table, so no wrap is involved.
3762///
3763/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
3764/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
3765/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
3766/// 10 of the 21 reachable superblock positions for above-right and 7 for
3767/// below-left.
3768/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3769const HAS_TR_4X8: [u8; 64] = [255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119];
3770/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
3771const HAS_BL_4X8: [u8; 64] = [16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0];
3772/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3773const HAS_TR_8X4: [u8; 64] = [255, 255, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 255, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0];
3774/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
3775const HAS_BL_8X4: [u8; 64] = [254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0];
3776/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3777const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119];
3778/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
3779const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
3780/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3781const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
3782/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
3783const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0];
3784/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3785const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
3786/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
3787const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
3788/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3789const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
3790/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
3791const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
3792/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3793const HAS_TR_32X64: [u8; 1] = [127];
3794/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
3795const HAS_BL_32X64: [u8; 1] = [0];
3796/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3797const HAS_TR_64X32: [u8; 1] = [19];
3798/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
3799const HAS_BL_64X32: [u8; 1] = [34];
3800/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3801const HAS_TR_4X16: [u8; 32] = [255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255, 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127];
3802/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
3803const HAS_BL_4X16: [u8; 32] = [0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0];
3804/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3805const HAS_TR_16X4: [u8; 32] = [255, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, 127, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0];
3806/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
3807const HAS_BL_16X4: [u8; 32] = [254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0];
3808/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3809const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
3810/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
3811const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
3812/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3813const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
3814/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
3815const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
3816/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3817const HAS_TR_16X64: [u8; 2] = [255, 127];
3818/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
3819const HAS_BL_16X64: [u8; 2] = [0, 0];
3820/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3821const HAS_TR_64X16: [u8; 2] = [3, 1];
3822/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
3823const HAS_BL_64X16: [u8; 2] = [42, 42];
3824
3825/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
3826fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
3827 match (bw, bh) {
3828 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
3829 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
3830 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
3831 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
3832 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
3833 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
3834 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
3835 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
3836 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
3837 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
3838 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
3839 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
3840 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
3841 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
3842 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
3843 }
3844}
3845
3846impl Reach {
3847 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
3848 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
3849 /// own answer is `block` -- a different rule from the standalone-block
3850 /// tables, because a unit's neighbours are mostly its own block's
3851 /// already-reconstructed units:
3852 /// * top-right: available while the unit to the right is still inside
3853 /// the block (`col_off + tx < bw`); otherwise only the block's top row
3854 /// of units reaches past it, through the block-level answer
3855 /// (libaom's `row_off > 0` branch returns exactly
3856 /// `col_off + txw < plane_bw`).
3857 /// * bottom-left: a unit outside the block's left column has none
3858 /// (libaom returns 0 for `col_off > 0`); inside the block
3859 /// (`row_off + tx < bh`) they are the left unit's, already
3860 /// reconstructed; the bottom row falls back to the block-level answer.
3861 pub(crate) fn of_tu(
3862 bw: usize,
3863 bh: usize,
3864 col_off: usize,
3865 row_off: usize,
3866 // The unit's own width and height in pixels; equal for a square
3867 // transform, different for the rect unit a 1:4 strip's first split
3868 // produces (lane-rectsplitx r1).
3869 tx_w: usize,
3870 tx_h: usize,
3871 block: Self,
3872 ) -> Self {
3873 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
3874 // order, so both libaom predicates special-case it (lane-sb128c r10);
3875 // without this the last unit column of every chunk of a 128x64 block
3876 // predicts from a chunk libaom has not decoded yet.
3877 let wide = bw > 64;
3878 Self {
3879 above_right: if row_off > 0 {
3880 // `has_top_right`'s `row_off > 0` branch: the offset is taken
3881 // modulo the 64-wide chunk, except for the one unit whose
3882 // top-right corner is the centre of a 128x128 block.
3883 if wide {
3884 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
3885 } else {
3886 col_off + tx_w < bw
3887 }
3888 } else if col_off + tx_w < bw {
3889 true
3890 } else {
3891 block.above_right
3892 },
3893 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
3894 // `has_bottom_left`: at the left edge of a right-hand chunk
3895 // the bottom-left pixels are in the already-coded left chunk,
3896 // provided they stay inside it.
3897 (row_off % 64) + tx_h < bh.min(64)
3898 } else if col_off > 0 {
3899 false
3900 } else if row_off + tx_h < bh {
3901 true
3902 } else {
3903 block.below_left
3904 },
3905 }
3906 }
3907
3908 /// What a block of `side` samples at `(x, y)` may read past its own edges,
3909 /// in a frame of `width` by `height`.
3910 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
3911 Self {
3912 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
3913 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
3914 }
3915 }
3916
3917 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
3918 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
3919 /// block's own width for the row stride and by its own height for the
3920 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
3921 /// unlike the square [`Self::of`] which uses one `side` for everything.
3922 pub(crate) fn of_rect(
3923 bw: usize,
3924 bh: usize,
3925 x: usize,
3926 y: usize,
3927 width: usize,
3928 height: usize, fctx: &crate::decode::FrameCtx,
3929 ) -> Self {
3930 Self {
3931 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
3932 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
3933 }
3934 }
3935
3936 /// [`Self::of`] for one transform unit of a square block whose transform
3937 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
3938 /// non-zero `row_off`/`col_off`): interior units answer from the block's
3939 /// own geometry, and only a unit on the block's top row (resp. left
3940 /// column) reaches the table -- which is the BLOCK's table read at the
3941 /// BLOCK's position, never a table row for the transform's size. Letting
3942 /// the unit stand in for a block of its own size agrees with libaom for
3943 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
3944 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
3945 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
3946 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
3947 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
3948 /// the transform covering the whole block, luma): everything before the
3949 /// table lookup is that function's own early-exit ladder.
3950 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3951 let sb_mi: usize = reach_sb_px(fctx) / 4;
3952 let (mi_row, mi_col) = (y / 4, x / 4);
3953 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3954 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3955 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3956 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3957 // Top row of the superblock: the top-right pixels are in the (already
3958 // decoded) superblock above.
3959 if blk_row == 0 {
3960 return true;
3961 }
3962 // Rightmost column: they fall in the superblock to the right.
3963 if ((blk_col + 1) << bw_log2) >= sb_mi {
3964 return false;
3965 }
3966 let table = rect_reach_tables(bw, bh).0;
3967 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
3968 }
3969
3970 /// libaom `has_top_right`'s own index arithmetic:
3971 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
3972 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
3973 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
3974 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
3975 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
3976 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
3977 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
3978 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
3979 (blk_row << (5 - bw_log2)) + blk_col
3980 }
3981
3982 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
3983 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
3984 let sb_mi: usize = reach_sb_px(fctx) / 4;
3985 let (mi_row, mi_col) = (y / 4, x / 4);
3986 let bw_log2 = (bw / 4).trailing_zeros() as usize;
3987 let bh_log2 = (bh / 4).trailing_zeros() as usize;
3988 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
3989 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
3990 // Leftmost column of the superblock: the bottom-left pixels are in
3991 // the left superblock iff they stay inside its height.
3992 if blk_col == 0 {
3993 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
3994 }
3995 // Bottom row (and not the leftmost column): they fall in the
3996 // superblock below, which is not decoded yet.
3997 if ((blk_row + 1) << bh_log2) >= sb_mi {
3998 return false;
3999 }
4000 let table = rect_reach_tables(bw, bh).1;
4001 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
4002 }
4003
4004 /// Marks every [`Reach::of`] made until the returned guard drops as being
4005 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
4006 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
4007 /// unaffected: libaom's own comment says vertical rectangles keep their
4008 /// non-vert table, which is what [`Reach::of_rect`] already reads.
4009 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
4010 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
4011 /// can count the sub-block work that partition creates (lane-ab16).
4012 pub(crate) fn in_vert_ab() -> bool {
4013 VERT_AB_PARTITION.with(std::cell::Cell::get)
4014 }
4015
4016 pub(crate) fn vert_ab_partition() -> VertAbGuard {
4017 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
4018 }
4019
4020 /// Neither, which is all a mode that reads no further than its own edges
4021 /// needs.
4022 pub(crate) fn none() -> Self {
4023 Self {
4024 above_right: false,
4025 below_left: false,
4026 }
4027 }
4028
4029 /// `has_top_right` for a block whose transform covers it whole: the top
4030 /// row of a superblock reads into the superblock above, which is decoded;
4031 /// the rightmost column would read into the superblock to the right, which
4032 /// is not; and everything between is the table's to answer.
4033 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4034 let (row, col, per_side) = Self::position(side, x, y, fctx);
4035 if row == 0 {
4036 return true;
4037 }
4038 if col + 1 == per_side {
4039 return false;
4040 }
4041 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4042 // (the clamp corner-cut that used to live here is gone); sides
4043 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4044 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4045 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4046 // -- a reach over-estimate (extra above-right reference pixels),
4047 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4048 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4049 // NB: named `table_row`, not `row` -- `row` above is the block's
4050 // position inside the superblock and is what the bit index below
4051 // steps by (a merge that shadowed it desynced every block size).
4052 let table_row = Self::table(side);
4053 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() {
4054 HAS_TOP_RIGHT_VERT[table_row]
4055 } else {
4056 HAS_TOP_RIGHT[table_row]
4057 };
4058 Self::bit(
4059 table,
4060 (row * Self::table_stride(side) + col) % (table.len() * 8),
4061 )
4062 }
4063
4064 /// `has_bottom_left` for such a block: the leftmost column of a superblock
4065 /// reads into the superblock to its left, which is decoded only as far
4066 /// down as its own bottom; the bottom row would read into the superblock
4067 /// below, which is not decoded at all; and the table answers the rest.
4068 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
4069 let (row, col, per_side) = Self::position(side, x, y, fctx);
4070 if col == 0 {
4071 return row * side + side < reach_sb_px(fctx);
4072 }
4073 if row + 1 == per_side {
4074 return false;
4075 }
4076 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
4077 // (the clamp corner-cut that used to live here is gone); sides
4078 // 16/32/64 share row 0 exactly as libaom's tables repeat.
4079 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
4080 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
4081 // -- a reach over-estimate (extra above-right reference pixels),
4082 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
4083 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
4084 // NB: named `table_row`, not `row` -- `row` above is the block's
4085 // position inside the superblock and is what the bit index below
4086 // steps by (a merge that shadowed it desynced every block size).
4087 let table_row = Self::table(side);
4088 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() {
4089 HAS_BOTTOM_LEFT_VERT[table_row]
4090 } else {
4091 HAS_BOTTOM_LEFT[table_row]
4092 };
4093 Self::bit(
4094 table,
4095 (row * Self::table_stride(side) + col) % (table.len() * 8),
4096 )
4097 }
4098
4099 /// Where a block sits inside its superblock, in blocks of its own size,
4100 /// and how many of them a superblock is across.
4101 fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
4102 let sb = reach_sb_px(fctx);
4103 ((y % sb) / side, (x % sb) / side, sb / side)
4104 }
4105
4106 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
4107 /// these tables to its compile-time maximum superblock (128, spec
4108 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
4109 /// size an encode actually uses, so a block's row in the bit index steps
4110 /// by 128 / `side` even though this crate only ever codes a 64
4111 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
4112 /// here instead indexes the wrong bit for every block size but the one
4113 /// where 64 and 128 give the same stride.
4114 fn table_stride(side: usize) -> usize {
4115 128 / side
4116 }
4117
4118 /// Which of the three block sizes the encoder codes a table row is for.
4119 fn table(side: usize) -> usize {
4120 if side == BLOCK {
4121 1
4122 } else if side == 8 {
4123 2
4124 } else if side == 4 {
4125 3
4126 } else {
4127 0
4128 }
4129 }
4130
4131 /// One bit of a table, counting from the low end of its first byte.
4132 fn bit(table: &[u8], index: usize) -> bool {
4133 (table[index / 8] >> (index % 8)) & 1 != 0
4134 }
4135}
4136
4137/// What one symbol costs against a CDF, in bits.
4138/// Whether local warped motion is on: the `WARPED_CAUSAL` candidate in the
4139/// search, the frame header's `allow_warped_motion` and the sequence's
4140/// `enable_warped_motion`, all three together. ON by default since
4141/// lane-av1rejudge re-measured it at [`LAMBDA_SCALE`] 0.05 (the table at
4142/// [`warp_prediction`]); `EC_AV1_WARP=0` turns the tool -- and the two header
4143/// bits -- back off for an A/B on one build.
4144pub(crate) fn warp_on() -> bool {
4145 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
4146 crate::envflags::var("EC_AV1_WARP").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
4147 });
4148 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::WARP))
4149}
4150
4151/// The smallest LEAF an OBMC candidate is offered for, so the census can
4152/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
4153/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
4154/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
4155///
4156/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
4157/// (12 frames, four quantizers, the standing keep table):
4158///
4159/// | min side | film 1080p | film 2160p | screen |
4160/// |---|---|---|---|
4161/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
4162/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
4163/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
4164/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
4165///
4166/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
4167/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
4168/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
4169/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
4170/// that wins the local RD on five blocks in six and loses ladder bytes is
4171/// the `local-RD-on-references` class again, not a missing footprint.
4172///
4173/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
4174/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
4175/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
4176/// loss on the 1080p film became a 0.3-point win and the other two rows went
4177/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
4178/// of the "local win, ladder loss" it was charged with was the rate weight.
4179/// It still does not meet the keep rule (two down, one flat, both columns).
4180/// The tool stays OFF by default; the upgrade path is the price, not the size
4181/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
4182/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
4183/// 1080p film up, i.e. the same disagreement between the two gates).
4184///
4185/// RE-JUDGED again on lane-av1rejudge against the defaults this lane kept
4186/// (local warp on, [`LEAF_SECOND_NEW_MARGIN`] 1.2 -- native +16.2/-1.1,
4187/// +46.6/+18.8, +51.3/-14.4): OBMC at min side 8 on top of that base reads
4188/// +16.2/-1.0, +46.6/+18.8, +51.3/-14.4, i.e. three rows flat and the 1080p
4189/// rav1e column 0.1 WORSE, so the tool buys nothing once the second-reference
4190/// margin is loosened. On warp alone it looked like a keep (+16.3/-0.9 at
4191/// min 8, +16.6/-0.7 at min 16 against warp's +16.7/-0.5) -- that gain and
4192/// the margin's gain are the same bytes. It stays OFF.
4193///
4194/// RE-MEASURED on lane-obmc3 (2026-09-08) on the REAL film rows -- every
4195/// judgement above was taken when the gate's "film" rows were the `testsrc2`
4196/// COLOUR BARS fixtures (class `gate film rows are colour bars`), so this is
4197/// the first OBMC measurement on film. BD vs libaom / vs rav1e, 12 pictures,
4198/// the standing native keep table (`bd_rate_screen_native`):
4199///
4200/// | arm | film A | film B | screen | OBMC fire A/B |
4201/// |---|---|---|---|---|
4202/// | off (control) | +21.7 / -4.4 | +26.9 / -0.6 | +20.1 / -30.4 | 0% / 0% |
4203/// | min side 8 | +21.7 / -4.3 | +27.2 / -0.3 | +20.0 / -30.4 | 15.5% / 9.7% |
4204/// | min side 16 | +21.5 / -4.5 | +27.6 / +0.1 | +20.1 / -30.4 | 10.0% / 6.9% |
4205///
4206/// and on the LONG-GOP gate (`bd_rate_film_long_gop`, 48 pictures, film B
4207/// only), where the anchors' non-skip area is the known gap:
4208///
4209/// | arm | film B long GOP | wall ours |
4210/// |---|---|---|
4211/// | off (control) | +89.8 / +9.1 | 477.5s |
4212/// | min side 8 | +89.6 / +9.0 | 514.1s |
4213///
4214/// The two gates disagree in SIGN on film B -- 0.3/0.3 worse over 12
4215/// pictures, 0.2/0.1 better over 48 -- and film A moves 0.2/0.1 the good way
4216/// only at min side 16, which is exactly where film B loses 0.7 on both
4217/// columns. Nothing here meets the keep rule (both films down on both
4218/// columns, or one down >=0.5 with the other flat), and the long-GOP gain
4219/// costs +7.7% wall. OBMC stays OFF at every preset.
4220fn obmc_min_side() -> usize {
4221 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
4222 *N.get_or_init(|| {
4223 std::env::var("EC_AV1_OBMC_MIN")
4224 .ok()
4225 .and_then(|v| v.parse().ok())
4226 .unwrap_or(8)
4227 })
4228}
4229
4230/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
4231/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
4232/// same frame-CDF price the coefficients of a non-screen frame are estimated
4233/// with, not the static default table.
4234/// The same price for whichever alphabet the writer will really use for this
4235/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
4236/// (`allow_warped_motion` and at least one warp sample), otherwise the
4237/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
4238/// search pay it, so the alphabet cancels out of a comparison and only its
4239/// per-value spread decides.
4240fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
4241 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
4242 return 0.0;
4243 };
4244 match warp_alphabet {
4245 true => crate::tile::motion_mode_symbol_bits(row, motion),
4246 false => crate::tile::obmc_symbol_bits(row, motion == 1),
4247 }
4248}
4249
4250/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
4251/// candidate, the header's `allow_warped_motion` and the sequence's
4252/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
4253/// native keep table, against the same build with the knob off:
4254///
4255/// | clip | warp on | off |
4256/// |---|---|---|
4257/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
4258/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
4259/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
4260///
4261/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
4262/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
4263/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
4264/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
4265/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
4266/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
4267/// this is a measured loss, not an inert knob. Same shape as the OBMC
4268/// candidate above it (`obmc_min_side`): a local RD win that does not convert
4269/// into ladder bytes.
4270///
4271/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
4272/// because a tool whose gain is local and whose cost is the rate it adds is
4273/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
4274///
4275/// | clip | warp on | off (both at lambda 0.05) |
4276/// |---|---|---|
4277/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
4278/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
4279/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
4280///
4281/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
4282/// column inside 0.1 everywhere -- which reads as a keep rather than the
4283/// 0.7/0.9 loss it was.
4284///
4285/// KEPT ON BY DEFAULT on lane-av1rejudge, which reproduced that table
4286/// exactly (base +17.0/-0.3, +47.0/+19.2, +51.6/-14.2; warp +16.7/-0.5,
4287/// +47.0/+19.1, +51.3/-14.3 -- two rows down on both columns, one flat) and
4288/// ran the conformance shape the lambda lane deferred: every warp stream
4289/// decodes three-way exact (our decoder and ffmpeg, `EC_COMP_MISMATCH=1`
4290/// clean), the native gate runs clean under `EC_AV1_TILES=2:2` (warp inside
4291/// a 16-tile frame, sample walk and all), and tile bytes still do not depend
4292/// on the thread count. The tool fires on 5.4% / 3.3% / 3.3% of the blocks
4293/// that code a motion_mode symbol. `EC_AV1_WARP=0` ([`warp_on`]) turns it,
4294/// `allow_warped_motion` and `enable_warped_motion` back off together.
4295///
4296/// The WARPED_CAUSAL prediction of one square single-reference block: the
4297/// decoder's own warp-sample walk (`decode::find_samples` +
4298/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
4299/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
4300/// grid -- never a second implementation of any of the three. `None` when the
4301/// block would code no motion_mode symbol at all, when it has no warp sample
4302/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
4303/// or when the projection is not filter-representable (the decoder would then
4304/// predict translationally, so the mode is pure cost).
4305#[allow(clippy::too_many_arguments)]
4306fn warp_prediction(
4307 grid: &MiGrid,
4308 (mi_row, mi_col): (usize, usize),
4309 (mi_rows, mi_cols): (usize, usize),
4310 (x, y): (usize, usize),
4311 side: usize,
4312 mv: (i32, i32),
4313 ref_frame: i8,
4314 ref_planes: [(&[u16], usize, usize, usize); 3],
4315 fctx: &crate::decode::FrameCtx,
4316) -> Option<[Vec<u8>; 3]> {
4317 let n4 = side / 4;
4318 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
4319 return None;
4320 }
4321 let mut samples = crate::decode::find_samples(
4322 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
4323 );
4324 if samples.is_empty() {
4325 return None;
4326 }
4327 if samples.len() > 1 {
4328 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
4329 }
4330 let params = crate::warp::find_projection(
4331 &samples,
4332 side as i32,
4333 side as i32,
4334 mv.1,
4335 mv.0,
4336 mi_row as i32,
4337 mi_col as i32,
4338 )?;
4339 let mut pred = [
4340 vec![0u16; side * side],
4341 vec![0u16; side * side / 4],
4342 vec![0u16; side * side / 4],
4343 ];
4344 // The translational prediction first, exactly as the decoder builds it,
4345 // then the affine one over the planes whose OWN block is at least 8x8
4346 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
4347 // 4x4 chroma stays translational).
4348 for (i, r) in ref_planes.into_iter().enumerate() {
4349 let luma_plane = i == 0;
4350 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
4351 let s = if luma_plane { side } else { side / 2 };
4352 mc::predict(
4353 r.0,
4354 r.1,
4355 r.2,
4356 r.3,
4357 mv_to_q4(px, mv.1, luma_plane),
4358 mv_to_q4(py, mv.0, luma_plane),
4359 s,
4360 s,
4361 &mut pred[i],
4362 fctx,
4363 );
4364 if crate::decode::warp_plane_allowed(s, s) {
4365 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
4366 crate::warp::warp_affine(
4367 &params,
4368 r.0,
4369 r.2 as i32,
4370 r.3 as i32,
4371 r.1 as i32,
4372 &mut pred[i],
4373 px as i32,
4374 py as i32,
4375 cside,
4376 cside,
4377 cside,
4378 sub,
4379 sub,
4380 fctx,
4381 );
4382 }
4383 }
4384 let [py_buf, pu_buf, pv_buf] = pred;
4385 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
4386 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
4387}
4388
4389/// What tile.rs' `write_compound_ref_frames` pays for the pair
4390/// `(ref0, ref1)`, symbol for symbol, each at the context its own
4391/// `single_ref_p*_ctx`/`uni_comp_ref_p1_ctx`/`comp_reference_type_ctx`
4392/// derives from the block's above/left neighbours -- plus the `comp_mode`
4393/// symbol itself at `reference_mode_ctx`.
4394///
4395/// Before lane-ctx this was four constants at CDF row 0 that assumed the pair
4396/// was LAST+GOLDEN or LAST+ALTREF: `comp_bwdref[0][0] = 1` prices a BWDREF or
4397/// ALTREF2 partner as ALTREF and drops its `p6` symbol entirely, and the
4398/// `uni_comp_ref` leaves price a LAST+LAST2 pair as LAST+GOLDEN.
4399pub(crate) fn compound_ref_bits(
4400 (ref0, ref1): (i8, i8),
4401 stack: &crate::mvstack::MvStack,
4402) -> f64 {
4403 use crate::mvstack::{
4404 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4405 comp_reference_type_ctx, is_uni_comp_ref, single_ref_p1_ctx, single_ref_p2_ctx,
4406 single_ref_p3_ctx, single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
4407 uni_comp_ref_p1_ctx,
4408 };
4409 let (a, a1) = stack.above_refs;
4410 let (l, l1) = stack.left_refs;
4411 let unidir = is_uni_comp_ref(ref0, ref1);
4412 let comp_mode = symbol_bits(
4413 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4414 1,
4415 );
4416 let ref_type = symbol_bits(
4417 &cdf::COMP_REF_TYPE[comp_reference_type_ctx(stack.above_nbr, stack.left_nbr)],
4418 usize::from(!unidir),
4419 );
4420 if unidir {
4421 let both_backward = (ref0, ref1) == (BWDREF_FRAME, ALTREF_FRAME);
4422 let p0 = symbol_bits(
4423 &cdf::UNI_COMP_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4424 usize::from(both_backward),
4425 );
4426 if both_backward {
4427 return comp_mode + ref_type + p0;
4428 }
4429 let past_last2 = ref1 != LAST2_FRAME;
4430 let p1 = symbol_bits(
4431 &cdf::UNI_COMP_REF[uni_comp_ref_p1_ctx(a, a1, l, l1)][1],
4432 usize::from(past_last2),
4433 );
4434 let p2 = if past_last2 {
4435 symbol_bits(
4436 &cdf::UNI_COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4437 usize::from(ref1 == GOLDEN_FRAME),
4438 )
4439 } else {
4440 0.0
4441 };
4442 return comp_mode + ref_type + p0 + p1 + p2;
4443 }
4444 let far = ref0 == LAST3_FRAME || ref0 == GOLDEN_FRAME;
4445 let fwd = symbol_bits(
4446 &cdf::COMP_REF[single_ref_p3_ctx(a, a1, l, l1)][0],
4447 usize::from(far),
4448 ) + if far {
4449 symbol_bits(
4450 &cdf::COMP_REF[single_ref_p5_ctx(a, a1, l, l1)][2],
4451 usize::from(ref0 == GOLDEN_FRAME),
4452 )
4453 } else {
4454 symbol_bits(
4455 &cdf::COMP_REF[single_ref_p4_ctx(a, a1, l, l1)][1],
4456 usize::from(ref0 == LAST2_FRAME),
4457 )
4458 };
4459 let is_altref = ref1 == ALTREF_FRAME;
4460 let bwd = symbol_bits(
4461 &cdf::COMP_BWDREF[single_ref_p2_ctx(a, a1, l, l1)][0],
4462 usize::from(is_altref),
4463 ) + if is_altref {
4464 0.0
4465 } else {
4466 symbol_bits(
4467 &cdf::COMP_BWDREF[single_ref_p6_ctx(a, a1, l, l1)][1],
4468 usize::from(ref1 == ALTREF2_FRAME),
4469 )
4470 };
4471 comp_mode + ref_type + fwd + bwd
4472}
4473
4474/// What the `skip` symbol costs at the context tile.rs really codes it with
4475/// (`above_skip[mi_c] + left_skip[mi_r]`, the two cells the MV stack now
4476/// carries) instead of row 0 -- the pricer's skip-versus-residual margin is
4477/// exactly the difference between this symbol's two values, so the row it is
4478/// read from moves that decision (class pricer-context-zero, lane-ctx).
4479pub(crate) fn skip_bits_at(stack: &crate::mvstack::MvStack, skip: bool) -> f64 {
4480 let ctx = usize::from(stack.above_skip) + usize::from(stack.left_skip);
4481 symbol_bits(&cdf::SKIP[ctx], usize::from(skip))
4482}
4483
4484/// What the `is_inter` symbol costs at tile.rs' own `intra_inter_ctx` -- the
4485/// neighbours' intra/inter state, with an out-of-tile side contributing
4486/// nothing, off the same two cells (lane-ctx).
4487pub(crate) fn intra_inter_bits_at(stack: &crate::mvstack::MvStack, inter: bool) -> f64 {
4488 let ctx = crate::tile::intra_inter_ctx(
4489 stack.above_nbr.is_some(),
4490 stack.left_nbr.is_some(),
4491 stack.above_nbr.is_some_and(|n| n.is_inter),
4492 stack.left_nbr.is_some_and(|n| n.is_inter),
4493 );
4494 symbol_bits(&cdf::INTRA_INTER[ctx], usize::from(inter))
4495}
4496
4497/// The `comp_mode = 0` symbol tile.rs' `write_comp_mode` codes ahead of a
4498/// SINGLE-reference block's reference syntax, at `reference_mode_ctx`'s own
4499/// context -- zero on a frame that carries no `reference_select` bit, where
4500/// the writer codes no symbol at all.
4501fn comp_mode_single_bits(stack: &crate::mvstack::MvStack) -> f64 {
4502 if !reference_select() {
4503 return 0.0;
4504 }
4505 symbol_bits(
4506 &cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(stack.above_nbr, stack.left_nbr)],
4507 0,
4508 )
4509}
4510
4511/// What tile.rs' `write_single_ref` pays for `ref_frame`, symbol for symbol,
4512/// each at the context that symbol's own `single_ref_p*_ctx` derives from the
4513/// block's above/left neighbours -- plus the `comp_mode = 0` symbol
4514/// `write_comp_mode` codes ahead of it on a `reference_select` frame.
4515/// LAST is p1=0,p3=0,p4=0,
4516/// LAST2 p1=0,p3=0,p4=1, LAST3 p1=0,p3=1,p5=0, GOLDEN p1=0,p3=1,p5=1,
4517/// BWDREF p1=1,p2=0,p6=0, ALTREF2 p1=1,p2=0,p6=1 and ALTREF p1=1,p2=1.
4518/// Before lane-pricer every BACKWARD reference was priced as LAST -- three
4519/// symbols off the wrong CDFs -- which is what made the search believe an
4520/// ALTREF block cost the same syntax as a LAST one. The `comp_mode` term is
4521/// lane-ctx2's: a compound candidate paid `comp_mode = 1` while a single one
4522/// paid nothing at all, so compound was overcharged by the whole symbol.
4523pub(crate) fn single_ref_bits(ref_frame: i8, stack: &crate::mvstack::MvStack) -> f64 {
4524 use crate::mvstack::{
4525 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
4526 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
4527 single_ref_p5_ctx, single_ref_p6_ctx,
4528 };
4529 let (a, a1) = stack.above_refs;
4530 let (l, l1) = stack.left_refs;
4531 let comp_mode = comp_mode_single_bits(stack);
4532 let backward = ref_frame >= BWDREF_FRAME;
4533 let p1 = symbol_bits(
4534 &cdf::SINGLE_REF[single_ref_p1_ctx(a, a1, l, l1)][0],
4535 usize::from(backward),
4536 );
4537 if backward {
4538 let is_altref = ref_frame == ALTREF_FRAME;
4539 let p2 = symbol_bits(
4540 &cdf::SINGLE_REF[single_ref_p2_ctx(a, a1, l, l1)][1],
4541 usize::from(is_altref),
4542 );
4543 return comp_mode
4544 + p1
4545 + p2
4546 + if is_altref {
4547 0.0
4548 } else {
4549 symbol_bits(
4550 &cdf::SINGLE_REF[single_ref_p6_ctx(a, a1, l, l1)][5],
4551 usize::from(ref_frame == ALTREF2_FRAME),
4552 )
4553 };
4554 }
4555 let far = ref_frame == LAST3_FRAME || ref_frame == GOLDEN_FRAME;
4556 comp_mode + p1 + symbol_bits(
4557 &cdf::SINGLE_REF[single_ref_p3_ctx(a, a1, l, l1)][2],
4558 usize::from(far),
4559 ) + if far {
4560 symbol_bits(
4561 &cdf::SINGLE_REF[single_ref_p5_ctx(a, a1, l, l1)][4],
4562 usize::from(ref_frame == GOLDEN_FRAME),
4563 )
4564 } else {
4565 symbol_bits(
4566 &cdf::SINGLE_REF[single_ref_p4_ctx(a, a1, l, l1)][3],
4567 usize::from(ref_frame == LAST2_FRAME),
4568 )
4569 }
4570}
4571
4572pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
4573 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
4574 let width = cdf[symbol] - low;
4575 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
4576 // 32769 prices a symbol can carry; the `log2` behind each is computed
4577 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
4578 // profile -- this function is called for every symbol of every candidate
4579 // the RD search prices). Each entry is exactly the expression this used
4580 // to evaluate, so every price is bit-identical.
4581 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
4582 PRICES.get_or_init(|| {
4583 (0..=32768u32)
4584 .map(|w| -(f64::from(w) / 32768.0).log2())
4585 .collect()
4586 })[usize::from(width)]
4587}
4588
4589/// What the tile writer spends to say a block is coded in each of the thirteen
4590/// modes, given the modes of the blocks above it and to its left: the luma mode
4591/// symbol against the CDF those two neighbours pick, the angle delta a
4592/// directional mode carries, and the chroma mode symbol, whose CDF the luma
4593/// mode itself indexes.
4594///
4595/// Without this the search is blind to what a mode costs to name, which is not
4596/// a rounding error: a directional mode on a picture that does not run that way
4597/// is a rate loss the squared error never sees.
4598/// Codes one square of the picture as a single block: searches the luma mode,
4599/// codes both chroma planes DC, and hands back the block and what it cost --
4600/// squared error plus lambda times the bits its symbols spend.
4601/// How many halvings of a `side`-square block's transform the `tx_depth`
4602/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
4603/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
4604fn max_tx_depth(side: usize) -> usize {
4605 match side {
4606 8 => 1,
4607 16 | 32 => 2,
4608 _ => 0,
4609 }
4610}
4611
4612/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
4613/// Priced at context row 0 -- the writer picks the real row from its
4614/// neighbours' transform sizes, which the search has no view of; the term is
4615/// the same for every depth of one block either way, so it only shifts the
4616/// depth-0-versus-split margin, never the ordering between two splits.
4617fn tx_depth_bits(side: usize, depth: usize) -> f64 {
4618 match side {
4619 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
4620 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
4621 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
4622 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
4623 }
4624}
4625
4626/// lane-split: a multiplier on the RATE term of the transform-SPLIT trial
4627/// only -- the intra `tx_depth` depth>0 candidates in [`code_square`] and the
4628/// inter var-tx depth-1 trial in [`commit_inter_luma`]. `1.0` is the control
4629/// (the mode search's own weight); below 1 the split trial is charged less
4630/// for its bits and fires more often.
4631///
4632/// The knob the class `rd-rate-term-calibration` asks for: lane-txd made the
4633/// `tx_depth` SYMBOL price correct and every film row got worse, because the
4634/// correct row is a one-sided push away from splitting (depth 0 up to 1.5
4635/// bits cheaper at ctx 2, which is 66% of an inter frame's intra blocks) --
4636/// so what is mis-calibrated is the weight the split's rate is judged under,
4637/// not the price. `EC_AV1_SPLIT_LAMBDA`.
4638pub(crate) fn split_lambda_mult() -> f64 {
4639 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4640 crate::envflags::var("EC_AV1_SPLIT_LAMBDA")
4641 .ok()
4642 .and_then(|v| v.parse().ok())
4643 .unwrap_or(SPLIT_LAMBDA)
4644 });
4645 *M
4646}
4647
4648/// The shipped value of [`split_lambda_mult`]. See lanes/split.report.md for
4649/// the sweep that chose it.
4650const SPLIT_LAMBDA: f64 = 1.0;
4651
4652/// lane-split census (`EC_AV1_SPLIT_CENSUS=1`): the split decision itself,
4653/// bucketed by site (0 = intra `tx_depth`, 1 = inter var-tx), frame type
4654/// (0 = key, 1 = inter) and block side (8/16/32/64). Ten counters per bucket:
4655/// trials offered, trials the split won, then the (rate, distortion) of the
4656/// split and flat arms summed apart for the split-won and flat-won trials --
4657/// rate scaled by 64 into an integer counter, as [`TXRD_STATS`] is.
4658static SPLIT_CENSUS: [std::sync::atomic::AtomicU64; 160] =
4659 [const { std::sync::atomic::AtomicU64::new(0) }; 160];
4660
4661/// Whether [`SPLIT_CENSUS`] is armed, read once.
4662pub(crate) fn split_census_on() -> bool {
4663 static ON: std::sync::LazyLock<bool> =
4664 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_SPLIT_CENSUS"));
4665 *ON
4666}
4667
4668/// Where one (site, frame type, block side) bucket starts in [`SPLIT_CENSUS`].
4669/// Sides below 8 and above 64 fold into the end rows, which no caller offers.
4670fn split_census_base(site: usize, key: bool, side: usize) -> usize {
4671 let side_idx = (side.trailing_zeros() as usize).saturating_sub(3).min(3);
4672 ((site * 2 + usize::from(!key)) * 4 + side_idx) * 10
4673}
4674
4675/// Records one split trial into [`SPLIT_CENSUS`]. `split` and `flat` are each
4676/// `(rate in bits, distortion as squared error)`.
4677fn split_census(
4678 site: usize,
4679 key: bool,
4680 side: usize,
4681 split_won: bool,
4682 split: (f64, f64),
4683 flat: (f64, f64),
4684) {
4685 use std::sync::atomic::Ordering::Relaxed;
4686 let base = split_census_base(site, key, side);
4687 let add = |i: usize, v: u64| {
4688 SPLIT_CENSUS[base + i].fetch_add(v, Relaxed);
4689 };
4690 add(0, 1);
4691 let off = if split_won {
4692 add(1, 1);
4693 2
4694 } else {
4695 6
4696 };
4697 let (win, lose) = if split_won { (split, flat) } else { (flat, split) };
4698 add(off, (win.0 * 64.0).max(0.0) as u64);
4699 add(off + 1, win.1.max(0.0) as u64);
4700 add(off + 2, (lose.0 * 64.0).max(0.0) as u64);
4701 add(off + 3, lose.1.max(0.0) as u64);
4702}
4703
4704/// Prints [`SPLIT_CENSUS`] to stderr when `EC_AV1_SPLIT_CENSUS=1`. Called at
4705/// the end of every `Av1Encoder::encode_frames` call and NOT reset, so the
4706/// last table a run prints is the whole encode's total (there is no flush
4707/// hook the encoder API guarantees to reach).
4708pub(crate) fn dump_split_census() {
4709 use std::sync::atomic::Ordering::Relaxed;
4710 eprintln!(
4711 "SPLITCENSUS site frame side offered split share% \
4712 win_rate win_dist lose_rate lose_dist"
4713 );
4714 for site in 0..2 {
4715 for key in [true, false] {
4716 for side_idx in 0..4 {
4717 let base = split_census_base(site, key, 8 << side_idx);
4718 let v: [u64; 10] = std::array::from_fn(|i| SPLIT_CENSUS[base + i].load(Relaxed));
4719 if v[0] == 0 {
4720 continue;
4721 }
4722 let (n, s) = (v[0] as f64, v[1] as f64);
4723 // Winner terms live at 2,3 (split won) and 6,7 (flat won),
4724 // loser terms at 4,5 and 8,9 -- so each mean is one sum over
4725 // all `n` trials, not a mean of two means.
4726 eprintln!(
4727 "SPLITCENSUS {} {} {:>3} {:>7} {:>7} {:>5.1} \
4728 {:>9.2} {:>9.0} {:>9.2} {:>9.0}",
4729 if site == 0 { "intra" } else { "inter" },
4730 if key { "key " } else { "inter" },
4731 8 << side_idx,
4732 v[0],
4733 v[1],
4734 100.0 * s / n,
4735 (v[2] + v[6]) as f64 / n / 64.0,
4736 (v[3] + v[7]) as f64 / n,
4737 (v[4] + v[8]) as f64 / n / 64.0,
4738 (v[5] + v[9]) as f64 / n,
4739 );
4740 }
4741 }
4742 }
4743}
4744
4745/// lane-newmv: a multiplier on the mv RATE term of the BLOCK-level inter
4746/// decision only -- the `NEWMV` candidate's own mv residual + DRL bits, not
4747/// its mode/reference syntax and not the search's own cost function
4748/// ([`crate::motion`]'s `EC_AV1_MV_SEARCH_LAMBDA` is that one). `1.0` is the
4749/// control; below 1 a coded vector is charged less and `NEWMV` wins more
4750/// blocks. `EC_AV1_MV_LAMBDA`, class `rd-rate-term-calibration`.
4751pub(crate) fn mv_lambda_mult() -> f64 {
4752 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4753 crate::envflags::var("EC_AV1_MV_LAMBDA")
4754 .ok()
4755 .and_then(|v| v.parse().ok())
4756 .unwrap_or(MV_LAMBDA)
4757 });
4758 *M
4759}
4760
4761/// The shipped value of [`mv_lambda_mult`]. See lanes/newmv.report.md.
4762const MV_LAMBDA: f64 = 1.0;
4763
4764/// What a `NEWMV` candidate is charged ON TOP of its own priced mv syntax
4765/// bits, `(EC_AV1_MV_LAMBDA - 1) * mv_bits` (added to the candidate's bits,
4766/// which the RD cost multiplies by lambda). Zero at the default weight.
4767fn mv_rate_surcharge(mv_bits: f64) -> f64 {
4768 (mv_lambda_mult() - 1.0) * mv_bits
4769}
4770
4771/// lane-newmv census (`EC_AV1_NEWMV_CENSUS=1`): the block-level `NEWMV`
4772/// decision, bucketed by block side (8/16/32/64). Eight counters per bucket:
4773/// 0 blocks that ran a `LAST` motion search, 1 of those whose vector the
4774/// writer could name (offered to RD), 2 blocks `NEWMV` won, 3 the summed RD
4775/// cost it won by, 4 the summed cost it lost by, 5 the summed
4776/// `|mv - nearest_mv|` (1/8-pel units, both axes), 6 blocks whose searched
4777/// vector IS the stack's `NEARESTMV`, 7 the summed mv syntax bits (x64, as
4778/// [`SPLIT_CENSUS`]'s rate terms are). Four globals follow at 32: extra-
4779/// reference searches offered/skipped by [`EXTRA_NEW_SKIP_MARGIN`], leaf
4780/// second-reference searches offered/skipped by [`LEAF_SECOND_NEW_MARGIN`].
4781static NEWMV_CENSUS: [std::sync::atomic::AtomicU64; 36] =
4782 [const { std::sync::atomic::AtomicU64::new(0) }; 36];
4783
4784/// Whether [`NEWMV_CENSUS`] is armed, read once.
4785pub(crate) fn newmv_census_on() -> bool {
4786 static ON: std::sync::LazyLock<bool> =
4787 std::sync::LazyLock::new(|| crate::envflags::env_flag!("EC_AV1_NEWMV_CENSUS"));
4788 *ON
4789}
4790
4791/// Bumps one of [`NEWMV_CENSUS`]'s four global counters (32..36).
4792fn newmv_census_global(i: usize) {
4793 if newmv_census_on() {
4794 NEWMV_CENSUS[32 + i].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4795 }
4796}
4797
4798/// Records one block's `NEWMV` decision into [`NEWMV_CENSUS`]. `other_cost`
4799/// is the best cost the block had WITHOUT the `NEWMV` candidate (its
4800/// `NEAREST`/`NEAR`/`GLOBAL`/intra winner), `new_cost` the `NEWMV`
4801/// candidate's own; both `f64::INFINITY` is a block that offered neither.
4802fn newmv_census_block(
4803 side: usize,
4804 offered: bool,
4805 new_cost: f64,
4806 other_cost: f64,
4807 mv: (i32, i32),
4808 nearest: (i32, i32),
4809 mv_bits: f64,
4810) {
4811 if !newmv_census_on() {
4812 return;
4813 }
4814 use std::sync::atomic::Ordering::Relaxed;
4815 let base = (side.trailing_zeros() as usize).saturating_sub(3).min(3) * 8;
4816 let add = |i: usize, v: u64| {
4817 NEWMV_CENSUS[base + i].fetch_add(v, Relaxed);
4818 };
4819 add(0, 1);
4820 if !offered {
4821 return;
4822 }
4823 add(1, 1);
4824 if new_cost < other_cost {
4825 add(2, 1);
4826 add(3, (other_cost - new_cost).max(0.0) as u64);
4827 } else {
4828 add(4, (new_cost - other_cost).max(0.0) as u64);
4829 }
4830 add(5, ((mv.0 - nearest.0).unsigned_abs() + (mv.1 - nearest.1).unsigned_abs()) as u64);
4831 if mv == nearest {
4832 add(6, 1);
4833 }
4834 add(7, (mv_bits * 64.0).max(0.0) as u64);
4835}
4836
4837/// Prints [`NEWMV_CENSUS`] to stderr when `EC_AV1_NEWMV_CENSUS=1`, on the
4838/// same guard [`dump_split_census`] rides (cumulative, so the last table a
4839/// run prints is the whole encode's).
4840pub(crate) fn dump_newmv_census() {
4841 use std::sync::atomic::Ordering::Relaxed;
4842 eprintln!(
4843 "NEWMVCENSUS side searched offered won won% win_margin lose_margin \
4844 mv_dist_q3 mv==nearest% mv_bits"
4845 );
4846 for side_idx in 0..4 {
4847 let base = side_idx * 8;
4848 let v: [u64; 8] = std::array::from_fn(|i| NEWMV_CENSUS[base + i].load(Relaxed));
4849 if v[0] == 0 {
4850 continue;
4851 }
4852 let off = v[1].max(1) as f64;
4853 eprintln!(
4854 "NEWMVCENSUS {:>3} {:>8} {:>8} {:>7} {:>5.1} {:>10.0} {:>11.0} {:>10.2} {:>12.1} {:>7.2}",
4855 8 << side_idx,
4856 v[0],
4857 v[1],
4858 v[2],
4859 100.0 * v[2] as f64 / off,
4860 v[3] as f64 / v[2].max(1) as f64,
4861 v[4] as f64 / (v[1] - v[2]).max(1) as f64,
4862 v[5] as f64 / off,
4863 100.0 * v[6] as f64 / off,
4864 v[7] as f64 / off / 64.0,
4865 );
4866 }
4867 // lane-hpmv: how many mv components this encode coded an eighth-pel bit
4868 // for, and how many of those named a vector no non-hp frame can code.
4869 let (hp_all, hp_eighth) = crate::tile::hp_symbols();
4870 eprintln!(
4871 "NEWMVCENSUS hp symbols {hp_all}, of them eighth-pel {hp_eighth} ({:.1}%)",
4872 100.0 * hp_eighth as f64 / hp_all.max(1) as f64,
4873 );
4874 let g: [u64; 4] = std::array::from_fn(|i| NEWMV_CENSUS[32 + i].load(Relaxed));
4875 eprintln!(
4876 "NEWMVCENSUS pre-RD margin skips: extra-reference {}/{} ({:.1}%), \
4877 leaf second reference {}/{} ({:.1}%)",
4878 g[1],
4879 g[0],
4880 100.0 * g[1] as f64 / g[0].max(1) as f64,
4881 g[3],
4882 g[2],
4883 100.0 * g[3] as f64 / g[2].max(1) as f64,
4884 );
4885 let [calls, evals, _subpel, rounds, near_pred, unmoved, widest, widest_moves] =
4886 crate::motion::take_census();
4887 let per = |n: u64| n as f64 / calls.max(1) as f64;
4888 eprintln!(
4889 "NEWMVCENSUS search: {calls} calls, {:.1} evals/call, {:.2} integer rounds/call; \
4890 winner within +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%, \
4891 moved at the WIDEST step {:.1}% of calls ({:.2} such moves/call)",
4892 per(evals),
4893 per(rounds),
4894 100.0 * near_pred as f64 / calls.max(1) as f64,
4895 100.0 * unmoved as f64 / calls.max(1) as f64,
4896 100.0 * widest as f64 / calls.max(1) as f64,
4897 per(widest_moves),
4898 );
4899}
4900
4901/// [`TX_TYPE_HITS`] for the INTER luma units (lane-txset2), counted apart so
4902/// the intra witness's fire count stays its own.
4903pub(crate) static INTER_TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
4904 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
4905
4906/// lane-txrd: a multiplier on the rate term of the TRANSFORM-TYPE decision
4907/// only (`EC_AV1_TXRD_LAMBDA`, default 1.0 = the mode search's own weight).
4908/// `0` compares types on reconstruction error alone, which is what separates
4909/// a rate-term calibration (class `rd-rate-term-calibration`) from a
4910/// distortion the trial mis-measures.
4911pub(crate) fn tx_type_lambda_mult() -> f64 {
4912 static M: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
4913 crate::envflags::var("EC_AV1_TXRD_LAMBDA")
4914 .ok()
4915 .and_then(|v| v.parse().ok())
4916 .unwrap_or(1.0)
4917 });
4918 *M
4919}
4920
4921/// lane-txi: what a non-`DCT_DCT` transform type is charged ON TOP of its own
4922/// priced bits -- `(EC_AV1_TXRD_LAMBDA - 1) * lambda * bits`, zero at the
4923/// default weight of 1 and for `DCT_DCT` itself. The instrument the film
4924/// question needs: at weight 1 the five-type intra search spends 1.2% more
4925/// bytes for 0.04 dB on both film rows, so what it under-charges is the rate
4926/// of the type it picks.
4927pub(crate) fn non_dct_surcharge(lambda: f64, tx_type: TxType, bits: f64) -> f64 {
4928 if tx_type == TxType::DctDct {
4929 0.0
4930 } else {
4931 lambda * (tx_type_lambda_mult() - 1.0) * bits
4932 }
4933}
4934
4935/// lane-txrd instrument: over the FLAT inter luma decision, the summed
4936/// reconstruction error and priced bits of the type the search chose against
4937/// the `DCT_DCT` trial it was compared with. Both are `* 64` so they fit an
4938/// integer counter. `EC_AV1_TXRD_CENSUS`.
4939pub(crate) static TXRD_STATS: [std::sync::atomic::AtomicU64; 7] = [
4940 std::sync::atomic::AtomicU64::new(0),
4941 std::sync::atomic::AtomicU64::new(0),
4942 std::sync::atomic::AtomicU64::new(0),
4943 std::sync::atomic::AtomicU64::new(0),
4944 std::sync::atomic::AtomicU64::new(0),
4945 std::sync::atomic::AtomicU64::new(0),
4946 std::sync::atomic::AtomicU64::new(0),
4947];
4948
4949/// Reads [`TXRD_STATS`] and zeroes it. Only the gate reads it, so the lib
4950/// build would warn `dead_code` (class from lane-txset2's `coeff_bits`).
4951#[cfg(test)]
4952pub(crate) fn take_txrd_stats() -> [u64; 7] {
4953 std::array::from_fn(|i| TXRD_STATS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
4954}
4955
4956/// Reads [`INTER_TX_TYPE_HITS`] and zeroes it.
4957#[cfg(test)]
4958pub(crate) fn take_inter_tx_type_hits() -> [usize; 16] {
4959 std::array::from_fn(|t| INTER_TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
4960}
4961
4962/// How many luma transform units resolved to each [`TxType`], indexed by the
4963/// enum's own discriminant (lane-txset): the fire count a witness asserts on,
4964/// and the instrument that says which types the search actually reaches.
4965pub(crate) static TX_TYPE_HITS: [std::sync::atomic::AtomicUsize; 16] =
4966 [const { std::sync::atomic::AtomicUsize::new(0) }; 16];
4967
4968/// Reads [`TX_TYPE_HITS`] and zeroes it, so a gate or a test attributes the
4969/// counts to its own encode.
4970#[cfg(test)]
4971pub(crate) fn take_tx_type_hits() -> [usize; 16] {
4972 std::array::from_fn(|t| TX_TYPE_HITS[t].swap(0, std::sync::atomic::Ordering::Relaxed))
4973}
4974
4975/// How many blocks resolved to each `tx_depth`, the fire count that says
4976/// whether the depth search below reaches its candidates at all.
4977static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
4978 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
4979
4980/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
4981/// to its own encode.
4982#[cfg(test)]
4983pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
4984 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
4985}
4986
4987/// How many inter blocks resolved to each var-tx depth (0 = one transform
4988/// over the whole block, 1 = its four halves), the fire count a gate prints
4989/// to see the split search reach its candidates at all. Indexed
4990/// `(block is 32x32) * 4 + (block is compound) * 2 + depth`, so one census
4991/// says which of the four block classes the split reaches -- the 32x32 root
4992/// and the compound blocks are this lane's two new ones.
4993static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 8] =
4994 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
4995
4996/// Whether a 32x32 inter winner searches its own var-tx depth (the four
4997/// 16x16 units against the flat transform) instead of coding depth 0 blind.
4998/// ON by default; `EC_AV1_TX32_DEPTH=0` turns it off.
4999///
5000/// Rejected three times on the bars rows of the native gate (flat to +0.3).
5001/// lane-av1resweep re-judged it on the two REAL film crops at
5002/// [`LAMBDA_SCALE`] 0.05, where it is the largest single lever in this file
5003/// (BD vs libaom / vs rav1e, shipped -> `EC_AV1_TX32_DEPTH=1`):
5004///
5005/// | clip | shipped | tx32 depth | + [`compound_var_tx`] |
5006/// |---|---|---|---|
5007/// | bars 1080p | +15.6 / -1.7 | +15.7 / -1.5 | +15.6 / -1.6 |
5008/// | bars 2160p | +46.5 / +18.8 | +46.5 / +18.8 | +46.6 / +18.8 |
5009/// | film A | +69.0 / +37.5 | +67.9 / +36.3 | +65.5 / +34.7 |
5010/// | film B | +100.0 / +61.5 | +96.6 / +58.4 | +94.5 / +56.9 |
5011/// | screen | +51.0 / -14.5 | +50.7 / -14.4 | +50.2 / -14.6 |
5012///
5013/// The bars rows are ~90% zero-intra-cost cells, so the split never had
5014/// residual to reach there -- the tool was being judged on content that
5015/// cannot pay for it (class `gate-blind-to-feature`). `EC_AV1_TX32_DEPTH`.
5016fn tx32_depth_search() -> bool {
5017 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5018 crate::envflags::var("EC_AV1_TX32_DEPTH").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
5019 });
5020 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX32_DEPTH))
5021}
5022
5023/// Whether a COMPOUND inter winner is offered the var-tx split at all: its
5024/// trial units have to be predicted from BOTH references
5025/// ([`mc_trial_compound`]) or the split would re-predict them by single-
5026/// reference translation, which is not what the decoder reconstructs.
5027/// ON by default (the table on [`tx32_depth_search`]: on real film it is
5028/// worth a further -2.4/-1.6 on film A and -2.1/-1.5 on film B on top of the
5029/// 32x32 depth search); `EC_AV1_COMP_VARTX=0` turns it off.
5030/// `EC_AV1_COMP_VARTX`.
5031fn compound_var_tx() -> bool {
5032 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
5033 crate::envflags::var("EC_AV1_COMP_VARTX").ok().map(|v| !matches!(v.as_str(), "0" | "off"))
5034 });
5035 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::COMPOUND_VAR_TX))
5036}
5037
5038/// How many 32x32-and-below inter blocks each reference frame won, indexed by
5039/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
5040/// fire count a gate prints to see an extra reference reach a block at all
5041/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
5042/// chosen is a pyramid that costs bytes and buys nothing).
5043static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
5044 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
5045
5046/// Reads [`REF_FRAME_HITS`] and zeroes it.
5047#[cfg(test)]
5048pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
5049 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
5050}
5051
5052/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
5053#[cfg(test)]
5054pub(crate) fn take_inter_tx_split_hits() -> [usize; 8] {
5055 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
5056}
5057
5058/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
5059/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
5060/// is one flag, depth 1 is a split root plus one unsplit flag per child
5061/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
5062/// or a 4x4 sub-size).
5063fn txfm_split_bits(side: usize, depth: usize) -> f64 {
5064 let max_tx = side.min(64);
5065 let ctx = |tx: usize| {
5066 crate::decode::txfm_partition_ctx_rect(
5067 crate::decode::TXFM_CTX_INIT,
5068 crate::decode::TXFM_CTX_INIT,
5069 side,
5070 tx,
5071 tx,
5072 )
5073 };
5074 if depth == 0 {
5075 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
5076 }
5077 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
5078 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
5079}
5080
5081/// spec 5.11.40 / libaom `av1_get_tx_type`: an INTER block's chroma transform
5082/// type is never coded -- the decoder takes the LUMA type of the block's
5083/// chroma-reference position and reduces it to the set the chroma size allows
5084/// ([`crate::decode::reduce_inherited_chroma_tx_type`]). This encoder
5085/// quantised chroma under a `DCT_DCT` basis whatever luma chose, so every
5086/// non-`DCT_DCT` luma winner had its chroma levels inverse-transformed on a
5087/// basis they were never produced for: on the bars gate row the luma of the
5088/// unconditional tx-type arm came out BETTER on every frame (53.66 -> 53.70
5089/// dB) while V lost seven decibels (52.52 -> 45.53) -- the whole 20-point BD
5090/// collapse two lanes attributed to the type PRICE (class
5091/// `parsed then discarded` / `override slot on one arm`: a decoder-derived
5092/// field the encoder never mirrored).
5093///
5094/// Re-codes the two chroma planes of a committed inter block at the type the
5095/// decoder will use, `None` when the inherited type reduces to `DCT_DCT` and
5096/// the trials the caller already holds are right.
5097#[allow(clippy::too_many_arguments)]
5098fn recode_inter_chroma(
5099 chroma: &[Plane; 2],
5100 (x, y): (usize, usize),
5101 side: usize,
5102 mv: (i32, i32),
5103 refs: [(&[u16], usize, usize, usize); 2],
5104 second: Option<((i32, i32), [(&[u16], usize, usize, usize); 2])>,
5105 search: &Search,
5106 set: TxbSet,
5107 luma_tx_type: TxType,
5108 fctx: &crate::decode::FrameCtx,
5109) -> Option<[Trial; 2]> {
5110 let c = side / 2;
5111 let tx = crate::decode::reduce_inherited_chroma_tx_type(luma_tx_type, c.min(32), c.min(32), fctx);
5112 if tx == TxType::DctDct {
5113 return None;
5114 }
5115 Some([0usize, 1].map(|p| match second {
5116 Some((mv1, r1)) => mc_trial_compound_typed(
5117 &chroma[p], x / 2, y / 2, c, (mv, mv1), false, refs[p], r1[p], search.base_q_idx,
5118 search.deadzone, set, tx, fctx,
5119 ),
5120 None => mc_trial_typed(
5121 &chroma[p], x / 2, y / 2, c, mv, false, refs[p].0, refs[p].1, refs[p].2, refs[p].3,
5122 false, search.base_q_idx, search.deadzone, set, tx, fctx,
5123 ),
5124 }))
5125}
5126
5127/// The inter block's own var-tx decision, once its motion vector is settled:
5128/// its residual as ONE transform over the whole block, or as the four
5129/// transforms of half the side the tree's first halving names. The prediction
5130/// is the same motion compensation either way, so the split trial
5131/// re-transforms the identical residual in four pieces -- it wins where four
5132/// small transforms carry a locally varying residual cheaper than one big
5133/// one. Commits the winner into `luma` and hands back its block-coordinate
5134/// levels, the depth the writer codes and the cost the winner adds to (or
5135/// takes off) the caller's already-computed flat cost.
5136///
5137/// Only for a block wholly inside the frame: past the true edge the reader's
5138/// var-tx recursion skips the units that fall outside
5139/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
5140/// leave the residual units this writes unpaired.
5141#[allow(clippy::too_many_arguments)]
5142fn commit_inter_luma(
5143 luma: &mut Plane,
5144 (x, y): (usize, usize),
5145 side: usize,
5146 mv: (i32, i32),
5147 reference: (&[u16], usize, usize, usize),
5148 search: &Search,
5149 flat: &Trial,
5150 skip: bool,
5151 // A COMPOUND winner's second half: the vector and reference planes the
5152 // trial units are blended from ([`mc_trial_compound`], the decoder's own
5153 // `comp_group_idx == 0` average). `None` is the single-reference block.
5154 second: Option<((i32, i32), (&[u16], usize, usize, usize))>,
5155 fctx: &crate::decode::FrameCtx,
5156) -> (Vec<i32>, u8, f64, Vec<TxType>) {
5157 // lane-txset2 step 1: the whole-block (depth 0) residual picks its own
5158 // type out of the two-type inter set the writer already codes a symbol
5159 // for, priced the same way the intra search is (sse + lambda * bits, the
5160 // bits carrying the `tx_type` symbol itself through RDOQ). A skipped
5161 // block codes no residual and the 64-point transform names no type.
5162 let mut flat_typed: Option<Trial> = None;
5163 let mut flat_type = TxType::DctDct;
5164 if !skip {
5165 // lane-intertx: on a `reduced_tx_set = 0` frame the search names the
5166 // Set1 alphabet the writer codes into ([`luma_set_for`], the shape
5167 // the intra search already takes), which is what makes the wider
5168 // seven-type candidate list below reachable -- and prices every
5169 // candidate, `IDTX` included, in the alphabet its symbol is really
5170 // coded into.
5171 if let Some(fset) =
5172 inter_luma_set(side).map(|set| luma_set_for(set, search.screen))
5173 {
5174 let lambda = search.lambda * tx_type_lambda_mult();
5175 let cost = |t: &Trial| t.sse + lambda * t.bits;
5176 for &tx_type in inter_tx_type_candidates(fset, search.screen) {
5177 if tx_type == TxType::DctDct {
5178 continue;
5179 }
5180 let candidate = match second {
5181 Some((mv1, ref1)) => mc_trial_compound_typed(
5182 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
5183 search.deadzone, fset, tx_type, fctx,
5184 ),
5185 None => mc_trial_typed(
5186 luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
5187 reference.3, false, search.base_q_idx, search.deadzone, fset, tx_type,
5188 fctx,
5189 ),
5190 };
5191 if cost(&candidate) < cost(flat_typed.as_ref().unwrap_or(flat)) {
5192 flat_type = tx_type;
5193 flat_typed = Some(candidate);
5194 }
5195 }
5196 }
5197 }
5198 // Counted at the return points, so the census names the types the block
5199 // really CODES -- a split unit's winner that the flat cost then beats was
5200 // never written (class `counter from refused stream`).
5201 let count = |types: &[TxType]| {
5202 for &t in types {
5203 INTER_TX_TYPE_HITS[t as usize].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5204 }
5205 };
5206 let flat_ref: &Trial = flat_typed.as_ref().unwrap_or(flat);
5207 if crate::envflags::env_flag!("EC_AV1_TXRD_CENSUS") && !skip {
5208 use std::sync::atomic::Ordering::Relaxed;
5209 TXRD_STATS[0].fetch_add(1, Relaxed);
5210 TXRD_STATS[1].fetch_add(flat_ref.sse as u64, Relaxed);
5211 TXRD_STATS[2].fetch_add(flat.sse as u64, Relaxed);
5212 TXRD_STATS[3].fetch_add((flat_ref.bits * 64.0) as u64, Relaxed);
5213 TXRD_STATS[4].fetch_add((flat.bits * 64.0) as u64, Relaxed);
5214 // Is the `DCT_DCT` baseline the search compares against the trial
5215 // THIS function would build for the same block? A stale or
5216 // differently-predicted baseline is what would let a candidate win on
5217 // both terms at once (class `local-rd-on-references` vs a real
5218 // pricing defect); re-predicting it here is the only way to tell.
5219 if let Some(fset) = inter_luma_set(side) {
5220 let here = match second {
5221 Some((mv1, ref1)) => mc_trial_compound_typed(
5222 luma, x, y, side, (mv, mv1), true, reference, ref1, search.base_q_idx,
5223 search.deadzone, fset, TxType::DctDct, fctx,
5224 ),
5225 None => mc_trial_typed(
5226 luma, x, y, side, mv, true, reference.0, reference.1, reference.2,
5227 reference.3, false, search.base_q_idx, search.deadzone, fset,
5228 TxType::DctDct, fctx,
5229 ),
5230 };
5231 TXRD_STATS[5].fetch_add(here.sse as u64, Relaxed);
5232 TXRD_STATS[6].fetch_add((here.bits * 64.0) as u64, Relaxed);
5233 static DUMPED: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
5234 let n = TXRD_STATS[0].load(Relaxed);
5235 if here.sse * 2.0 < flat.sse && DUMPED.fetch_add(1, Relaxed) < 30 {
5236 eprintln!(
5237 "TXRD block {n} at ({x},{y}) side={side} compound={} mv={mv:?} \
5238 flat sse={:.0} bits={:.1} | here sse={:.0} bits={:.1} | chosen {flat_type:?} \
5239 sse={:.0} bits={:.1}",
5240 second.is_some(), flat.sse, flat.bits, here.sse, here.bits,
5241 flat_ref.sse, flat_ref.bits,
5242 );
5243 }
5244 }
5245 }
5246 // What the caller's already-counted `flat` cost has to be corrected by
5247 // when a non-`DCT_DCT` type won it, the same way the split delta below is.
5248 let flat_gain = (flat_ref.sse + search.lambda * flat_ref.bits)
5249 - (flat.sse + search.lambda * flat.bits);
5250 let eligible = tx_select()
5251 && tx_select_inter()
5252 && !skip
5253 && side >= 16
5254 && (second.is_none() || compound_var_tx())
5255 && (side != BLOCK || tx32_depth_search())
5256 && x + side <= luma.true_width
5257 && y + side <= luma.true_height;
5258 if !eligible {
5259 luma.commit(x, y, side, flat_ref);
5260 count(&[flat_type]);
5261 return (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type]);
5262 }
5263 let tx = side / 2;
5264 let set = luma_set_for(
5265 if tx >= 32 {
5266 // lane-b64b: the 64x64 root's halved transform is TX_32X32.
5267 TxbSet::Luma32Inter
5268 } else if tx >= 16 {
5269 TxbSet::Luma16Inter
5270 } else {
5271 TxbSet::Luma8Inter
5272 },
5273 search.screen,
5274 );
5275 let mut levels = vec![0i32; side * side];
5276 let (mut sse, mut bits) = (0.0, 0.0);
5277 let mut units = Vec::with_capacity(4);
5278 // The split units are smaller than their block, so their `txb_skip`
5279 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
5280 // each unit's own commit publishes what the next one reads, coding order.
5281 luma.ctx.tu_split = true;
5282 // One type per unit in the writer's own raster order (tile.rs
5283 // `write_luma_tus`), all `DCT_DCT` when nothing else is offered.
5284 let mut split_types = vec![TxType::DctDct; 4];
5285 for tu_row in 0..2 {
5286 for tu_col in 0..2 {
5287 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
5288 let unit = |tx_type: TxType| match second {
5289 Some((mv1, ref1)) => mc_trial_compound_typed(
5290 luma, tu_x, tu_y, tx, (mv, mv1), true, reference, ref1,
5291 search.base_q_idx, search.deadzone, set, tx_type, fctx,
5292 ),
5293 None => mc_trial_typed(
5294 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
5295 reference.3, false, search.base_q_idx, search.deadzone, set, tx_type, fctx,
5296 ),
5297 };
5298 let mut best: Option<(f64, TxType, Trial)> = None;
5299 for &tx_type in inter_tx_type_candidates(set, search.screen) {
5300 let candidate = unit(tx_type);
5301 let cost = candidate.sse + search.lambda * tx_type_lambda_mult() * candidate.bits;
5302 if best.as_ref().is_none_or(|(b, _, _)| cost < *b) {
5303 best = Some((cost, tx_type, candidate));
5304 }
5305 }
5306 let (_, tx_type, trial) = best.expect("the candidate list is never empty");
5307 split_types[tu_row * 2 + tu_col] = tx_type;
5308 sse += trial.sse;
5309 bits += trial.bits;
5310 for row in 0..tx {
5311 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
5312 .copy_from_slice(&trial.levels[row * tx..][..tx]);
5313 }
5314 units.push((tu_x, tu_y, trial));
5315 }
5316 }
5317 luma.ctx.tu_split = false;
5318 let split_rate = bits + txfm_split_bits(side, 1);
5319 let flat_rate = flat_ref.bits + txfm_split_bits(side, 0);
5320 let split_cost = sse + search.lambda * split_lambda_mult() * split_rate;
5321 let flat_cost = flat_ref.sse + search.lambda * flat_rate;
5322 if split_census_on() {
5323 split_census(1, false, side, split_cost < flat_cost, (split_rate, sse), (flat_rate, flat_ref.sse));
5324 }
5325 let class = usize::from(side == BLOCK) * 4 + usize::from(second.is_some()) * 2;
5326 // The depth census has a leaf row and a 32x32 row and no 64 one, so the
5327 // 64x64 root counts itself ([`take_b64_var_tx_hits`]) instead of landing
5328 // in the leaf row (class `gate-blind-to-feature`).
5329 let counted = side <= BLOCK;
5330 if split_cost < flat_cost {
5331 for (tu_x, tu_y, trial) in &units {
5332 luma.commit(*tu_x, *tu_y, tx, trial);
5333 }
5334 if counted {
5335 INTER_TX_SPLIT_HITS[class + 1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5336 }
5337 count(&split_types);
5338 return (levels, 1, flat_gain + split_cost - flat_cost, split_types);
5339 }
5340 if counted {
5341 INTER_TX_SPLIT_HITS[class].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
5342 }
5343 luma.commit(x, y, side, flat_ref);
5344 count(&[flat_type]);
5345 (flat_ref.levels.clone(), 0, flat_gain, vec![flat_type])
5346}
5347
5348/// The largest distinct-colour count a block may hold and still be offered a
5349/// palette candidate at all: past it the k-means quantisation costs more
5350/// error than the map saves rate, and every trial is wasted wall.
5351///
5352/// Swept on the gate's own screen capture (lane-av1pal2, the
5353/// `unswept-decision-constants` class): 32 (the value this lane inherited)
5354/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
5355/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
5356/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
5357/// binds on nothing this content holds. 128 ships: best BD against both
5358/// references and no wall cost at all (6.1s, the same as at 32, because the
5359/// blocks it newly admits are ones the RD then keeps).
5360/// `EC_AV1_PAL_MAXCOLORS`.
5361fn palette_max_colors() -> usize {
5362 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5363 *N.get_or_init(|| {
5364 std::env::var("EC_AV1_PAL_MAXCOLORS")
5365 .ok()
5366 .and_then(|v| v.parse().ok())
5367 .unwrap_or(128)
5368 })
5369}
5370
5371/// The palettes worth trying for one block's luma, in the shape libaom's
5372/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
5373/// distinct colours takes them ALL (the prediction is then exact and the
5374/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
5375/// one-dimensional Lloyd iteration seeded evenly across its range -- both
5376/// offered, because which wins is an RD question the caller answers.
5377/// `block` is `side*side` source samples, row-major.
5378fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
5379 let mut histogram = [0u32; 256];
5380 for &v in block {
5381 histogram[usize::from(v)] += 1;
5382 }
5383 let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
5384 if present.len() < 2 {
5385 return Vec::new();
5386 }
5387 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
5388 let mut base = [0u16; 8];
5389 base[..colors.len()].copy_from_slice(colors);
5390 let map = block
5391 .iter()
5392 .map(|&v| {
5393 colors
5394 .iter()
5395 .enumerate()
5396 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
5397 .map(|(i, _)| i as u8)
5398 .expect("a palette holds at least two colours")
5399 })
5400 .collect();
5401 crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
5402 };
5403 if present.len() <= 8 {
5404 return vec![exact(&present)];
5405 }
5406 if present.len() > palette_max_colors() {
5407 return Vec::new();
5408 }
5409 let (lo, hi) = (
5410 i32::from(present[0]),
5411 i32::from(present[present.len() - 1]),
5412 );
5413 let mut out = Vec::with_capacity(2);
5414 for n in [8usize, 4] {
5415 // Even seeding across the block's own range, then four Lloyd passes
5416 // over the histogram (256 bins, not `side*side` pixels).
5417 let mut centres: Vec<f64> = (0..n)
5418 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
5419 .collect();
5420 for _ in 0..4 {
5421 let mut sums = vec![0f64; n];
5422 let mut counts = vec![0u32; n];
5423 for (v, &count) in histogram.iter().enumerate() {
5424 if count == 0 {
5425 continue;
5426 }
5427 let k = (0..n)
5428 .min_by(|&a, &b| {
5429 (centres[a] - v as f64)
5430 .abs()
5431 .total_cmp(&(centres[b] - v as f64).abs())
5432 })
5433 .expect("n >= 2");
5434 sums[k] += (v as u32 * count) as f64;
5435 counts[k] += count;
5436 }
5437 for k in 0..n {
5438 if counts[k] > 0 {
5439 centres[k] = sums[k] / f64::from(counts[k]);
5440 }
5441 }
5442 }
5443 let mut colors: Vec<u16> = centres
5444 .iter()
5445 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
5446 .collect();
5447 colors.sort_unstable();
5448 colors.dedup();
5449 if colors.len() >= 2 {
5450 out.push(exact(&colors));
5451 }
5452 }
5453 out
5454}
5455
5456#[allow(clippy::too_many_arguments)]
5457// ---------------------------------------------------------------------------
5458// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
5459// validity). A key frame that detected screen content and finds enough exact
5460// repeats in its own source sets `allow_intrabc`, which the spec forces every
5461// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
5462// its place when the copied blocks pay back the deblock/CDEF/LR the frame
5463// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
5464// ---------------------------------------------------------------------------
5465
5466/// Whether intra block copy is offered at all. **Off by default** --
5467/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
5468/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
5469/// but on the gate's real screen capture it MEASURED WORSE: setting
5470/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
5471/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
5472/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
5473/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
5474/// that detected no screen content.
5475fn intrabc_enabled() -> bool {
5476 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
5477 return forced;
5478 }
5479 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
5480 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
5481}
5482
5483thread_local! {
5484 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
5485 /// probe runs both arms in one process, and the suite is one process, so
5486 /// an environment variable cannot separate them (same reason
5487 /// [`SCREEN_FORCE`] exists).
5488 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
5489}
5490
5491#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5492pub(crate) fn force_intrabc(value: Option<bool>) {
5493 INTRABC_FORCE.with(|c| c.set(value));
5494}
5495
5496/// How many of a screen frame's 16x16 blocks must have an exact repeat
5497/// somewhere else in the source before `allow_intrabc` is worth the in-loop
5498/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
5499/// constant class: `probe_intrabc_threshold` measures the arm at several
5500/// values.
5501fn intrabc_pct() -> usize {
5502 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5503 *N.get_or_init(|| {
5504 std::env::var("EC_AV1_INTRABC_PCT")
5505 .ok()
5506 .and_then(|v| v.parse().ok())
5507 .unwrap_or(10)
5508 })
5509}
5510
5511/// The pixel grid intrabc source positions are hashed on
5512/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
5513/// which keeps the block-hash table (and so the search) linear in the frame
5514/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
5515/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
5516/// bilinear interpolation decode.rs applies but this encoder does not.
5517fn intrabc_step() -> usize {
5518 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
5519 *N.get_or_init(|| {
5520 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
5521 .ok()
5522 .and_then(|v| v.parse().ok())
5523 .unwrap_or(4);
5524 if n % 2 == 0 { n.max(2) } else { 4 }
5525 })
5526}
5527
5528/// The side of the luma square the block-hash table is keyed on.
5529const IBC_HASH: usize = 16;
5530
5531/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
5532/// the current one the source's bottom-right corner must already be. Under
5533/// 128 superblocks the same 256 pixels are two superblocks, which
5534/// [`Ibc::dv_valid`] derives from the size itself.
5535const INTRABC_DELAY_SB64: i32 = 4;
5536
5537/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
5538fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
5539 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
5540 for row in 0..IBC_HASH {
5541 let base = (y + row) * width + x;
5542 for &v in &plane[base..base + IBC_HASH] {
5543 h ^= u64::from(v);
5544 h = h.wrapping_mul(0x100_0000_01b3);
5545 }
5546 }
5547 h
5548}
5549
5550/// Every `intrabc_step()`-aligned position of `plane` inside
5551/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
5552fn ibc_index(
5553 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
5554 plane: &[u8],
5555 width: usize,
5556 (x0, y0): (usize, usize),
5557 (x1, y1): (usize, usize),
5558) {
5559 let step = intrabc_step();
5560 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
5561 return;
5562 }
5563 let mut y = y0.next_multiple_of(step);
5564 while y + IBC_HASH <= y1 {
5565 let mut x = x0.next_multiple_of(step);
5566 while x + IBC_HASH <= x1 {
5567 table
5568 .entry(ibc_hash(plane, width, x, y))
5569 .or_default()
5570 .push((x as u32, y as u32));
5571 x += step;
5572 }
5573 y += step;
5574 }
5575}
5576
5577/// Whether `screen`-detected source `y` repeats itself enough to be worth
5578/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
5579/// content appears at some other position, against [`intrabc_pct`]. Returns
5580/// the share as well, for the gate's own print.
5581fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
5582 if true_width < 4 * 64 || true_height < 2 * 64 {
5583 return (false, 0.0);
5584 }
5585 let mut table = std::collections::HashMap::new();
5586 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
5587 let (mut total, mut matched) = (0usize, 0usize);
5588 let mut by = 0;
5589 while by + IBC_HASH <= true_height {
5590 let mut bx = 0;
5591 while bx + IBC_HASH <= true_width {
5592 total += 1;
5593 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
5594 if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
5595 matched += 1;
5596 }
5597 }
5598 bx += IBC_HASH;
5599 }
5600 by += IBC_HASH;
5601 }
5602 let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
5603 (share * 100.0 >= intrabc_pct() as f64, share)
5604}
5605
5606/// One tile's intrabc search state: a block-hash table over the part of the
5607/// tile's own reconstruction that is already final (whole superblock rows --
5608/// the in-loop filters are off on this frame, so a coded superblock row never
5609/// changes again), plus the last DV chosen, which the RD price uses as its
5610/// predictor estimate.
5611struct Ibc {
5612 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
5613 /// source repeats exactly where a lossily coded reconstruction only
5614 /// nearly does, so an exact-match table over the reconstruction finds
5615 /// almost nothing. The candidate is then SCORED against the
5616 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
5617 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
5618 /// The tile's own luma rect, in samples.
5619 tile: (usize, usize, usize, usize),
5620 /// The DV the previous intrabc block of this tile took -- the *estimate*
5621 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
5622 /// against. The writer computes the true predictor off its own mi grid
5623 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
5624 /// a slightly mispriced candidate, never a wrong bitstream.
5625 last_dv: Option<(i32, i32)>,
5626 /// How many blocks took intrabc, and how many hash lookups found at least
5627 /// one valid candidate -- the gate's own fire counts.
5628 hits: usize,
5629 lookups: usize,
5630 found: usize,
5631}
5632
5633impl Ibc {
5634 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
5635 let mut table = std::collections::HashMap::new();
5636 ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
5637 Self {
5638 table,
5639 tile,
5640 last_dv: None,
5641 hits: 0,
5642 lookups: 0,
5643 found: 0,
5644 }
5645 }
5646
5647 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
5648 /// (1/8 pel), with this lane's own extra restriction on top: the source
5649 /// must lie entirely in a COMPLETED superblock row, which is exactly the
5650 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
5651 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
5652 /// wavefront's own diagonal) are legal and not searched; the upgrade path
5653 /// is to index the current row's finished superblocks too.
5654 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
5655 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
5656 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
5657 return false;
5658 }
5659 let (tx0, ty0, tx1, ty1) = (
5660 self.tile.0 as i32,
5661 self.tile.1 as i32,
5662 self.tile.2 as i32,
5663 self.tile.3 as i32,
5664 );
5665 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
5666 let (w, h) = (w as i32, h as i32);
5667 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
5668 return false;
5669 }
5670 // lane-b128m: libaom counts this wavefront in SUPERBLOCKS, and the
5671 // superblock is 128 wide under `EC_AV1_SB128` (`INTRABC_DELAY_SB =
5672 // INTRABC_DELAY_PIXELS >> sb_size_log2`, i.e. 2 there and 4 here).
5673 // Counting 64s under a 128 superblock let the search take a source
5674 // from a 64 row the 128 visit order had not reconstructed yet.
5675 let sb_log2 = if crate::encode::sb128_on() { 7 } else { 6 };
5676 let delay: i32 = if sb_log2 == 7 { INTRABC_DELAY_SB64 / 2 } else { INTRABC_DELAY_SB64 };
5677 let active_sb_row = (y as i32 - ty0) >> sb_log2;
5678 let active_sb_col = (x as i32 - tx0) >> sb_log2;
5679 let src_sb_row = (sy + h - 1 - ty0) >> sb_log2;
5680 let src_sb_col = (sx + w - 1 - tx0) >> sb_log2;
5681 // This lane's own restriction (see the doc comment).
5682 if src_sb_row >= active_sb_row {
5683 return false;
5684 }
5685 let total = ((tx1 - tx0 - 1) >> sb_log2) + 1;
5686 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - delay {
5687 return false;
5688 }
5689 // libaom's wavefront: only the top-left cone of the frame is legal.
5690 let wf = (1 + delay) * (active_sb_row - src_sb_row);
5691 src_sb_col < active_sb_col - delay + wf
5692 }
5693}
5694
5695/// How many block searches ran, how many found at least one VALID candidate,
5696/// and how many won on rate-distortion -- the hash hit rate a gate prints
5697/// (class `gate-blind-to-feature`: "the search ran" and "the search found
5698/// something" and "the block took it" are three different claims).
5699static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
5700 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
5701
5702impl Drop for Ibc {
5703 fn drop(&mut self) {
5704 for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
5705 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
5706 }
5707 }
5708}
5709
5710/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
5711/// its own encode.
5712#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
5713pub(crate) fn take_intrabc_search() -> [usize; 3] {
5714 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
5715}
5716
5717/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
5718/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
5719/// infers rather than codes.
5720fn dv_component_bits(diff: i32) -> f64 {
5721 let z = diff.unsigned_abs() as i32 - 1;
5722 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
5723 let class = mv_class_of(z);
5724 bits += symbol_bits(&cdf::MV_CLASS, class);
5725 let local = z - mv_class_base(class);
5726 if class == 0 {
5727 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
5728 } else {
5729 let d = local >> 3;
5730 for i in 0..class {
5731 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
5732 }
5733 }
5734 bits
5735}
5736
5737/// What one block vector costs against `pred`, plus the `skip` and
5738/// `use_intrabc` flags the block carries and the ordinary intra block does
5739/// not pay in this currency.
5740fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
5741 let diff = (dv.0 - pred.0, dv.1 - pred.1);
5742 let joint = match (diff.0 != 0, diff.1 != 0) {
5743 (false, false) => 0,
5744 (false, true) => 1,
5745 (true, false) => 2,
5746 (true, true) => 3,
5747 };
5748 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
5749 if diff.0 != 0 {
5750 bits += dv_component_bits(diff.0);
5751 }
5752 if diff.1 != 0 {
5753 bits += dv_component_bits(diff.1);
5754 }
5755 bits
5756}
5757
5758/// The squared error of copying the `side`-square block at `(sx, sy)` of each
5759/// plane's reconstruction onto the source block at `(x, y)`, luma and both
5760/// chroma planes together -- what an intrabc block's whole (residual-free)
5761/// distortion is.
5762fn ibc_sse(
5763 luma: &Plane,
5764 chroma: &[Plane; 2],
5765 (x, y): (usize, usize),
5766 (sx, sy): (usize, usize),
5767 side: usize,
5768) -> f64 {
5769 // Inside the true frame only, for the reason [`Plane::block_sse`] is
5770 // (lane-sse): an intrabc block at the edge would otherwise be ranked by
5771 // how well it copies the padding.
5772 let mut sse = 0.0f64;
5773 let clip = |whole: usize, inside: usize| match edge_sse() {
5774 true => whole.min(inside),
5775 false => whole,
5776 };
5777 let rows = clip(side, luma.true_height.saturating_sub(y));
5778 let cols = clip(side, luma.true_width.saturating_sub(x));
5779 for row in 0..rows {
5780 let src = &luma.source[(y + row) * luma.width + x..][..cols];
5781 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..cols];
5782 for (&s, &r) in src.iter().zip(rec) {
5783 let d = f64::from(i32::from(s) - i32::from(r));
5784 sse += d * d;
5785 }
5786 }
5787 let half = side / 2;
5788 for plane in chroma {
5789 let rows = clip(half, plane.true_height.saturating_sub(y / 2));
5790 let cols = clip(half, plane.true_width.saturating_sub(x / 2));
5791 for row in 0..rows {
5792 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..cols];
5793 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..cols];
5794 for (&s, &r) in src.iter().zip(rec) {
5795 let d = f64::from(i32::from(s) - i32::from(r));
5796 sse += d * d;
5797 }
5798 }
5799 }
5800 sse
5801}
5802
5803/// Copies the `side`-square block at `(sx, sy)` of each plane's
5804/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
5805/// since it carries no residual (`skip`). Full-pel in both planes by
5806/// construction ([`intrabc_step`] keeps every DV even), which is what makes
5807/// this a plain copy where decode.rs runs the bilinear kernel over the same
5808/// samples.
5809fn ibc_commit(
5810 luma: &mut Plane,
5811 chroma: &mut [Plane; 2],
5812 (x, y): (usize, usize),
5813 (sx, sy): (usize, usize),
5814 side: usize,
5815) {
5816 for row in 0..side {
5817 let from = (sy + row) * luma.width + sx;
5818 let to = (y + row) * luma.width + x;
5819 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
5820 luma.reconstruction[to..to + side].copy_from_slice(&copied);
5821 }
5822 let half = side / 2;
5823 for plane in chroma {
5824 for row in 0..half {
5825 let from = (sy / 2 + row) * plane.width + sx / 2;
5826 let to = (y / 2 + row) * plane.width + x / 2;
5827 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
5828 plane.reconstruction[to..to + half].copy_from_slice(&copied);
5829 }
5830 plane.commit_ctx_zero(x / 2, y / 2, half);
5831 }
5832 luma.commit_ctx_zero(x, y, side);
5833}
5834
5835/// Searches this block's own DV: every hash-table position whose 16x16 luma
5836/// square equals the block's source square, plus the previous block's DV as a
5837/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
5838/// the winning `(dv, cost)`, or `None` when nothing valid was found.
5839fn ibc_search(
5840 ibc: &mut Ibc,
5841 luma: &Plane,
5842 chroma: &[Plane; 2],
5843 (x, y): (usize, usize),
5844 side: usize,
5845 lambda: f64,
5846) -> Option<((i32, i32), f64, (usize, usize))> {
5847 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
5848 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
5849 let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
5850 let dv = (
5851 (sy as i32 - y as i32) * 8,
5852 (sx as i32 - x as i32) * 8,
5853 );
5854 if !ibc.dv_valid(x, y, side, side, dv) {
5855 return;
5856 }
5857 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
5858 if best.as_ref().is_none_or(|b| cost < b.1) {
5859 *best = Some((dv, cost, (sx, sy)));
5860 }
5861 };
5862 ibc.lookups += 1;
5863 let key = ibc_hash(luma.source, luma.width, x, y);
5864 // The table is filled in raster order, so the entries BEFORE this block's
5865 // own position are exactly the already-coded ones -- and the nearest of
5866 // them costs the fewest DV bits. Walking backwards from the block's own
5867 // slot is what makes the search look up-and-left; taking the newest
5868 // entries outright only ever finds candidates below and to the right,
5869 // every one of which `dv_valid` rejects.
5870 let hits: Vec<(u32, u32)> = ibc
5871 .table
5872 .get(&key)
5873 .map(|h| {
5874 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
5875 h[..end].iter().rev().take(32).copied().collect()
5876 })
5877 .unwrap_or_default();
5878 for (hx, hy) in hits {
5879 consider(&*ibc, hx as usize, hy as usize, &mut best);
5880 }
5881 if let Some(dv) = ibc.last_dv {
5882 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
5883 if sx >= 0 && sy >= 0 {
5884 consider(&*ibc, sx as usize, sy as usize, &mut best);
5885 }
5886 }
5887 if best.is_some() {
5888 ibc.found += 1;
5889 }
5890 best
5891}
5892
5893fn code_square(
5894 luma: &mut Plane,
5895 chroma: &mut [Plane; 2],
5896 (x, y): (usize, usize),
5897 side: usize,
5898 search: &Search,
5899 mode_bits: &[f64; 13],
5900 // The frame header's `tx_mode == TxMode::Select`: the block then searches
5901 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
5902 // transform over its whole side.
5903 tx_select: bool,
5904 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
5905 // header did not set `allow_intrabc`.
5906 ibc: Option<&mut Ibc>,
5907 // Whether this is a KEY frame's block, read only by the split census
5908 // ([`SPLIT_CENSUS`]): the two frame types split at very different rates,
5909 // which is this lane's whole finding.
5910 census_key: bool,
5911 fctx: &crate::decode::FrameCtx,
5912) -> (BlockCoeffs, f64) {
5913 let (luma_set, chroma_set) = if side == SUPERBLOCK {
5914 // A whole superblock coded as ONE intra block (lane-i64): one
5915 // TX_64X64 luma transform, whose coded quarter is the 32x32 corner
5916 // `code_from_prediction` hands back, and one TX_32X32 per chroma
5917 // plane -- the same three sets the key frame writer's
5918 // `Superblock::Whole` arm codes, and the same the inter 64x64 root
5919 // uses (`search_skip_64`).
5920 (TxbSet::Luma64, TxbSet::Chroma32)
5921 } else if side == BLOCK {
5922 (TxbSet::Luma32, TxbSet::Chroma16)
5923 } else if side == 8 {
5924 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
5925 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
5926 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
5927 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
5928 // (this branch is still unreached), so leaving `Chroma8` here would
5929 // silently wire the wrong table the moment one does; `Chroma4` is
5930 // what a real caller needs.
5931 (TxbSet::Luma8, TxbSet::Chroma4)
5932 } else {
5933 (TxbSet::Luma16, TxbSet::Chroma8)
5934 };
5935 let at = At {
5936 x,
5937 y,
5938 side,
5939 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
5940 set: luma_set_for(luma_set, search.screen),
5941 };
5942 let (mut luma_coeffs, mode, angle_delta, mut cost, tx_type) =
5943 luma.search_block(at, search, mode_bits, fctx);
5944 let mut luma_tx_types = vec![tx_type];
5945 // The depth search runs on the mode the whole-block transform picked --
5946 // libaom's own ordering, and the reason it costs one extra pass per depth
5947 // rather than one per (mode, depth) pair.
5948 let mut tx_depth = 0u8;
5949 // A 64x64 block has no depth to search (`max_tx_depth`), but the writer
5950 // still codes its `tx_depth` symbol off `TX_SIZE_CAT3`, so the incumbent
5951 // pays that zero exactly as a 32x32's depth search makes it pay
5952 // `tx_depth_bits(32, 0)` -- otherwise the 64-versus-four-32 comparison
5953 // below hands the root a symbol for free.
5954 if tx_select && side == SUPERBLOCK {
5955 cost += search.lambda * tx_depth_bits(side, 0);
5956 }
5957 if tx_select && max_tx_depth(side) > 0 {
5958 let mut best = (
5959 cost + search.lambda * tx_depth_bits(side, 0),
5960 0usize,
5961 luma.snapshot(x, y, side),
5962 luma_coeffs,
5963 );
5964 let mut best_types = std::mem::take(&mut luma_tx_types);
5965 // The census wants the flat arm's own (rate, distortion), which
5966 // `search_block` only hands back folded into one cost -- so under the
5967 // env flag alone it is re-coded at depth 0 and the plane restored.
5968 let census_flat = split_census_on().then(|| {
5969 let kept = luma.snapshot(x, y, side);
5970 let (_, sse, bits, _) =
5971 luma.code_tx_depth(at, mode, angle_delta, 0, None, search, fctx);
5972 luma.restore(x, y, side, &kept);
5973 (bits + tx_depth_bits(side, 0), sse)
5974 });
5975 let mut census_split: Option<(f64, f64)> = None;
5976 for depth in 1..=max_tx_depth(side) {
5977 let (levels, sse, bits, types) =
5978 luma.code_tx_depth(at, mode, angle_delta, depth, None, search, fctx);
5979 let rate = bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth);
5980 let cost_d = sse + search.lambda * split_lambda_mult() * rate;
5981 if census_flat.is_some() {
5982 let c = (bits + tx_depth_bits(side, depth), sse);
5983 if census_split.is_none_or(|b| sse + search.lambda * rate < b.1 + search.lambda * b.0)
5984 {
5985 census_split = Some(c);
5986 }
5987 }
5988 if cost_d < best.0 {
5989 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
5990 best_types = types;
5991 }
5992 }
5993 if let (Some(flat), Some(split)) = (census_flat, census_split) {
5994 split_census(0, census_key, side, best.1 > 0, split, flat);
5995 }
5996 luma_tx_types = best_types;
5997 luma.restore(x, y, side, &best.2);
5998 cost = best.0;
5999 tx_depth = best.1 as u8;
6000 luma_coeffs = best.3;
6001 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6002 }
6003 // The palette candidate is priced against the mode the luma search (and
6004 // its transform-depth search) already settled on, so a block only takes
6005 // one when it beats the best ordinary intra coding of the same pixels.
6006 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
6007 // prediction is the colour map, not the DC of its neighbours.
6008 let mut mode = mode;
6009 let mut angle_delta = angle_delta;
6010 let mut palette = None;
6011 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6012 let source: Vec<u8> = (y..y + side)
6013 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
6014 .collect();
6015 let kept = luma.snapshot(x, y, side);
6016 // spec 5.11.50: a block cut by the frame's right/bottom edge codes
6017 // its map over the ON-SCREEN corner only and the decoder replicates
6018 // that outward, so the searched map is folded the same way here --
6019 // the prediction priced, the reconstruction committed and the symbols
6020 // `write_color_index_map` writes are then one and the same map
6021 // (lane-palw).
6022 let on = (
6023 side.min(luma.true_width.saturating_sub(x)),
6024 side.min(luma.true_height.saturating_sub(y)),
6025 );
6026 for mut pal in palette_candidates(&source) {
6027 let n = usize::from(pal.size);
6028 crate::decode::palette_replicate(&mut pal.map, side, side, on);
6029 let prediction: Vec<u8> = pal
6030 .map
6031 .iter()
6032 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
6033 .collect();
6034 let trial = luma.code_from_prediction(
6035 x,
6036 y,
6037 side,
6038 &prediction,
6039 false,
6040 search.base_q_idx,
6041 search.deadzone,
6042 luma_set,
6043 );
6044 let cost_p = trial.sse
6045 + search.lambda
6046 * (trial.bits
6047 + mode_bits[DC_PRED as usize]
6048 + crate::tile::palette_bits(&pal, side, on)
6049 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
6050 if cost_p < cost {
6051 cost = cost_p;
6052 mode = DC_PRED as u8;
6053 angle_delta = 0;
6054 tx_depth = 0;
6055 luma_coeffs = coeffs(&trial.levels, side.min(BLOCK));
6056 luma.commit(x, y, side, &trial);
6057 palette = Some(pal);
6058 }
6059 }
6060 if palette.is_none() {
6061 luma.restore(x, y, side, &kept);
6062 }
6063 }
6064
6065 // The five recursive filter-intra modes (spec 5.11.14), priced against
6066 // whatever the mode, transform-depth and palette searches settled on --
6067 // the same "one candidate loop after the incumbent is known" shape the
6068 // palette above uses. A block that takes one is `DC_PRED` with no palette
6069 // by construction (`av1_filter_intra_allowed`), and its luma transform
6070 // types are coded from `fimode_to_intradir`'s row (`crate::tile::tx_row`).
6071 //
6072 // lane-fitu: on a SCREEN frame the candidate is priced at every transform
6073 // depth the ordinary intra search runs, each unit predicting recursively
6074 // off the units before it ([`Plane::code_tx_depth`]'s `filter_intra`
6075 // arm), so a block whose ordinary winner wanted a split transform is
6076 // compared against a filter arm that may split too.
6077 //
6078 // Measured (native BD table, lane-fitu): searching the depths on EVERY
6079 // frame moves screen -1.0/-0.4 and the bars rows -0.4/-0.7 but leaves
6080 // film A flat and film B +0.1/+0.5 WORSE -- the extra filter blocks are a
6081 // locally cheaper reconstruction that the film rows go on to predict from
6082 // (class `local-rd-on-references`) -- at +30..35% encoder wall. Screen
6083 // content is where it pays, and a non-screen frame keeps the depth-0-only
6084 // arm, byte for byte.
6085 let mut filter_intra: Option<u8> = None;
6086 if filter_intra_on()
6087 && palette.is_none()
6088 && let Some(class) = crate::decode::filter_intra_size_class(side)
6089 {
6090 let row = &cdf::FILTER_INTRA[class];
6091 // With the sequence bit on, EVERY `DC_PRED` block without a luma
6092 // palette carries the flag, so the incumbent pays its zero before the
6093 // comparison -- otherwise the candidate is charged a bit the block
6094 // spends either way (class `price-the-narrowing-not-the-table`).
6095 if mode == DC_PRED {
6096 cost += search.lambda * symbol_bits(row, 0);
6097 }
6098 let one_bits = symbol_bits(row, 1);
6099 let kept = luma.snapshot(x, y, side);
6100 let max_depth = if tx_select && search.screen { max_tx_depth(side) } else { 0 };
6101 let mut best: Option<(f64, u8, usize, (Vec<u8>, Vec<CoefCtx>), Vec<Coeff>)> = None;
6102 for fi in 0..5u8 {
6103 for depth in 0..=max_depth {
6104 // A filter-intra block's units are coded through
6105 // `code_from_prediction`, which is `DCT_DCT` throughout, so
6106 // this arm keeps the empty (all-`DCT_DCT`) type list.
6107 let (levels, sse, bits, _) =
6108 luma.code_tx_depth(at, DC_PRED, 0, depth, Some(fi), search, fctx);
6109 let cost_f = sse
6110 + search.lambda
6111 * (bits
6112 + mode_bits[DC_PRED as usize]
6113 + one_bits
6114 + symbol_bits(&cdf::FILTER_INTRA_MODE, usize::from(fi))
6115 + if tx_select { tx_depth_bits(side, depth) } else { 0.0 });
6116 if cost_f < cost && best.as_ref().is_none_or(|b| cost_f < b.0) {
6117 best = Some((
6118 cost_f,
6119 fi,
6120 depth,
6121 luma.snapshot(x, y, side),
6122 coeffs(&levels, side),
6123 ));
6124 }
6125 }
6126 }
6127 if let Some((cost_f, fi, depth, snapshot, levels)) = best {
6128 cost = cost_f;
6129 mode = DC_PRED;
6130 angle_delta = 0;
6131 tx_depth = depth as u8;
6132 luma_coeffs = levels;
6133 luma.restore(x, y, side, &snapshot);
6134 filter_intra = Some(fi);
6135 } else {
6136 luma.restore(x, y, side, &kept);
6137 }
6138 }
6139
6140 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
6141 // planes; what it costs still counts towards the partition decision.
6142 let ([u, v], uv_mode, chroma_cost, palette_uv, cfl_alphas) =
6143 search_chroma(chroma, luma, (x, y), side, chroma_set, search, mode, fctx);
6144 cost += chroma_cost;
6145
6146 // The intrabc arm is priced against the WHOLE block -- luma and both
6147 // chroma planes, residual-free -- so it is compared after the chroma
6148 // search has added its own cost, not against the luma decision alone.
6149 if let Some(ibc) = ibc {
6150 if let Some((dv, cost_ibc, src)) =
6151 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
6152 {
6153 if cost_ibc < cost {
6154 ibc_commit(luma, chroma, (x, y), src, side);
6155 ibc.last_dv = Some(dv);
6156 ibc.hits += 1;
6157 return (
6158 BlockCoeffs {
6159 skip: true,
6160 dv: Some(dv),
6161 ..BlockCoeffs::default()
6162 },
6163 cost_ibc,
6164 );
6165 }
6166 }
6167 }
6168 // A palette or filter-intra block's luma was recoded through `DCT_DCT`
6169 // (its levels came from `code_from_prediction`), so the searched types
6170 // belong to a block this one no longer is.
6171 if palette.is_some() || filter_intra.is_some() {
6172 luma_tx_types = Vec::new();
6173 }
6174 (
6175 BlockCoeffs {
6176 u,
6177 v,
6178 luma: luma_coeffs,
6179 mode,
6180 uv_mode,
6181 tx_depth,
6182 palette,
6183 palette_uv,
6184 filter_intra,
6185 cfl_alphas,
6186 angle_delta_y: angle_delta as i8,
6187 luma_tx_types,
6188 ..BlockCoeffs::default()
6189 },
6190 cost,
6191 )
6192}
6193
6194/// The chroma modes the search offers, and the only ones it may offer: each
6195/// predicts from the row directly above and the column directly to the left
6196/// and nothing further, so none of them needs the above-right/below-left
6197/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
6198/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
6199/// reconstruction and its own alpha syntax; both are left out here.
6200const CHROMA_MODES: [u8; 7] = [
6201 DC_PRED,
6202 V_PRED,
6203 H_PRED,
6204 SMOOTH_PRED,
6205 SMOOTH_V_PRED,
6206 SMOOTH_H_PRED,
6207 PAETH_PRED,
6208];
6209
6210/// The thirteen intra mode names, for the chroma fire count's print.
6211#[cfg(test)]
6212const UV_MODE_NAMES: [&str; 14] = [
6213 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
6214 "SMOOTH_H", "PAETH", "CFL",
6215];
6216
6217/// How many blocks each chroma mode has won, indexed by the mode itself --
6218/// the fire count that says whether the search below reaches its candidates
6219/// at all (the `gate-blind-to-feature` class), printed once per gate run.
6220static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 14] =
6221 [const { std::sync::atomic::AtomicUsize::new(0) }; 14];
6222
6223/// How many blocks each CfL alpha magnitude (`1..=16`, indexed `mag - 1`) has
6224/// won, summed over both chroma planes -- the alpha histogram the gate prints
6225/// beside the CfL share (`gate-blind-to-feature`: a tool that fires at one
6226/// magnitude only is a search that never left its first candidate).
6227static CFL_ALPHA_HITS: [std::sync::atomic::AtomicUsize; 17] =
6228 [const { std::sync::atomic::AtomicUsize::new(0) }; 17];
6229
6230/// Reads [`CFL_ALPHA_HITS`] and zeroes it. Index 0 is "this plane took alpha
6231/// zero on a CfL block", `1..=16` the magnitudes.
6232#[cfg(test)]
6233pub(crate) fn take_cfl_alpha_hits() -> [usize; 17] {
6234 std::array::from_fn(|m| CFL_ALPHA_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6235}
6236
6237/// How many directional luma blocks won at each `angle_delta_y`, indexed
6238/// `delta + 3` -- the histogram that says whether the refinement below ever
6239/// leaves zero (`gate-blind-to-feature`).
6240static ANGLE_DELTA_HITS: [std::sync::atomic::AtomicUsize; 7] =
6241 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
6242
6243/// Reads [`ANGLE_DELTA_HITS`] and zeroes it.
6244#[cfg(test)]
6245pub(crate) fn take_angle_delta_hits() -> [usize; 7] {
6246 std::array::from_fn(|d| ANGLE_DELTA_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
6247}
6248
6249/// Whether the luma search refines a directional winner's `angle_delta_y`
6250/// (`EC_AV1_ANGLE=0` switches it off, the lane's own on/off pair).
6251fn angle_delta_on() -> bool {
6252 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6253 crate::envflags::var("EC_AV1_ANGLE").ok().map(|v| v != "0")
6254 });
6255 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::ANGLE))
6256}
6257
6258/// Whether the chroma search offers `UV_CFL_PRED` at all (`EC_AV1_CFL=0`
6259/// switches it off, which is how the lane measured its own on/off pair).
6260fn cfl_on() -> bool {
6261 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6262 crate::envflags::var("EC_AV1_CFL").ok().map(|v| v != "0")
6263 });
6264 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CFL))
6265}
6266
6267/// Whether the intra search offers the five recursive filter-intra modes at
6268/// all, and with them whether the sequence header sets `enable_filter_intra`
6269/// (`EC_AV1_FILTER_INTRA=0` switches both off, which is how the lane measured
6270/// its own on/off pair -- and how every byte pin written before it still
6271/// reproduces). It is also a speed lever: on at preset 0, off above it.
6272// lane-sb128: `use_128x128_superblock` (spec 5.5.1). `EC_AV1_SB128=0` turns
6273// it off for the whole process (a sequence-header field, so it cannot change
6274// mid-stream anyway), the same env-flag shape `EC_AV1_FILTER_INTRA` uses.
6275// NOT an `EncoderConfig` field: that struct is built by 90 literal sites in
6276// this workspace.
6277
6278/// Whether a sequence codes 128x128 superblocks when the environment says
6279/// nothing. ON since lane-b128 gave the 128 root a real `PARTITION_NONE`
6280/// candidate ([`search_root_128`]): with SPLIT-only roots the size was pure
6281/// cost (lane-sb128b measured film B +24.9 -> +37.5 vs libaom), and with the
6282/// 128x128 block in it every row of the native BD gate is down or flat on
6283/// both columns (BD-rate vs libaom cpu-6 / rav1e s6, 12 frames):
6284///
6285/// | row | 64 superblocks | 128 + the 128 root |
6286/// |---|---|---|
6287/// | bars 1080p | -3.1 / -18.7 | **-3.7 / -19.2** |
6288/// | bars 2160p | +9.1 / -13.3 | **+8.5 / -13.8** |
6289/// | film A | +20.3 / -5.0 | **+20.1 / -5.2** |
6290/// | film B | +24.6 / -2.0 | **+24.3 / -2.2** |
6291/// | screen capture | +14.6 / -33.2 | **+14.4 / -33.2** |
6292///
6293/// and the long-GOP gate agrees (film A +24.0/-7.6 -> +23.6/-7.9, film B
6294/// +85.8/+7.1 -> +85.1/+6.6). Both arms re-run on lane-b128m's own base.
6295///
6296/// ON since lane-b128m closed the eleven 128-superblock desyncs that held it
6297/// off (the delta_q unit at the 128 superblock, the superblock size travelling
6298/// with a `FrameCtx` copy into a tile search worker, the writer's intrabc DV
6299/// predictor and wavefront, and seven test harnesses that handed the encoder a
6300/// 64-superblock context). `EC_AV1_SB128=0` turns it off.
6301pub(crate) const SB128_DEFAULT: bool = true;
6302
6303/// Whether this process's sequences code 128x128 superblocks. An ENCODER
6304/// knob (like `speed::SPEED`), never read by a decode: read through a
6305/// process-global (not a thread-local) because the tile writers run on
6306/// worker threads; `2` is "the environment has not been read yet".
6307static ENC_SB128: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(2);
6308
6309/// Whether this process's sequences code 128x128 superblocks.
6310pub(crate) fn sb128_on() -> bool {
6311 use std::sync::atomic::Ordering::Relaxed;
6312 match ENC_SB128.load(Relaxed) {
6313 2 => {
6314 let on = crate::envflags::var("EC_AV1_SB128")
6315 .ok()
6316 .map_or(SB128_DEFAULT, |v| v != "0");
6317 ENC_SB128.store(u8::from(on), Relaxed);
6318 on
6319 }
6320 v => v == 1,
6321 }
6322}
6323
6324/// Forces [`sb128_on`] for the rest of the process -- the superblock size is
6325/// a SEQUENCE field, so a gate that flips it must run alone (`#[ignore]`),
6326/// exactly like the speed-preset gates.
6327#[cfg(test)]
6328pub(crate) fn force_sb128(on: bool) {
6329 ENC_SB128.store(u8::from(on), std::sync::atomic::Ordering::Relaxed);
6330}
6331
6332/// The luma loop-restoration unit size this sequence codes: a 128 superblock
6333/// cannot signal the 64 unit at all (spec `lr_params` reads ONE bit there,
6334/// `RESTORATION_TILESIZE_MAX >> (2 - (shift + 1))`, so the smallest unit is
6335/// 128), which is the one filter parameter the superblock size moves.
6336pub(crate) fn lr_unit() -> u32 {
6337 if sb128_on() { 128 } else { 64 }
6338}
6339
6340pub(crate) fn filter_intra_on() -> bool {
6341 #[cfg(test)]
6342 if let Some(forced) = FILTER_INTRA_FORCE.with(std::cell::Cell::get) {
6343 return forced;
6344 }
6345 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
6346 crate::envflags::var("EC_AV1_FILTER_INTRA").ok().map(|v| v != "0")
6347 });
6348 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::FILTER_INTRA))
6349}
6350
6351/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
6352/// to its own encode.
6353#[cfg(test)]
6354pub(crate) fn take_uv_mode_hits() -> [usize; 14] {
6355 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
6356}
6357
6358/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
6359/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
6360/// Returns each plane's levels, the mode, and what the pair cost (squared
6361/// error plus lambda times bits, the same currency the luma search speaks).
6362///
6363/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
6364/// which is what the luma mode decision was taken against, so what a
6365/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
6366/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
6367/// writer then has to code.
6368#[allow(clippy::too_many_arguments)]
6369/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
6370/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
6371/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
6372/// trials all seven, as before this lever.
6373///
6374/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
6375/// the search's largest trial population by far -- seven modes times two
6376/// planes for every intra block, against 3.7 luma trials -- and the RD
6377/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
6378/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
6379fn chroma_top_k() -> Option<usize> {
6380 static ENV: std::sync::LazyLock<Option<Option<usize>>> = std::sync::LazyLock::new(|| {
6381 crate::envflags::var("EC_AV1_CHROMA_K")
6382 .ok()
6383 .map(|v| v.parse::<usize>().ok().filter(|&k| k > 0))
6384 });
6385 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::CHROMA_K))
6386}
6387
6388/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
6389/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
6390/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
6391/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
6392/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
6393/// BD swings by about a point in either direction as near-tie chroma modes
6394/// flip, which is the measurement's own sensitivity, not a trend: nothing
6395/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
6396/// RE-MEASURED on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on:
6397/// K=4 is +17.1/-0.1, +47.1/+19.2, +51.6/-13.8 against the base's
6398/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3 -- every row worse. Still `None`.
6399pub(crate) const CHROMA_TOP_K: Option<usize> = None;
6400
6401fn search_chroma(
6402 chroma: &mut [Plane; 2],
6403 // The luma plane's RECONSTRUCTION under this block, already committed by
6404 // [`Plane::search_block`] -- the signal a `UV_CFL_PRED` candidate scales.
6405 luma: &Plane,
6406 (x, y): (usize, usize),
6407 side: usize,
6408 set: TxbSet,
6409 search: &Search,
6410 luma_mode: u8,
6411 fctx: &crate::decode::FrameCtx,
6412) -> (
6413 [Vec<Coeff>; 2],
6414 u8,
6415 f64,
6416 Option<crate::tile::PaletteUv>,
6417 Option<(i32, i32)>,
6418) {
6419 let at = At {
6420 x: x / 2,
6421 y: y / 2,
6422 side: side / 2,
6423 reach: Reach::none(),
6424 set,
6425 };
6426 // The census's cheap proxy for a chroma mode: the SAD of its prediction
6427 // summed over both planes, ranked by the same rule the luma histogram
6428 // uses. Only built under `EC_AV1_CENSUS`.
6429 // The SAD of each mode's prediction, summed over both planes -- the
6430 // census's ranking rule, and what [`chroma_top_k`] prunes by.
6431 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
6432 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6433 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
6434 u.iter()
6435 .zip(v.iter())
6436 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
6437 .collect()
6438 };
6439 let modes: Vec<u8> = match chroma_top_k() {
6440 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
6441 _ => CHROMA_MODES.to_vec(),
6442 };
6443 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
6444 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
6445 let ranking: Vec<(f64, u8)> = if census_on() {
6446 sad_scores(chroma)
6447 } else {
6448 Vec::new()
6449 };
6450 census_add(2, 1);
6451 census_add(3, modes.len());
6452 let mut best: Option<(f64, u8, Trial, Trial)> = None;
6453 for mode in modes {
6454 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
6455 if (V_PRED..=D67_PRED).contains(&mode) {
6456 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
6457 }
6458 // lane-i64: `av1_get_ext_tx_set_type` resolves a CHROMA plane at
6459 // `tx_size_sqr >= TX_32X32` to `EXT_TX_SET_DCTONLY`, so the 32x32
6460 // chroma of a 64x64 block is `DCT_DCT` whatever
6461 // `Intra_Mode_To_Tx_Type` says -- the decoder's own `side >= 32` arm
6462 // (decode.rs `read_chroma_plane`), and ADST is not even defined at 32
6463 // points.
6464 let tx_type = if at.side >= 32 {
6465 TxType::DctDct
6466 } else {
6467 crate::decode::default_intra_tx_type(mode)
6468 };
6469 let u = chroma[0].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6470 let v = chroma[1].trial_typed(at, mode, 0, search.base_q_idx, search.deadzone, tx_type, fctx);
6471 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
6472 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
6473 best = Some((cost, mode, u, v));
6474 }
6475 }
6476 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
6477 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
6478 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
6479 // what keeps `u_colors` ascending and distinct the way
6480 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
6481 // each cluster's own mean, since the colour-index map is SHARED by the
6482 // two planes. Priced against the best ordinary chroma mode above, so a
6483 // block only takes one when it beats it; a palette block's chroma mode is
6484 // `UV_DC_PRED` by construction.
6485 let mut palette_uv = None;
6486 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
6487 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
6488 let plane_source = |p: &Plane| -> Vec<u8> {
6489 (at.y..at.y + at.side)
6490 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
6491 .collect()
6492 };
6493 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
6494 // The luma on-screen extent carried into this plane exactly as the
6495 // reader does it (`decode::palette_onscreen_uv`); see the luma arm.
6496 let on_uv = crate::decode::palette_onscreen_uv(
6497 (side, side),
6498 (
6499 side.min(luma.true_width.saturating_sub(x)),
6500 side.min(luma.true_height.saturating_sub(y)),
6501 ),
6502 (at.side, at.side),
6503 );
6504 for mut pal in palette_candidates(&u_source) {
6505 let n = usize::from(pal.size);
6506 crate::decode::palette_replicate(&mut pal.map, at.side, at.side, on_uv);
6507 // V's base colour per cluster: the mean of the samples the shared
6508 // map assigns to it (an empty cluster cannot happen -- every
6509 // colour `palette_candidates` returns is some pixel's nearest).
6510 let mut sums = [0u32; 8];
6511 let mut counts = [0u32; 8];
6512 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
6513 let k = usize::from(i).min(n - 1);
6514 sums[k] += u32::from(sample);
6515 counts[k] += 1;
6516 }
6517 let mut v_colors = [0u16; 8];
6518 for k in 0..n {
6519 v_colors[k] = if counts[k] > 0 {
6520 ((sums[k] + counts[k] / 2) / counts[k]) as u16
6521 } else {
6522 0
6523 };
6524 }
6525 let candidate = crate::tile::PaletteUv {
6526 size: pal.size,
6527 u_colors: pal.colors,
6528 v_colors,
6529 map: pal.map,
6530 };
6531 let predict = |colors: &[u16; 8]| -> Vec<u8> {
6532 candidate
6533 .map
6534 .iter()
6535 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
6536 .collect()
6537 };
6538 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
6539 let u_trial = chroma[0].code_from_prediction(
6540 at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
6541 );
6542 let v_trial = chroma[1].code_from_prediction(
6543 at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
6544 );
6545 let cost_p = u_trial.sse
6546 + v_trial.sse
6547 + search.lambda
6548 * (u_trial.bits
6549 + v_trial.bits
6550 + crate::tile::palette_uv_bits(&candidate, side, on_uv));
6551 if cost_p < cost {
6552 cost = cost_p;
6553 mode = DC_PRED;
6554 u = u_trial;
6555 v = v_trial;
6556 palette_uv = Some(candidate);
6557 }
6558 }
6559 }
6560 // The chroma-from-luma arm (spec 5.11.45, libaom `cfl_rd_pick_alpha`):
6561 // `UV_CFL_PRED` predicts as `DC_PRED` (`get_uv_mode`, spec 9.3) and then
6562 // nudges every sample by `alpha_q3` times the block's subsampled,
6563 // average-subtracted luma reconstruction. Offered only where
6564 // `is_cfl_allowed` (spec 5.11.5) does -- a luma block at most 32x32 --
6565 // and priced against the best ordinary chroma mode above, palette
6566 // included, so a block only takes it when it beats both.
6567 let mut cfl_alphas = None;
6568 if side <= 32 && cfl_on() {
6569 // The AC signal, through the decoder's own
6570 // `cfl_luma_subsampling_420_lbd_c` + `subtract_average_c` body.
6571 let ac = crate::decode::cfl_ac_q3_at(x, y, side, side, |lx, ly| {
6572 i32::from(luma.reconstruction[ly * luma.width + lx])
6573 });
6574 let dc_prediction = |plane: &Plane| -> Vec<u8> {
6575 let (mut above_buf, mut left_buf) = ([0u8; 2 * SUPERBLOCK], [0u8; 2 * SUPERBLOCK]);
6576 let (above, left, corner) =
6577 plane.edges_into(at.x, at.y, at.side, at.reach, &mut above_buf, &mut left_buf);
6578 let mut prediction = vec![0u8; at.side * at.side];
6579 intra_predict_u8(
6580 DC_PRED, 0, above, left, corner, at.side, at.side, false, false, &mut prediction,
6581 fctx,
6582 );
6583 prediction
6584 };
6585 let bases = [dc_prediction(&chroma[0]), dc_prediction(&chroma[1])];
6586 // `av1_cfl_predict_block` (cfl.c): clip the nudged prediction, then
6587 // add the residual -- which is what [`Plane::code_from_prediction`]
6588 // does with what this returns.
6589 let apply = |base: &[u8], alpha: i32| -> Vec<u8> {
6590 base.iter()
6591 .zip(ac.iter())
6592 .map(|(&b, &a)| {
6593 (i32::from(b) + crate::decode::cfl_scaled(alpha, a)).clamp(0, 255) as u8
6594 })
6595 .collect()
6596 };
6597 // The least-squares alpha, then its two neighbours: minimising
6598 // `sum (source - base - alpha*ac/64)^2` over a continuous alpha is one
6599 // dot-product ratio, and the quantised optimum is one of the two
6600 // integers around it (the clamp and the Q6 rounding are what the SSE
6601 // check below re-decides). libaom sweeps all sixteen magnitudes under
6602 // full RD; three predictions per plane buy nearly the same alpha for a
6603 // thirtieth of the search.
6604 let pick_alpha = |plane: &Plane, base: &[u8]| -> i32 {
6605 let (mut num, mut den) = (0.0f64, 0.0f64);
6606 for row in 0..at.side {
6607 for col in 0..at.side {
6608 let i = row * at.side + col;
6609 let d = f64::from(plane.source[(at.y + row) * plane.width + at.x + col])
6610 - f64::from(base[i]);
6611 num += d * f64::from(ac[i]);
6612 den += f64::from(ac[i]) * f64::from(ac[i]);
6613 }
6614 }
6615 if den == 0.0 {
6616 return 0;
6617 }
6618 let ideal = 64.0 * num / den;
6619 let mut best = (plane.block_sse(at.x, at.y, at.side, base), 0i32);
6620 for alpha in [ideal.floor() as i64, ideal.ceil() as i64] {
6621 let alpha = alpha.clamp(-16, 16) as i32;
6622 if alpha == 0 {
6623 continue;
6624 }
6625 let sse = plane.block_sse(at.x, at.y, at.side, &apply(base, alpha));
6626 if sse < best.0 {
6627 best = (sse, alpha);
6628 }
6629 }
6630 best.1
6631 };
6632 let picked = [
6633 pick_alpha(&chroma[0], &bases[0]),
6634 pick_alpha(&chroma[1], &bases[1]),
6635 ];
6636 if picked != [0, 0] {
6637 let cfl_bits = symbol_bits(uv_cdf, crate::tile::UV_CFL_PRED) - dc_bits;
6638 let trial = |plane_idx: usize, alpha: i32| -> Trial {
6639 let prediction = if alpha == 0 {
6640 bases[plane_idx].clone()
6641 } else {
6642 apply(&bases[plane_idx], alpha)
6643 };
6644 chroma[plane_idx].code_from_prediction(
6645 at.x,
6646 at.y,
6647 at.side,
6648 &prediction,
6649 false,
6650 search.base_q_idx,
6651 search.deadzone,
6652 set,
6653 )
6654 };
6655 // At least one alpha must be nonzero: `cfl_alpha_signs` has no
6656 // (ZERO, ZERO) joint value ([`crate::tile::cfl_joint_sign`]).
6657 let combos: [(i32, i32); 3] = [
6658 (picked[0], picked[1]),
6659 (picked[0], 0),
6660 (0, picked[1]),
6661 ];
6662 for &(alpha_u, alpha_v) in &combos {
6663 if (alpha_u, alpha_v) == (0, 0) {
6664 continue;
6665 }
6666 let cu = trial(0, alpha_u);
6667 let cv = trial(1, alpha_v);
6668 let bits =
6669 cfl_bits + crate::tile::cfl_alpha_bits(alpha_u, alpha_v) + cu.bits + cv.bits;
6670 let cost_cfl = cu.sse + cv.sse + search.lambda * bits;
6671 if cost_cfl < cost {
6672 cost = cost_cfl;
6673 mode = crate::tile::UV_CFL_PRED as u8;
6674 u = cu;
6675 v = cv;
6676 palette_uv = None;
6677 cfl_alphas = Some((alpha_u, alpha_v));
6678 }
6679 }
6680 }
6681 }
6682 if let Some((alpha_u, alpha_v)) = cfl_alphas {
6683 for alpha in [alpha_u, alpha_v] {
6684 CFL_ALPHA_HITS[alpha.unsigned_abs() as usize]
6685 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6686 }
6687 }
6688 if census_on() {
6689 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
6690 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6691 }
6692 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6693 chroma[0].commit(at.x, at.y, at.side, &u);
6694 chroma[1].commit(at.x, at.y, at.side, &v);
6695 (
6696 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
6697 mode,
6698 cost,
6699 palette_uv,
6700 cfl_alphas,
6701 )
6702}
6703
6704/// Codes one leaf of a straddling quadrant as whichever costs least of intra
6705/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
6706/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
6707/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
6708/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
6709/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
6710/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
6711/// attempted here: these leaves only ever fill the sliver of real content a
6712/// true edge lands in the middle of a larger block, not a leaf worth a full
6713/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
6714/// (see `write_inter_frame_leaf`'s doc comment).
6715#[allow(clippy::too_many_arguments)]
6716/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
6717/// as [`code_square_inter`] wants them: empty on a frame that codes no
6718/// `reference_select`, or when the leaf compound candidates are switched off.
6719/// One helper because THREE leaf call sites need it -- the split quadrants
6720/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
6721/// `&[]` and so coded no compound block anywhere along the frame's true edge.
6722#[allow(clippy::too_many_arguments)]
6723fn leaf_compound_stacks<'a>(
6724 grid: &MiGrid,
6725 mi_row: usize,
6726 mi_col: usize,
6727 bw4: usize,
6728 bh4: usize,
6729 mi_cols: usize,
6730 mi_rows: usize,
6731 reference_select: bool,
6732 golden: Option<&'a Picture>,
6733 altref: Option<&'a Picture>,
6734) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
6735 if !(reference_select && leaf_compound()) {
6736 return Vec::new();
6737 }
6738 [
6739 (crate::mvstack::GOLDEN_FRAME, golden),
6740 (crate::mvstack::ALTREF_FRAME, altref),
6741 ]
6742 .into_iter()
6743 .filter_map(|(r, pic)| {
6744 pic.map(|p| {
6745 (
6746 r,
6747 p,
6748 crate::mvstack::find_mv_stack_compound(
6749 grid, mi_row, mi_col, bw4, bh4,
6750 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6751 grid.sign_bias_table(), &[(0, 0); 7], None,
6752 ),
6753 )
6754 })
6755 })
6756 .collect()
6757}
6758
6759/// The OBMC prediction of one square single-reference block: this block's own
6760/// translation prediction (`mc::predict`) with every bordering above/left
6761/// neighbour blended into the overlap strips by the DECODER's own plan and
6762/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
6763/// the search prices is what a decoder reconstructs -- never a second
6764/// implementation of the blend. `None` when the block has no overlappable
6765/// neighbour at all (the writer would then code no `motion_mode` symbol) or
6766/// when the plan cannot be built (a neighbour naming a reference this encode
6767/// does not hold).
6768#[allow(clippy::too_many_arguments)]
6769fn obmc_prediction(
6770 grid: &MiGrid,
6771 (mi_row, mi_col): (usize, usize),
6772 (mi_rows, mi_cols): (usize, usize),
6773 (x, y): (usize, usize),
6774 side: usize,
6775 mv: (i32, i32),
6776 refs: &[Option<&Picture>; 8],
6777 // This block's OWN reference planes, luma then both chroma, each as
6778 // (samples, stride, true width, true height).
6779 ref_planes: [(&[u16], usize, usize, usize); 3],
6780 frame_width: usize,
6781 fctx: &crate::decode::FrameCtx,
6782) -> Option<[Vec<u8>; 3]> {
6783 let n4 = side / 4;
6784 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
6785 return None;
6786 }
6787 let refpix = crate::decode::RefPix::ready(*refs);
6788 let plan = crate::decode::obmc_plan(
6789 grid,
6790 &[],
6791 &[],
6792 mi_row,
6793 mi_col,
6794 n4,
6795 n4,
6796 mi_rows,
6797 mi_cols,
6798 side,
6799 side,
6800 side,
6801 side / 2,
6802 x,
6803 y,
6804 x / 2,
6805 y / 2,
6806 &refpix,
6807 Some(fctx.interp_filter.get()),
6808 frame_width,
6809 )
6810 .ok()?;
6811 let mut pred = [
6812 vec![0u16; side * side],
6813 vec![0u16; side * side / 4],
6814 vec![0u16; side * side / 4],
6815 ];
6816 for (i, r) in ref_planes.into_iter().enumerate() {
6817 let luma_plane = i == 0;
6818 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
6819 let s = if luma_plane { side } else { side / 2 };
6820 mc::predict(
6821 r.0,
6822 r.1,
6823 r.2,
6824 r.3,
6825 mv_to_q4(px, mv.1, luma_plane),
6826 mv_to_q4(py, mv.0, luma_plane),
6827 s,
6828 s,
6829 &mut pred[i],
6830 fctx,
6831 );
6832 }
6833 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
6834 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
6835 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
6836 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
6837}
6838
6839fn code_square_inter(
6840 luma: &mut Plane,
6841 chroma: &mut [Plane; 2],
6842 (x, y): (usize, usize),
6843 side: usize,
6844 search: &Search,
6845 mode_bits: &[f64; 13],
6846 reference: &Picture,
6847 stack: &MvStack,
6848 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
6849 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
6850 // `reference_select`, and at the straddling call sites).
6851 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
6852 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
6853 // (`record_mi`, in the writer's own coding order) and this leaf's place in
6854 // it -- what the OBMC candidate's eligibility walk and neighbour plan
6855 // read, the same state the tile writer reads when it codes the leaf's
6856 // `motion_mode` symbol.
6857 grid: &MiGrid,
6858 (mi_row, mi_col): (usize, usize),
6859 (mi_rows, mi_cols): (usize, usize),
6860 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
6861 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
6862 refs: &[Option<&Picture>; 8],
6863 fctx: &crate::decode::FrameCtx,
6864) -> (BlockCoeffs, f64) {
6865 let (intra_block, intra_cost) =
6866 code_square(
6867 luma,
6868 chroma,
6869 (x, y),
6870 side,
6871 search,
6872 mode_bits,
6873 tx_select() && tx_select_inter(),
6874 None,
6875 false,
6876 fctx,
6877 );
6878 let luma_set = if side == 8 {
6879 TxbSet::Luma8Inter
6880 } else {
6881 TxbSet::Luma16Inter
6882 };
6883 let chroma_set = if side == 8 {
6884 TxbSet::Chroma4
6885 } else {
6886 TxbSet::Chroma8
6887 };
6888
6889 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
6890 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
6891 let single_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
6892 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
6893 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
6894 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
6895
6896 let mv = stack.nearest_mv;
6897 let ref_luma = (
6898 &reference.y,
6899 reference.width,
6900 luma.true_width,
6901 luma.true_height,
6902 );
6903 let ref_u = (
6904 &reference.u,
6905 reference.width / 2,
6906 chroma[0].true_width,
6907 chroma[0].true_height,
6908 );
6909 let ref_v = (
6910 &reference.v,
6911 reference.width / 2,
6912 chroma[1].true_width,
6913 chroma[1].true_height,
6914 );
6915 let luma_trial = mc_trial(
6916 luma,
6917 x,
6918 y,
6919 side,
6920 mv,
6921 true,
6922 ref_luma.0,
6923 ref_luma.1,
6924 ref_luma.2,
6925 ref_luma.3,
6926 false,
6927 search.base_q_idx,
6928 search.deadzone,
6929 luma_set, fctx,
6930 );
6931 let u = mc_trial(
6932 &chroma[0],
6933 x / 2,
6934 y / 2,
6935 side / 2,
6936 mv,
6937 false,
6938 ref_u.0,
6939 ref_u.1,
6940 ref_u.2,
6941 ref_u.3,
6942 false,
6943 search.base_q_idx,
6944 search.deadzone,
6945 chroma_set, fctx,
6946 );
6947 let v = mc_trial(
6948 &chroma[1],
6949 x / 2,
6950 y / 2,
6951 side / 2,
6952 mv,
6953 false,
6954 ref_v.0,
6955 ref_v.1,
6956 ref_v.2,
6957 ref_v.3,
6958 false,
6959 search.base_q_idx,
6960 search.deadzone,
6961 chroma_set, fctx,
6962 );
6963 let skip = luma_trial.levels.iter().all(|&l| l == 0)
6964 && u.levels.iter().all(|&l| l == 0)
6965 && v.levels.iter().all(|&l| l == 0);
6966 let inter_cost = luma_trial.sse
6967 + u.sse
6968 + v.sse
6969 + search.lambda
6970 * (skip_bits(skip)
6971 + intra_inter_bits(true)
6972 + single_ref_bits
6973 + mode_bits_inter
6974 + if skip {
6975 0.0
6976 } else {
6977 luma_trial.bits + u.bits + v.bits
6978 });
6979
6980 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
6981 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
6982 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
6983 // scan's own coverage already reached as far) but a real gap at 4-mi
6984 // leaf geometry. r3 ported the extended scan and, while proving it a
6985 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
6986 // `mvstack.rs`), found and fixed a second bug the extended scan's
6987 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
6988 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
6989 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
6990 // regardless of whether it also casts a ref-frame-matching vote) --
6991 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
6992 // branches), which is what made 8-mi geometry a true no-op instead of
6993 // one that only held when every neighbour happened to be inter.
6994 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
6995 // only ever took the stack's NEARESTMV candidate or went intra, so a
6996 // 32x32 block splitting because its four quarters MOVE differently could
6997 // not code the movement it split for. Same candidate `search_inter_block`
6998 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
6999 // a vector the residual syntax can name -- at this leaf's own side.
7000 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
7001 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
7002 // re-price below can hand it back as the winner's own mode info.
7003 let nearest_info = InterInfo {
7004 ref1: None,
7005 mv1: (0, 0),
7006 ref_frame: crate::mvstack::LAST_FRAME,
7007 mode: InterMode::NearestMv,
7008 mv,
7009 ref_mv_idx: 0,
7010 };
7011 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
7012 // syntax, apart from its residual: the OBMC candidate re-prices the same
7013 // syntax against a different prediction, so both sides of that comparison
7014 // carry it.
7015 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
7016 // This leaf's own `NEWMV` vector, kept whether or not it won the
7017 // single-reference comparison: it seeds the compound half-new candidate
7018 // below, exactly as `search_inter_block` seeds its own from the searches
7019 // it already ran.
7020 let mut searched_new: Option<(i32, i32)> = None;
7021 // What that search cost, kept for the second reference's own early-out
7022 // below (`None` when this leaf ran no search at all).
7023 let mut searched_new_cost: Option<f64> = None;
7024 let source_block = luma.source_block(x, y, side);
7025 if leaf_new_mv() {
7026 let (seeds, seed_n) = mv_seeds(stack);
7027 let found = motion::search(
7028 ref_luma.0,
7029 ref_luma.1,
7030 ref_luma.2,
7031 ref_luma.3,
7032 &source_block,
7033 x,
7034 y,
7035 side,
7036 side,
7037 stack.pred_mv,
7038 &seeds[..seed_n],
7039 search.lambda, fctx,
7040 1,
7041 );
7042 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
7043 searched_new_cost = Some(found.cost);
7044 let mv_residual = mv_residual_bits(new_mv, stack.pred_mv);
7045 if mv_residual.is_none() {
7046 // lane-newmv: a vector the writer cannot name never reaches RD.
7047 newmv_census_block(side, false, f64::INFINITY, best.0, new_mv, stack.nearest_mv, 0.0);
7048 }
7049 if let Some(mv_bits) = mv_residual {
7050 searched_new = Some(new_mv);
7051 // Same reuse as `search_inter_block`: a NEWMV equal to the
7052 // stack's NEARESTMV is the same three trials, already run above.
7053 let (luma_new, u_new, v_new) = if new_mv == mv {
7054 (luma_trial.clone(), u.clone(), v.clone())
7055 } else {
7056 (
7057 mc_trial(
7058 luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2,
7059 ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx,
7060 ),
7061 mc_trial(
7062 &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1,
7063 ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set,
7064 fctx,
7065 ),
7066 mc_trial(
7067 &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1,
7068 ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set,
7069 fctx,
7070 ),
7071 )
7072 };
7073 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
7074 && u_new.levels.iter().all(|&l| l == 0)
7075 && v_new.levels.iter().all(|&l| l == 0);
7076 let drl_bits = if stack.entries.len() > 1 {
7077 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
7078 } else {
7079 0.0
7080 };
7081 let cost_new = luma_new.sse
7082 + u_new.sse
7083 + v_new.sse
7084 + search.lambda
7085 * (skip_bits(skip_new)
7086 + intra_inter_bits(true)
7087 + single_ref_bits
7088 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7089 + drl_bits
7090 + mv_bits
7091 + mv_rate_surcharge(mv_bits)
7092 + if skip_new {
7093 0.0
7094 } else {
7095 luma_new.bits + u_new.bits + v_new.bits
7096 });
7097 newmv_census_block(side, true, cost_new, best.0, new_mv, stack.nearest_mv, mv_bits);
7098 if cost_new < best.0 {
7099 single_syntax = intra_inter_bits(true)
7100 + single_ref_bits
7101 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
7102 + drl_bits
7103 + mv_bits;
7104 best = (
7105 cost_new,
7106 Some((
7107 luma_new,
7108 u_new,
7109 v_new,
7110 skip_new,
7111 InterInfo {
7112 ref1: None,
7113 mv1: (0, 0),
7114 ref_frame: crate::mvstack::LAST_FRAME,
7115 mode: InterMode::NewMv,
7116 mv: new_mv,
7117 ref_mv_idx: 0,
7118 },
7119 )),
7120 );
7121 }
7122 }
7123 }
7124
7125 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
7126 // `search_inter_block` prices for a whole 32x32 block:
7127 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
7128 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
7129 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
7130 // too. Priced with the same static-CDF approximation, plus the
7131 // compound-only syntax the writer emits.
7132 for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) {
7133 let (ref1, g) = (*ref1, *g);
7134 // The whole `comp_mode` + reference-pair tree at the writer's own
7135 // contexts, for THIS pair (lane-ctx).
7136 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
7137 let mode_ctx =
7138 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
7139 let mode_bits_of =
7140 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
7141 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
7142 (
7143 cstack.nearest_mv,
7144 mode_bits_of(0),
7145 InterInfo {
7146 ref_frame: crate::mvstack::LAST_FRAME,
7147 mode: InterMode::NearestNearestMv,
7148 mv: cstack.nearest_mv.0,
7149 mv1: cstack.nearest_mv.1,
7150 ref1: Some(ref1),
7151 ref_mv_idx: 0,
7152 },
7153 ),
7154 (
7155 ((0, 0), (0, 0)),
7156 mode_bits_of(6),
7157 InterInfo {
7158 ref_frame: crate::mvstack::LAST_FRAME,
7159 mode: InterMode::GlobalGlobalMv,
7160 mv: (0, 0),
7161 mv1: (0, 0),
7162 ref1: Some(ref1),
7163 ref_mv_idx: 0,
7164 },
7165 ),
7166 ];
7167 // Every compound MV residual here is priced against compound stack
7168 // entry 0, which is what `assign_compound_mv` predicts from at
7169 // `ref_mv_idx = 0` -- so it is also what the second-reference search
7170 // below seeds from and rounds to, and no candidate it finds can then
7171 // fail `mv_residual_bits`.
7172 let cbase = cstack
7173 .entries
7174 .first()
7175 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
7176 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
7177 // it a leaf could only name a stack vector for the second half, and
7178 // screen capture showed the consequence: every leaf compound block
7179 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
7180 // extra-reference `NEWMV`, when this reference's own
7181 // `NEAREST_NEARESTMV` vector already prices `margin` times better
7182 // than the `LAST` search of this same leaf did -- one candidate
7183 // evaluation standing in for a whole search.
7184 let margin = leaf_second_new_margin();
7185 let mut second_new: Option<(i32, i32)> = None;
7186 if leaf_second_new_mv() {
7187 newmv_census_global(2);
7188 let skip = margin > 0.0
7189 && searched_new_cost.is_some_and(|last| {
7190 motion::cost_at(
7191 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y,
7192 side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx,
7193 ) * margin
7194 <= last
7195 });
7196 if skip {
7197 newmv_census_global(3);
7198 }
7199 if !skip {
7200 let mut seeds = [(0, 0); 4];
7201 let mut seed_n = 1;
7202 for e in cstack.entries.iter().take(3) {
7203 seeds[seed_n] = e.mv1;
7204 seed_n += 1;
7205 }
7206 let found = motion::search(
7207 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side,
7208 side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1),
7209 );
7210 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
7211 }
7212 }
7213 if let Some(new_mv) = searched_new {
7214 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
7215 ccands.push((
7216 (new_mv, cstack.nearest_mv.1),
7217 mode_bits_of(3) + b0,
7218 InterInfo {
7219 ref_frame: crate::mvstack::LAST_FRAME,
7220 mode: InterMode::NewNearestMv,
7221 mv: new_mv,
7222 mv1: cstack.nearest_mv.1,
7223 ref1: Some(ref1),
7224 ref_mv_idx: 0,
7225 },
7226 ));
7227 }
7228 }
7229 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
7230 // searches this leaf ran, each residual priced against `cbase`.
7231 if let Some(mv1) = second_new {
7232 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
7233 ccands.push((
7234 (cstack.nearest_mv.0, mv1),
7235 mode_bits_of(2) + b1,
7236 InterInfo {
7237 ref_frame: crate::mvstack::LAST_FRAME,
7238 mode: InterMode::NearestNewMv,
7239 mv: cstack.nearest_mv.0,
7240 mv1,
7241 ref1: Some(ref1),
7242 ref_mv_idx: 0,
7243 },
7244 ));
7245 if let Some((new_mv, b0)) =
7246 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
7247 {
7248 ccands.push((
7249 (new_mv, mv1),
7250 mode_bits_of(7) + b0 + b1,
7251 InterInfo {
7252 ref_frame: crate::mvstack::LAST_FRAME,
7253 mode: InterMode::NewNewMv,
7254 mv: new_mv,
7255 mv1,
7256 ref1: Some(ref1),
7257 ref_mv_idx: 0,
7258 },
7259 ));
7260 }
7261 }
7262 }
7263 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
7264 ccands.dedup_by_key(|c| c.0);
7265 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
7266 let g_u = (
7267 g.u.as_slice(),
7268 g.width / 2,
7269 chroma[0].true_width,
7270 chroma[0].true_height,
7271 );
7272 let g_v = (
7273 g.v.as_slice(),
7274 g.width / 2,
7275 chroma[1].true_width,
7276 chroma[1].true_height,
7277 );
7278 for (mvs, bits, info) in ccands {
7279 let luma_c = mc_trial_compound(
7280 luma, x, y, side, mvs, true,
7281 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
7282 search.base_q_idx, search.deadzone, luma_set, fctx,
7283 );
7284 let u_c = mc_trial_compound(
7285 &chroma[0], x / 2, y / 2, side / 2, mvs, false,
7286 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
7287 search.base_q_idx, search.deadzone, chroma_set, fctx,
7288 );
7289 let v_c = mc_trial_compound(
7290 &chroma[1], x / 2, y / 2, side / 2, mvs, false,
7291 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
7292 search.base_q_idx, search.deadzone, chroma_set, fctx,
7293 );
7294 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
7295 && u_c.levels.iter().all(|&l| l == 0)
7296 && v_c.levels.iter().all(|&l| l == 0);
7297 let cost_c = luma_c.sse
7298 + u_c.sse
7299 + v_c.sse
7300 + search.lambda
7301 * (skip_bits(skip_c)
7302 + intra_inter_bits(true)
7303 + bits
7304 + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
7305 if cost_c < best.0 {
7306 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
7307 }
7308 }
7309 }
7310
7311 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
7312 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
7313 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
7314 // the writer codes no symbol for one. The prediction is the decoder's own
7315 // plan and blend over the neighbours this leaf's `grid` already carries
7316 // (published by `record_mi` in the writer's coding order), so the
7317 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
7318 // offered this only at 32x32, which is not where libaom cashes its OBMC
7319 // gain.
7320 let mut motion_won = 0u8;
7321 let single = match &best.1 {
7322 None => Some(nearest_info),
7323 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
7324 Some(_) => None,
7325 };
7326 if let Some(info) = single.filter(|i| {
7327 (crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on())
7328 && i.ref_frame == crate::mvstack::LAST_FRAME
7329 }) {
7330 let planes = [
7331 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7332 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7333 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7334 ];
7335 // Which alphabet this block's writer will code the symbol against
7336 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
7337 // 3-symbol one only under `allow_warped_motion` and at least one warp
7338 // sample. Mirrored here so the candidates are priced against the
7339 // table the tile really narrows.
7340 let warp_alphabet = warp_on()
7341 && crate::decode::num_proj_ref(
7342 grid,
7343 mi_row,
7344 mi_col,
7345 side / 4,
7346 side / 4,
7347 mi_cols,
7348 mi_rows,
7349 info.ref_frame,
7350 fctx,
7351 ) >= 1;
7352 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
7353 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
7354 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
7355 if let Some(pred) = obmc_prediction(
7356 grid,
7357 (mi_row, mi_col),
7358 (mi_rows, mi_cols),
7359 (x, y),
7360 side,
7361 info.mv,
7362 refs,
7363 planes,
7364 reference.width,
7365 fctx,
7366 ) {
7367 candidates.push((1, pred));
7368 }
7369 }
7370 if warp_alphabet {
7371 if let Some(pred) = warp_prediction(
7372 grid,
7373 (mi_row, mi_col),
7374 (mi_rows, mi_cols),
7375 (x, y),
7376 side,
7377 info.mv,
7378 info.ref_frame,
7379 planes,
7380 fctx,
7381 ) {
7382 candidates.push((2, pred));
7383 }
7384 }
7385 for (motion, pred) in candidates {
7386 let luma_o = luma.code_from_prediction(
7387 x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set,
7388 );
7389 let u_o = chroma[0].code_from_prediction(
7390 x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone,
7391 chroma_set,
7392 );
7393 let v_o = chroma[1].code_from_prediction(
7394 x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone,
7395 chroma_set,
7396 );
7397 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
7398 && u_o.levels.iter().all(|&l| l == 0)
7399 && v_o.levels.iter().all(|&l| l == 0);
7400 let cost_o = luma_o.sse
7401 + u_o.sse
7402 + v_o.sse
7403 + search.lambda
7404 * (skip_bits(skip_o)
7405 + single_syntax
7406 + mm(motion)
7407 + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits });
7408 // The incumbent pays the motion_mode symbol IT would code, so
7409 // both sides of the comparison carry that syntax.
7410 if cost_o < best.0 + search.lambda * mm(motion_won) {
7411 motion_won = motion;
7412 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
7413 }
7414 }
7415 }
7416
7417 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
7418 if cost < intra_cost {
7419 // A compound winner commits the flat trial it was priced from:
7420 // `commit_inter_luma`'s var-tx trial set is single-reference
7421 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
7422 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
7423 // predicting each half-side trial from BOTH references, verified
7424 // byte-identical to this when its split is disabled) and MEASURED
7425 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
7426 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
7427 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
7428 // compound block's residual is small enough that the four extra
7429 // per-unit txb_skip/eob symbols cost more ladder bytes than this
7430 // encoder's static-CDF estimate prices them at, so the local RD
7431 // win does not convert. lane-av1txbits REBUILT it on top of a
7432 // search that prices against the tables the frame is really
7433 // written with (`tile::arm_pricing_cdfs`, the estimate error on
7434 // these very blocks measured down from +31% to +3%) and measured
7435 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
7436 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
7437 // same build without it. The static-CDF estimate was NOT what
7438 // held the compound var-tx trial back. The flat trial stays.
7439 // An OBMC winner commits the flat trial too: `commit_inter_luma`
7440 // re-predicts each var-tx unit by plain translation, which is not
7441 // the prediction this candidate was priced from.
7442 // lane-av1txdepth REBUILT the compound trial set at LAMBDA_SCALE
7443 // 0.05 (both rejections above were measured at 0.1, the weight
7444 // the lambda lane showed was 2x too heavy): a compound winner is
7445 // offered the same var-tx split, its units predicted from BOTH
7446 // references (`mc_trial_compound`). RE-MEASURED native: film
7447 // 1080p +16.0/-1.1, film 2160p +46.6/+18.8, screen +51.4/-14.4
7448 // against the +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 with it off --
7449 // one row 0.2 down, two flat, short of the two-down-one-flat keep
7450 // rule, so it stays behind `EC_AV1_COMP_VARTX` (default OFF)
7451 // rather than change the default on a single 0.2 row. It fires:
7452 // 37.0% / 11.1% / 32.9% of the compound blocks split. 640x384 for
7453 // the record: +70.5/+84.0/+48.9 and +28.9/+46.2/-3.7 against
7454 // +70.4/+85.3/+48.5 and +28.4/+47.4/-4.0 -- the 4K film row is
7455 // 1.3/1.2 down there, which is where the upgrade path is if this
7456 // is picked up again.
7457 let second = info.ref1.filter(|_| motion_won == 0).and_then(|r| {
7458 refs[r as usize].map(|g| {
7459 (
7460 info.mv1,
7461 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
7462 )
7463 })
7464 });
7465 let (levels, tx_depth, dcost, luma_tx_types) = if motion_won != 0
7466 || (info.ref1.is_some() && second.is_none())
7467 {
7468 luma.commit(x, y, side, &luma_new);
7469 (luma_new.levels.clone(), 0, 0.0, Vec::new())
7470 } else {
7471 commit_inter_luma(
7472 luma, (x, y), side, info.mv,
7473 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7474 search, &luma_new, skip_new, second, fctx,
7475 )
7476 };
7477 // lane-txrd: chroma follows the luma type the search just chose.
7478 let [u_new, v_new] = match luma_tx_types.first().copied() {
7479 Some(t) => recode_inter_chroma(
7480 chroma, (x, y), side, info.mv,
7481 [
7482 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7483 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7484 ],
7485 info.ref1.filter(|_| motion_won == 0).and_then(|r| {
7486 refs[r as usize].map(|g| {
7487 (
7488 info.mv1,
7489 [
7490 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
7491 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
7492 ],
7493 )
7494 })
7495 }),
7496 search, chroma_set, t, fctx,
7497 )
7498 .unwrap_or([u_new, v_new]),
7499 None => [u_new, v_new],
7500 };
7501 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
7502 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
7503 return (
7504 BlockCoeffs {
7505 angle_delta_y: 0,
7506 cfl_alphas: None,
7507 filter_intra: None,
7508 luma: coeffs(&levels, side),
7509 u: coeffs(&u_new.levels, side / 2),
7510 v: coeffs(&v_new.levels, side / 2),
7511 mode: DC_PRED as u8,
7512 uv_mode: DC_PRED,
7513 skip: skip_new,
7514 eight: None,
7515 dv: None,
7516 palette: None,
7517 palette_uv: None,
7518 tx_depth,
7519 luma_tx_types,
7520 inter: Some(info),
7521 motion_mode: motion_won,
7522 },
7523 cost + dcost,
7524 );
7525 }
7526 }
7527
7528 census_add(8, 1);
7529 if skip {
7530 census_add(10, 1);
7531 }
7532 if inter_cost >= intra_cost {
7533 census_add(9, 1);
7534 }
7535 if inter_cost < intra_cost {
7536 let (levels, tx_depth, dcost, luma_tx_types) = commit_inter_luma(
7537 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,
7538 );
7539 // lane-txrd: chroma follows the luma type (this tail's block is
7540 // single-reference `NEARESTMV`, so no compound second half).
7541 let [u, v] = match luma_tx_types.first().copied() {
7542 Some(t) => recode_inter_chroma(
7543 chroma, (x, y), side, mv,
7544 [
7545 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7546 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7547 ],
7548 None, search, chroma_set, t, fctx,
7549 )
7550 .unwrap_or([u, v]),
7551 None => [u, v],
7552 };
7553 chroma[0].commit(x / 2, y / 2, side / 2, &u);
7554 chroma[1].commit(x / 2, y / 2, side / 2, &v);
7555 (BlockCoeffs {
7556 luma_tx_types,
7557 angle_delta_y: 0,
7558 cfl_alphas: None,
7559 filter_intra: None,
7560 luma: coeffs(&levels, side),
7561 u: coeffs(&u.levels, side / 2),
7562 v: coeffs(&v.levels, side / 2),
7563 mode: DC_PRED as u8,
7564 uv_mode: DC_PRED,
7565 skip,
7566 eight: None,
7567 dv: None,
7568 palette: None,
7569 palette_uv: None,
7570 tx_depth,
7571 motion_mode: 0,
7572 inter: Some(InterInfo {
7573 ref1: None,
7574 mv1: (0, 0),
7575 ref_frame: crate::mvstack::LAST_FRAME,
7576 mode: InterMode::NearestMv,
7577 mv,
7578 ref_mv_idx: 0,
7579 }),
7580 }, inter_cost + dcost)
7581 } else {
7582 (intra_block, intra_cost)
7583 }
7584}
7585
7586/// Publishes one coded inter-frame block into the `mi` grid the next block's
7587/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
7588/// block casts no vote but is still a coded cell (see `code_square_inter`'s
7589/// note on `processed_rows`/`processed_cols`).
7590fn record_mi(
7591 grid: &mut MiGrid,
7592 mi_row: usize,
7593 mi_col: usize,
7594 size: u8,
7595 inter: Option<InterInfo>,
7596 // lane-ctx: the block's own `skip`, so the next block's MV stack can hand
7597 // the RD pricer the two cells the writer's `skip_ctx` sums.
7598 skip: bool,
7599) {
7600 let info = match inter {
7601 Some(info) => MiInfo {
7602 is_inter: true,
7603 ref_frame: info.ref_frame,
7604 // A COMPOUND block votes with BOTH of its references and both of
7605 // its vectors, exactly as the tile writer publishes it: recording
7606 // a compound block as a single-reference one here left the
7607 // encoder's own grid disagreeing with the writer's from the first
7608 // compound block on, so every later stack it searched against was
7609 // not the stack the decoder derives.
7610 ref_frame1: info.ref1.unwrap_or(NO_REF1),
7611 mv1: mv16(info.mv1),
7612 mv: mv16(info.mv),
7613 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
7614 // side, compound modes 2/3/7 on the other.
7615 is_new_mv: matches!(
7616 info.mode,
7617 InterMode::NewMv
7618 | InterMode::NewNewMv
7619 | InterMode::NearestNewMv
7620 | InterMode::NewNearestMv
7621 ),
7622 size,
7623 size_h: size,
7624 is_global_mv0: false,
7625 is_global_mv1: false,
7626 },
7627 None => MiInfo {
7628 is_inter: false,
7629 ref_frame: -1,
7630 ref_frame1: NO_REF1,
7631 mv1: (0, 0),
7632 mv: (0, 0),
7633 is_new_mv: false,
7634 size,
7635 size_h: size,
7636 is_global_mv0: false,
7637 is_global_mv1: false,
7638 },
7639 };
7640 for dr in 0..usize::from(size) {
7641 for dc in 0..usize::from(size) {
7642 grid.set(mi_row + dr, mi_col + dc, info);
7643 grid.set_skip(mi_row + dr, mi_col + dc, skip);
7644 }
7645 }
7646}
7647
7648/// lane-b128hv: [`record_mi`] for a RECTANGULAR block -- the mi stamp the
7649/// writer's own `write_inter_block_128_rect` makes, so the second half of a
7650/// HORZ/VERT 128 root searches against the stack the writer will rebuild.
7651fn record_mi_rect(
7652 grid: &mut MiGrid,
7653 mi_row: usize,
7654 mi_col: usize,
7655 (w_mi, h_mi): (usize, usize),
7656 inter: Option<InterInfo>,
7657 skip: bool,
7658) {
7659 record_mi(grid, mi_row, mi_col, w_mi.min(h_mi) as u8, inter, skip);
7660 // `record_mi` stamped the square corner; widen it to the true footprint,
7661 // with the block's own (rect) size fields.
7662 let mut info = grid.get_frame(mi_row, mi_col).expect("just recorded");
7663 info.size = w_mi as u8;
7664 info.size_h = h_mi as u8;
7665 for dr in 0..h_mi {
7666 for dc in 0..w_mi {
7667 grid.set(mi_row + dr, mi_col + dc, info);
7668 grid.set_skip(mi_row + dr, mi_col + dc, skip);
7669 }
7670 }
7671}
7672
7673/// The reconstructed samples one 32x32 square covers in all three planes, so
7674/// that a partition trial can be undone.
7675/// One square of a plane, row-major, the inverse of [`Plane::restore`].
7676///
7677/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
7678/// which allocated and freed a `Vec` per row of every block it copied --
7679/// `Plane::snapshot` runs once per partition trial.
7680fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
7681 let mut out = vec![0u8; side * side];
7682 for row in 0..side {
7683 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
7684 }
7685 out
7686}
7687
7688fn snapshot(
7689 luma: &Plane,
7690 chroma: &[Plane; 2],
7691 (x, y): (usize, usize),
7692 side: usize,
7693) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
7694 [
7695 luma.snapshot(x, y, side),
7696 chroma[0].snapshot(x / 2, y / 2, side / 2),
7697 chroma[1].snapshot(x / 2, y / 2, side / 2),
7698 ]
7699}
7700
7701/// Puts such a snapshot back.
7702fn restore(
7703 luma: &mut Plane,
7704 chroma: &mut [Plane; 2],
7705 (x, y): (usize, usize),
7706 side: usize,
7707 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
7708) {
7709 luma.restore(x, y, side, &saved[0]);
7710 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
7711 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
7712}
7713
7714/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
7715/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
7716/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
7717/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
7718/// rule shared with the key-frame path, not a second one that could diverge.
7719fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
7720 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
7721 let dc_entry = dc_pos.map(|i| scored.remove(i));
7722 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
7723 scored.truncate(if dc_entry.is_some() {
7724 top_k.saturating_sub(1)
7725 } else {
7726 top_k
7727 });
7728 if let Some(dc_entry) = dc_entry {
7729 scored.push(dc_entry);
7730 }
7731 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
7732 modes.iter().copied().filter(|m| keep.contains(m)).collect()
7733}
7734
7735fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
7736 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
7737 [INTRA_MODE_CTX[usize::from(left_mode)]];
7738 std::array::from_fn(|mode| {
7739 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
7740 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
7741 } else {
7742 0.0
7743 };
7744 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
7745 })
7746}
7747
7748/// What the luma mode search picks between, and under what terms.
7749#[derive(Clone, Copy)]
7750struct Search<'a> {
7751 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
7752 /// luma search then offers a palette candidate beside the intra modes.
7753 screen: bool,
7754 base_q_idx: u8,
7755 deadzone: f64,
7756 lambda: f64,
7757 modes: &'a [u8],
7758 /// How many of `modes` the full RD trial (forward transform, quantize,
7759 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
7760 /// pre-pass on the prediction residual alone plus DC (always kept, since
7761 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
7762 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
7763 /// mode through full RD, unchanged from before this lever.
7764 top_k: Option<usize>,
7765}
7766
7767/// [`Search::top_k`]'s value: `None` keeps every mode's search unchanged
7768/// (the default, until a lever's quality gate justifies pruning by default);
7769/// `EC_AV1_PRUNE_K` sweeps it in a test build without touching callers.
7770fn prune_top_k() -> Option<usize> {
7771 #[cfg(test)]
7772 {
7773 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
7774 return k;
7775 }
7776 }
7777 let swept = std::env::var("EC_AV1_PRUNE_K")
7778 .ok()
7779 .and_then(|v| v.parse::<usize>().ok());
7780 match swept {
7781 Some(k) if cfg!(test) => Some(k),
7782 _ => crate::speed::at(&crate::speed::PRUNE_K),
7783 }
7784}
7785
7786// A per-thread override [`prune_top_k`] checks first, so one test can sweep
7787// `top_k` in-process without mutating the environment (forbidden here --
7788// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
7789#[cfg(test)]
7790thread_local! {
7791 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
7792 const { std::cell::Cell::new(None) };
7793}
7794
7795#[cfg(test)]
7796fn set_test_top_k_override(value: Option<usize>) {
7797 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
7798}
7799
7800/// The default: unpruned, thirteen full trials per block, same as before this
7801/// lever. Set from the sweep in the lane report if the quality gate clears it.
7802pub(crate) const PRUNE_TOP_K: Option<usize> = None;
7803
7804/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
7805/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
7806/// quality gates were measured separately and may land on different
7807/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
7808/// [`EC_AV1_PRUNE_K`] or the key-frame path.
7809fn prune_top_k_inter() -> Option<usize> {
7810 #[cfg(test)]
7811 {
7812 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
7813 return k;
7814 }
7815 }
7816 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
7817 .ok()
7818 .and_then(|v| v.parse::<usize>().ok());
7819 match swept {
7820 Some(k) if cfg!(test) => Some(k),
7821 _ => crate::speed::at(&crate::speed::PRUNE_K_INTER),
7822 }
7823}
7824
7825// A per-thread override [`prune_top_k_inter`] checks first, same reason as
7826// [`TEST_TOP_K_OVERRIDE`].
7827#[cfg(test)]
7828thread_local! {
7829 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
7830 const { std::cell::Cell::new(None) };
7831}
7832
7833#[cfg(test)]
7834fn set_test_top_k_override_inter(value: Option<usize>) {
7835 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
7836}
7837
7838/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
7839/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
7840/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
7841/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
7842/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
7843/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
7844/// pruning them costs less quality here.
7845pub(crate) const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
7846
7847// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
7848// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
7849// inter frame's cost can be attributed to a bucket without changing what
7850// the search actually does. Index: 0 = whole-call time inside
7851// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
7852// [`crate::mc::predict`] (every call, from the motion search's own
7853// candidates and from a committed inter block's final prediction alike),
7854// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
7855#[cfg(test)]
7856thread_local! {
7857 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
7858 std::cell::Cell::new(0),
7859 std::cell::Cell::new(0),
7860 std::cell::Cell::new(0),
7861 std::cell::Cell::new(0),
7862 ];
7863}
7864
7865/// lane-av1cap: the trial timers are `#[cfg(test)]`, and the BD gate and
7866/// every encoder test are `cfg(test)` builds -- so two `Instant::now()` ran
7867/// per transform trial and per `mc::predict` call whether or not anyone was
7868/// reading the breakdown (the vdso clock was 1.7% of the encoder's profile).
7869/// The clock is now read only when [`crate::par::stage_times`] is on, which
7870/// is what prints the breakdown in the first place.
7871#[cfg(test)]
7872pub(crate) fn stage_start() -> Option<std::time::Instant> {
7873 crate::par::stage_times().then(std::time::Instant::now)
7874}
7875
7876#[cfg(test)]
7877pub(crate) fn stage_since(bucket: usize, t: Option<std::time::Instant>) {
7878 if let Some(t) = t {
7879 stage_add(bucket, t.elapsed());
7880 }
7881}
7882
7883#[cfg(test)]
7884pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
7885 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
7886}
7887
7888#[cfg(test)]
7889fn stage_reset() {
7890 crate::par::set_stage_times(true);
7891 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
7892}
7893
7894#[cfg(test)]
7895fn stage_read() -> [std::time::Duration; 4] {
7896 crate::par::set_stage_times(false);
7897 STAGE_NS.with(|c| {
7898 c.each_ref()
7899 .map(|cell| std::time::Duration::from_nanos(cell.get()))
7900 })
7901}
7902
7903/// One mode's coding of one block, before it is committed.
7904#[derive(Clone)]
7905struct Trial {
7906 levels: Vec<i32>,
7907 reconstruction: Vec<u8>,
7908 sse: f64,
7909 bits: f64,
7910}
7911
7912/// The top-left `to` x `to` corner of a `from`-sided level grid -- the part
7913/// of a 64-point transform that is actually coded (everything outside it is
7914/// zeroed by [`crate::transform::quantize`] already, so this only reshapes).
7915fn coded_corner(levels: &[i32], from: usize, to: usize) -> Vec<i32> {
7916 let mut out = vec![0i32; to * to];
7917 for row in 0..to {
7918 out[row * to..][..to].copy_from_slice(&levels[row * from..][..to]);
7919 }
7920 out
7921}
7922
7923/// The non-zero levels of a block, as the tile writer takes them.
7924fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
7925 levels
7926 .iter()
7927 .enumerate()
7928 .filter(|&(_, &level)| level != 0)
7929 .map(|(i, &level)| Coeff {
7930 row: (i / side) as u8,
7931 col: (i % side) as u8,
7932 level,
7933 })
7934 .collect()
7935}
7936
7937thread_local! {
7938 /// The tile grid the next frame is coded with, as `(TileColsLog2,
7939 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
7940 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
7941 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
7942 /// one tile per frame, what every caller that never arms anything gets
7943 /// and what every stream this crate wrote before tiles existed carries.
7944 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
7945}
7946
7947/// Arms this thread's next frame encodes with a tile grid (log2 counts).
7948pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
7949 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
7950}
7951
7952fn armed_tiles() -> (u32, u32) {
7953 let armed = TILE_LOG2.with(std::cell::Cell::get);
7954 if armed != (0, 0) {
7955 return armed;
7956 }
7957 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
7958 // (which codes through `encode_sequence`, not the facade) can measure what
7959 // a tile grid costs without a knob of its own -- same shape as
7960 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
7961 match std::env::var("EC_AV1_TILES").ok() {
7962 Some(v) if cfg!(test) => {
7963 let mut f = v.split(':');
7964 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
7965 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
7966 (cols, rows)
7967 }
7968 _ => armed,
7969 }
7970}
7971
7972/// Codes a frame's `tiles` tiles, each entirely on its own (see
7973/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
7974/// the crate's own pool, and hands back their payloads in tile order plus
7975/// whatever `code` returned for tile `store` -- the CDF state
7976/// `context_update_tile_id` names. The result cannot depend on the thread
7977/// count: each job writes one tile from the frame's own starting tables into
7978/// its own slot.
7979fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
7980where
7981 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
7982{
7983 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
7984 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
7985 let threads = crate::par::tile_threads().min(tiles);
7986 let mut slots: Vec<Slot> = Vec::new();
7987 if threads <= 1 {
7988 for index in 0..tiles {
7989 slots.push(Some(code(index)));
7990 }
7991 } else {
7992 let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
7993 {
7994 let batch = crate::par::Batch::new("ec-av1-tile");
7995 for (from, to) in crate::par::bands(tiles, threads) {
7996 let done = &done;
7997 let code = &code;
7998 batch.submit(move || {
7999 for index in from..to {
8000 let coded = code(index);
8001 done.lock().expect("tile slots")[index] = Some(coded);
8002 }
8003 });
8004 }
8005 }
8006 slots = done.into_inner().expect("tile slots");
8007 }
8008 let mut out = Vec::with_capacity(tiles);
8009 let mut stored = None;
8010 for (index, slot) in slots.into_iter().enumerate() {
8011 let (bytes, cdfs) = slot.expect("every tile was coded")?;
8012 if index == store {
8013 stored = cdfs;
8014 }
8015 out.push(bytes);
8016 }
8017 Ok((out, stored))
8018}
8019
8020/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
8021/// workers, and returns the results in tile order. The counterpart of
8022/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
8023/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
8024/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
8025/// availability is already tile-relative (`clip_planes_to_tile`,
8026/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
8027/// other tiles have run -- gated by
8028/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
8029/// covers the search as well as the write.
8030///
8031/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
8032/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
8033/// does it for the decoder's filter bands.
8034fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
8035where
8036 T: Send,
8037 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
8038{
8039 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
8040 let threads = crate::par::tile_threads().min(tiles);
8041 if threads <= 1 {
8042 return (0..tiles).map(|index| job(index, fctx)).collect();
8043 }
8044 type Slot<T> = Option<Result<T>>;
8045 let done: std::sync::Mutex<Vec<Slot<T>>> =
8046 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
8047 {
8048 let batch = crate::par::Batch::new("ec-av1-tile-search");
8049 for (from, to) in crate::par::bands(tiles, threads) {
8050 let done = &done;
8051 let job = &job;
8052 let ctx = crate::decode::filter_ctx_copy(fctx);
8053 batch.submit(move || {
8054 for index in from..to {
8055 let searched = job(index, &ctx);
8056 done.lock().expect("tile slots")[index] = Some(searched);
8057 }
8058 });
8059 }
8060 }
8061 done.into_inner()
8062 .expect("tile slots")
8063 .into_iter()
8064 .map(|slot| slot.expect("every tile was searched"))
8065 .collect()
8066}
8067
8068/// One tile job's own copy of a plane: the frame's source, a blank
8069/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
8070/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
8071/// of the frame's reconstruction because a tile's prediction never reads a
8072/// sample outside its own rectangle, and every sample inside it is written
8073/// before it is read.
8074fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
8075 Plane {
8076 source,
8077 reconstruction: vec![128; source.len()],
8078 width,
8079 height,
8080 true_width,
8081 true_height,
8082 tile_x0: 0,
8083 tile_y0: 0,
8084 tile_x1: width,
8085 tile_y1: height,
8086 ctx: CoefCtxMap::default(),
8087 }
8088}
8089
8090/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
8091/// the frame's plane, through the [`crate::par::Shared`] every job holds.
8092///
8093/// corner-cut: the disjointness that makes the aliasing sound is the caller's
8094/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
8095/// rectangles partition it -- checked end-to-end by
8096/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
8097/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
8098/// row-range `split_at_mut` plumbing through `Plane`, which would have to
8099/// thread an origin offset through every prediction and transform call site
8100/// for the same bytes.
8101#[allow(unsafe_code)]
8102fn copy_rect(
8103 dst: crate::par::Shared<'_, Vec<u8>>,
8104 src: &[u8],
8105 stride: usize,
8106 x0: usize,
8107 y0: usize,
8108 x1: usize,
8109 y1: usize,
8110) {
8111 // SAFETY: this job touches only its own tile rectangle (see above).
8112 let dst = unsafe { dst.get() };
8113 for y in y0..y1 {
8114 let (a, b) = (y * stride + x0, y * stride + x1);
8115 dst[a..b].copy_from_slice(&src[a..b]);
8116 }
8117}
8118
8119/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
8120/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
8121/// tables the frame stores (spec 7.20), which is what
8122/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
8123/// below publish.
8124fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
8125 ec_av1_syntax::TileInfo {
8126 uniform_spacing: true,
8127 cols: layout.cols(),
8128 rows: layout.rows(),
8129 cols_log2: layout.cols_log2,
8130 rows_log2: layout.rows_log2,
8131 mi_col_starts: layout.mi_col_starts(),
8132 mi_row_starts: layout.mi_row_starts(),
8133 context_update_tile_id: layout.largest_tile() as u32,
8134 tile_size_bytes,
8135 }
8136}
8137
8138/// Clips the three planes' intra edge reads to `rect`, the tile the
8139/// superblock about to be searched belongs to (the encoder side of the
8140/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
8141/// raster order -- which is a linear extension of every tile's own coding
8142/// order, so a block still only ever predicts from samples already
8143/// reconstructed -- and only availability is tile-relative.
8144fn clip_planes_to_tile(
8145 luma: &mut Plane<'_>,
8146 chroma: &mut [Plane<'_>; 2],
8147 rect: crate::tile::TileRect,
8148) {
8149 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8150 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8151 luma.set_tile(x0, y0, x1, y1);
8152 for plane in chroma.iter_mut() {
8153 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
8154 }
8155}
8156
8157/// Encodes one picture as a key frame.
8158///
8159/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
8160/// picks its coefficient CDFs from one of four q contexts by that index.
8161/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
8162/// smaller values trade fidelity for rate.
8163///
8164/// The picture may be any even width and height: the encoder pads it by edge
8165/// replication to a whole number of 32x32 blocks internally, and the frame it
8166/// writes crops back to the picture's own size (`render_width`/
8167/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
8168/// own size, never the padded one.
8169///
8170/// # Errors
8171/// Returns an error when the picture's width or height is zero or odd, or
8172/// when its planes are not 4:2:0 of that size.
8173/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
8174/// stream. The per-frame decode state this needs lives for exactly this call.
8175///
8176/// # Errors
8177/// Returns an error under the same conditions
8178/// [`encode_key_frame_with_modes`] does.
8179pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
8180 encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder())
8181}
8182
8183/// [`encode_key_frame`] with the per-block intra modes given rather than
8184/// searched.
8185///
8186/// # Errors
8187/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
8188/// is empty, or when a block's coefficients do not fit the coded frame.
8189pub fn encode_key_frame_with_modes(
8190 picture: &Picture,
8191 base_q_idx: u8,
8192 deadzone: f64,
8193 modes: &[u8],
8194) -> Result<Encoded> {
8195 encode_key_frame_with_modes_with_ctx(
8196 picture,
8197 base_q_idx,
8198 deadzone,
8199 modes,
8200 &crate::decode::FrameCtx::for_encoder(),
8201 )
8202}
8203
8204/// Codes `pictures` as one key frame followed by inter frames.
8205///
8206/// Camera material is coded under [`crate::encoder::Pyramid::default`] since
8207/// lane-av1pyrdef -- mini-GOPs of 4 with a hidden `ALTREF` and a
8208/// `show_existing_frame` header, so `stream` is in CODING order while
8209/// `frames` stays in display order (`EncodedSequence::coding_order` is the
8210/// map). Screen content codes flat, decided once per sequence by the same
8211/// detector the streaming facade's content gate uses, and `EC_AV1_PYRAMID=0`
8212/// puts every stream back on the flat path for an A/B.
8213///
8214/// # Errors
8215/// Returns an error under the same conditions [`encode_key_frame`] and the
8216/// inter frame path do.
8217pub fn encode_sequence(
8218 pictures: &[Picture],
8219 base_q_idx: u8,
8220 deadzone: f64,
8221) -> Result<EncodedSequence> {
8222 encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::for_encoder())
8223}
8224
8225pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
8226 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
8227}
8228
8229/// Encodes one picture as a key frame, choosing each block's luma mode from
8230/// `modes` alone.
8231///
8232/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
8233/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
8234/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
8235/// uses.
8236///
8237/// # Errors
8238/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
8239/// names a mode [`crate::intra::predict`] does not predict.
8240pub(crate) fn encode_key_frame_with_modes_with_ctx(
8241 picture: &Picture,
8242 base_q_idx: u8,
8243 deadzone: f64,
8244 modes: &[u8], fctx: &crate::decode::FrameCtx,
8245) -> Result<Encoded> {
8246 picture.check_even()?;
8247 let padded = picture.padded_to(BLOCK);
8248 let encoded = encode_key_frame_inner(
8249 &padded,
8250 base_q_idx,
8251 deadzone,
8252 modes,
8253 split_blocks(),
8254 (picture.width, picture.height),
8255 unspecified_color_config(), fctx,
8256 )?;
8257 Ok(crop_encoded(&encoded, picture.width, picture.height))
8258}
8259
8260/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
8261/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
8262/// already padded to a whole number of 32x32 blocks; `render` is the real
8263/// (pre-pad) size the frame header tells a decoder to crop back to.
8264pub(crate) fn encode_key_frame_inner(
8265 picture: &Picture,
8266 base_q_idx: u8,
8267 deadzone: f64,
8268 modes: &[u8],
8269 split_blocks: bool,
8270 render: (usize, usize),
8271 color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
8272) -> Result<Encoded> {
8273 // lane-refs: an intra frame runs no motion compensation, and the
8274 // context is shared across the sequence -- put the kernel back to the
8275 // default so nothing reads the previous inter frame's.
8276 fctx.interp_filter.set(mc::InterpFilterKind::Regular);
8277 picture.check()?;
8278 if modes.is_empty() {
8279 return Err(Error::unsupported(
8280 "AV1 encode",
8281 "a mode search needs at least one mode to choose from",
8282 ));
8283 }
8284 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
8285 return Err(Error::unsupported(
8286 "AV1 encode",
8287 format!("intra mode {bad} is not one the encoder predicts"),
8288 ));
8289 }
8290 // The header carries the frame's true (unpadded) size as `frame_width`/
8291 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
8292 // `mi_rows` derived from that same true size (spec `compute_image_size`).
8293 // `render_width`/`render_height` come out equal to it too, so
8294 // `render_and_frame_size_different` is false and no render_size bits are
8295 // written, mirroring libaom/rav1e: the padded `picture` below is only the
8296 // internal coding surface, never what the header names.
8297 // Screen-content detection runs on the SOURCE luma, before any header is
8298 // built: it decides this sequence's `seq_force_screen_content_tools` (and
8299 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
8300 // this frame's own `allow_screen_content_tools`.
8301 let screen = screen_content(
8302 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
8303 picture.width,
8304 (picture.width).min(render.0),
8305 (picture.height).min(render.1),
8306 );
8307 arm_seq_screen(screen);
8308 // A key frame's writer really does start from the defaults, and a search
8309 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
8310 // disarm, or a key frame's bits would depend on which thread searched it.
8311 crate::tile::arm_pricing_cdfs(None, false);
8312 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
8313 // forces deblocking, CDEF and loop restoration OFF for this frame
8314 // (frame.rs:194/210/252/272), so it is only set when the source repeats
8315 // itself enough for the copied blocks to pay that back
8316 // ([`intrabc_worth_it`]).
8317 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
8318 // grid across every tile while this writer builds one per tile, so a
8319 // multi-tile allow_intrabc frame would predict its DVs off a different
8320 // grid than the decoder does. corner-cut, ceiling named: the upgrade
8321 // path is a frame-scoped grid shared by the tile writers.
8322 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
8323 intrabc_worth_it(
8324 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
8325 picture.width,
8326 picture.width.min(render.0),
8327 picture.height.min(render.1),
8328 )
8329 } else {
8330 (false, 0.0)
8331 };
8332 IBC_SHARE.with(|c| c.set(ibc_share));
8333 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
8334 header.allow_screen_content_tools = screen;
8335 // lane-txi: the wider `tx_type` alphabets, gated by the same content
8336 // rule the type search itself stands behind ([`wide_tx_set`]).
8337 header.reduced_tx_set = !wide_tx_set(screen);
8338 header.allow_intrabc = allow_intrabc;
8339 header.render_width = render.0 as u32;
8340 header.render_height = render.1 as u32;
8341 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
8342 // its luma transform below its own side (`crate::tile::write_luma_select`).
8343 // Set here rather than in `key_frame_headers_colour` so the header
8344 // builders' other callers -- the hand-built tile writers, which code no
8345 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
8346 let tx_select = tx_select();
8347 if tx_select {
8348 header.tx_mode = TxMode::Select;
8349 }
8350 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
8351
8352 // Prediction reads no further than this, in each plane's own units --
8353 // see `Plane::true_width`/`true_height`.
8354 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
8355 // lane-palw: the encoder's own in-process reconstruct reads its palette
8356 // colour-index maps back through `decode::palette_onscreen`, which takes
8357 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
8358 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
8359 // them here so the reconstruct clamps a block cut by the frame edge
8360 // exactly as the writer now does.
8361 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
8362 fctx.seg_mi_dims.set(frame_mi_dims);
8363 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
8364 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
8365 // design (see `intra_predict_u8`'s doc comment), so narrow the source
8366 // once here.
8367 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
8368 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
8369 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
8370 let mut luma = Plane {
8371 source: &picture_y8,
8372 reconstruction: vec![128; picture_y8.len()],
8373 width: picture.width,
8374 height: picture.height,
8375 true_width,
8376 true_height,
8377 tile_x0: 0,
8378 tile_y0: 0,
8379 tile_x1: picture.width,
8380 tile_y1: picture.height,
8381 ctx: CoefCtxMap::default(),
8382 };
8383 let mut chroma = [
8384 Plane {
8385 source: &picture_u8,
8386 reconstruction: vec![128; picture_u8.len()],
8387 width: picture.width / 2,
8388 height: picture.height / 2,
8389 true_width: true_width / 2,
8390 true_height: true_height / 2,
8391 tile_x0: 0,
8392 tile_y0: 0,
8393 tile_x1: picture.width / 2,
8394 tile_y1: picture.height / 2,
8395 ctx: CoefCtxMap::default(),
8396 },
8397 Plane {
8398 source: &picture_v8,
8399 reconstruction: vec![128; picture_v8.len()],
8400 width: picture.width / 2,
8401 height: picture.height / 2,
8402 true_width: true_width / 2,
8403 true_height: true_height / 2,
8404 tile_x0: 0,
8405 tile_y0: 0,
8406 tile_x1: picture.width / 2,
8407 tile_y1: picture.height / 2,
8408 ctx: CoefCtxMap::default(),
8409 },
8410 ];
8411
8412 // The search trades a bit for the squared error it saves, in the units the
8413 // reconstruction is measured in: one step of the quantizer, squared.
8414 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
8415 let search = Search {
8416 base_q_idx,
8417 deadzone,
8418 lambda: lambda_scale() * key_lambda_factor() * step * step,
8419 modes,
8420 top_k: prune_top_k(),
8421 screen,
8422 };
8423
8424 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
8425 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
8426 // which may be fewer columns/rows than the padded picture has room for
8427 // -- a block whose origin sits past the true bound is not coded at all,
8428 // matching what a decoder derives from `frame_width`/`frame_height` and
8429 // so never visits either.
8430 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
8431 let (cols, rows) = (cols as usize, rows as usize);
8432 // The luma mode of the block above and of the block to the left, which is
8433 // what picks the CDF the next block's mode is coded against -- the same
8434 // bookkeeping the tile writer keeps, so that the search is costing the
8435 // symbol the writer will actually write.
8436 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
8437 // because a 32x32 block may be split into four 16x16 ones.
8438 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
8439 // This frame's tile grid (one tile unless the facade armed more).
8440 let layout =
8441 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
8442 header.tile_info = tile_info_of(&layout, 1);
8443 // The filter search re-decodes this frame's tiles; the decoder derives
8444 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
8445 // `mi_row_starts`), which is what makes the writer's rects and the
8446 // reader's the same rects.
8447 let header_tile_info = header.tile_info.clone();
8448 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
8449 // once over the whole frame. Each tile job builds its own reconstruction
8450 // planes and its own `above_mode`/`left_mode` bands, which is also what
8451 // the tile writer reads -- a tile resets its neighbour contexts (spec
8452 // 5.11.1), so a block at a tile's left edge must cost its mode against
8453 // the default context, not against whatever the tile to its west left in
8454 // that row. At one tile the bands are the frame's, exactly as before.
8455 let (frame_width, frame_height) = (picture.width, picture.height);
8456 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
8457 let [cb, cr] = &mut chroma;
8458 let chroma_out = [
8459 crate::par::Shared::new(&mut cb.reconstruction),
8460 crate::par::Shared::new(&mut cr.reconstruction),
8461 ];
8462 let search_tile = |index: usize,
8463 fctx: &crate::decode::FrameCtx|
8464 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
8465 crate::tile::arm_pricing_cdfs(None, false);
8466 let rect = layout.rect(index);
8467 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
8468 let mut chroma = [
8469 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
8470 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
8471 ];
8472 clip_planes_to_tile(&mut luma, &mut chroma, rect);
8473 let mut above_mode = vec![DC_PRED; cols * 2];
8474 let mut left_mode = vec![DC_PRED; rows * 2];
8475 let mut ibc = allow_intrabc.then(|| {
8476 Ibc::new(
8477 (
8478 rect.mi_col0 as usize * 4,
8479 rect.mi_row0 as usize * 4,
8480 (rect.mi_col1 as usize * 4).min(true_width),
8481 (rect.mi_row1 as usize * 4).min(true_height),
8482 ),
8483 &picture_y8,
8484 frame_width,
8485 )
8486 });
8487 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
8488 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
8489 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
8490 let mut modes = Vec::with_capacity(4);
8491 // The quadrants of a superblock are coded in the order the decoder
8492 // walks them, which for a 64x64 split into 32x32 blocks is raster
8493 // order among the quadrants that are inside the frame.
8494 let mut blocks = Vec::with_capacity(4);
8495 // lane-i64: the whole superblock as ONE 64x64 intra block, tried
8496 // BEFORE its quadrants (so both start from the same
8497 // reconstruction) and compared against the four of them below --
8498 // the shape the inter frame's own 64 root takes
8499 // (`search_skip_64`). A frame that allows intrabc is refused
8500 // outright ([`I64_ROOT`]) because the quadrant searches below
8501 // carry DV state a discarded trial would desync.
8502 let (x64, y64) = (sb_col * SUPERBLOCK, sb_row * SUPERBLOCK);
8503 // lane-corner LIFTED the two guards this root shipped with: the
8504 // frame no longer has to be a whole number of superblocks, and
8505 // the superblock no longer has to be wholly inside the frame.
8506 // The desync the guards were written for (a 248x152 corner's
8507 // chroma disagreeing three ways) does NOT reproduce at this
8508 // revision -- see
8509 // `stream::tests::a_doubly_cut_superblock_root_round_trips_in_every_plane`,
8510 // which pins all three planes of the encoder's reconstruction,
8511 // our decoder and ffmpeg on four straddling sizes, three of them
8512 // cut on BOTH axes, with the edge fire count asserted. What the
8513 // guards cost was every key-frame root on an arbitrary export
8514 // size (the `aligned` line switched the whole feature off on, for
8515 // instance, a 1920x792 frame).
8516 let whole_inside = x64 + SUPERBLOCK <= luma.true_width
8517 && y64 + SUPERBLOCK <= luma.true_height;
8518 // lane-corner: and the superblock the true frame edge CUTS
8519 // THROUGH with more than half of each axis still inside, which is
8520 // all AV1 asks of a `PARTITION_NONE` root (spec
8521 // `decode_partition`'s `has_cols`/`has_rows`, the same pair the
8522 // key writer's `Superblock::Whole` arm checks) -- the shape the
8523 // inter root already takes ([`b64_edge`]).
8524 let edge_inside = edge_root_enabled()
8525 && crate::tile::has_half(
8526 sb_col as u32 * crate::tile::SB_MI,
8527 crate::tile::SB_MI,
8528 header.mi_cols,
8529 )
8530 && crate::tile::has_half(
8531 sb_row as u32 * crate::tile::SB_MI,
8532 crate::tile::SB_MI,
8533 header.mi_rows,
8534 );
8535 let sb64_legal = i64_root()
8536 && ibc.is_none()
8537 && sb_row * 2 + 1 < rows
8538 && sb_col * 2 + 1 < cols
8539 && (whole_inside || edge_inside);
8540 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
8541 if sb64_legal {
8542 I64_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8543 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
8544 let (c64, r64) = (sb_col * 4, sb_row * 4);
8545 let (block, cost) = code_square(
8546 &mut luma,
8547 &mut chroma,
8548 (x64, y64),
8549 SUPERBLOCK,
8550 &search,
8551 &mode_bits(above_mode[c64], left_mode[r64]),
8552 tx_select,
8553 None,
8554 true,
8555 fctx,
8556 );
8557 let cost = cost + search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
8558 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
8559 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
8560 sb64 = Some((cost, block, after));
8561 }
8562 // A superblock whose 64x64 trial already codes almost nothing per
8563 // pixel is taken outright and its quadrants are never searched --
8564 // `split_rd_breakout` one size up, at the threshold the inter
8565 // root clamps to ([`b64_breakout_threshold`]), where this lever
8566 // BUYS wall instead of spending it.
8567 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
8568 split_rd_breakout_at(b64_breakout_threshold(), *c, SUPERBLOCK, search.lambda)
8569 });
8570 // What the four quadrants cost together, including the split
8571 // partition symbol at the superblock level, so the two arms are
8572 // one comparable number.
8573 let mut sb_cost = match sb64 {
8574 Some(_) => search.lambda * crate::tile::partition_bits(SUPERBLOCK, true),
8575 None => 0.0,
8576 };
8577 for quadrant in 0..if early64 { 0 } else { 4 } {
8578 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
8579 if col >= cols || row >= rows {
8580 continue;
8581 }
8582 let (x, y) = (col * BLOCK, row * BLOCK);
8583 let (c0, r0) = (col * 2, row * 2);
8584 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
8585
8586 // spec `decode_partition`'s hasRows/hasCols recomputed at this
8587 // 32x32 block's own half (see `crate::tile::has_half`): the
8588 // true frame edge can fall inside a quadrant a superblock-level
8589 // check already let through. A quadrant that fails either may
8590 // not be left whole; a 16x16 sub-block that fails either (once
8591 // split) is a leaf this writer has no rectangular transform
8592 // for, so the search must not pick a split that would need one.
8593 let (has_cols32, has_rows32) = (
8594 crate::tile::has_half(
8595 col as u32 * crate::tile::BLOCK_MI,
8596 crate::tile::BLOCK_MI,
8597 header.mi_cols,
8598 ),
8599 crate::tile::has_half(
8600 row as u32 * crate::tile::BLOCK_MI,
8601 crate::tile::BLOCK_MI,
8602 header.mi_rows,
8603 ),
8604 );
8605 let whole_legal = has_cols32 && has_rows32;
8606 // A 16x16 sub-block's own hasCols/hasRows (spec
8607 // `decode_partition`, recomputed at this leaf's own half):
8608 // either axis false is a straddling leaf this writer codes as
8609 // the 8x8 leaves that are inside it
8610 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
8611 // false is the same split with the partition symbol inferred
8612 // rather than coded -- no rectangular transform is needed
8613 // (lane-av1rect).
8614 let sub_half = |sr: usize, sc: usize| {
8615 (
8616 crate::tile::has_half(
8617 sc as u32 * crate::tile::SUB_MI,
8618 crate::tile::SUB_MI,
8619 header.mi_cols,
8620 ),
8621 crate::tile::has_half(
8622 sr as u32 * crate::tile::SUB_MI,
8623 crate::tile::SUB_MI,
8624 header.mi_rows,
8625 ),
8626 )
8627 };
8628 // What the whole 32x32 costs, including the partition symbol
8629 // that says it is not split.
8630 let (whole, mut cost_whole) = code_square(
8631 &mut luma,
8632 &mut chroma,
8633 (x, y),
8634 BLOCK,
8635 &search,
8636 &mode_bits(above_mode[c0], left_mode[r0]),
8637 tx_select,
8638 ibc.as_mut(),
8639 true,
8640 fctx,
8641 );
8642 cost_whole += search.lambda * partition_bits(BLOCK, false);
8643 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
8644
8645 // What four 16x16 blocks cost instead, each searched against
8646 // the reconstruction the ones before it left.
8647 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
8648 let mut split = Vec::with_capacity(4);
8649 let mut cost_split = search.lambda
8650 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
8651 let mut split_modes = Vec::with_capacity(4);
8652 for sub in 0..4 {
8653 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
8654 // Same filter as the writer's `sub_positions` (spec
8655 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
8656 // return): a sub-block whose own origin sits past the
8657 // true frame is never coded, so it must not be searched
8658 // or pushed onto `split` either, or the writer's block
8659 // count will not match what it is prepared to name.
8660 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
8661 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
8662 {
8663 continue;
8664 }
8665 let (has_cols16, has_rows16) = sub_half(sr, sc);
8666 if has_cols16 && has_rows16 {
8667 let (block, cost) = code_square(
8668 &mut luma,
8669 &mut chroma,
8670 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
8671 SUB,
8672 &search,
8673 &mode_bits(above_mode[sc], left_mode[sr]),
8674 tx_select,
8675 ibc.as_mut(),
8676 true,
8677 fctx,
8678 );
8679 cost_split += cost;
8680 split_modes.push(block.mode);
8681 above_mode[sc] = block.mode;
8682 left_mode[sr] = block.mode;
8683 split.push(block);
8684 } else {
8685 // A straddling 16x16: two (or, at a true corner, one)
8686 // 8x8 leaves, in the raster order `write_leaf8`'s
8687 // caller expects. Both leaves cost against the SAME
8688 // enclosing-slot mode context (see
8689 // `crate::tile::write_leaf8`'s doc), and neither
8690 // updates `above_mode`/`left_mode` at this SUB slot --
8691 // the writer never does either, so the search must
8692 // not diverge from what it will actually read next.
8693 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
8694 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
8695 let mut leaves = Vec::with_capacity(2);
8696 for i in 0..4 {
8697 let leaf_x = x_sub + (i % 2) * 8;
8698 let leaf_y = y_sub + (i / 2) * 8;
8699 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
8700 continue;
8701 }
8702 let (leaf, cost) = code_square(
8703 &mut luma,
8704 &mut chroma,
8705 (leaf_x, leaf_y),
8706 8,
8707 &search,
8708 &leaf_mode_bits,
8709 tx_select,
8710 None,
8711 true,
8712 fctx,
8713 );
8714 cost_split += cost;
8715 split_modes.push(leaf.mode);
8716 leaves.push(leaf);
8717 }
8718 split.push(BlockCoeffs {
8719 eight: Some(leaves),
8720 ..BlockCoeffs::default()
8721 });
8722 }
8723 }
8724
8725 // A split whose subs are all whole 16x16 is a real quality
8726 // alternative to `whole`, exactly as before. Through r14, a
8727 // split carrying an 8x8-leaf sub was only ever forced
8728 // (`!whole_legal`), never chosen on cost, because the leaf
8729 // path was not yet proven against a real decoder; r15 proved
8730 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
8731 // the read path (`decode_leaf8`), so leaf8 can now win on
8732 // cost anywhere, same as any other split.
8733 if !whole_legal || (split_blocks && cost_split < cost_whole) {
8734 sb_cost += cost_split;
8735 modes.extend_from_slice(&split_modes);
8736 blocks.push(Quadrant::Split(split));
8737 } else {
8738 sb_cost += cost_whole;
8739 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
8740 for cell in 0..2 {
8741 above_mode[c0 + cell] = whole.mode;
8742 left_mode[r0 + cell] = whole.mode;
8743 }
8744 modes.push(whole.mode);
8745 blocks.push(Quadrant::Whole(whole));
8746 }
8747 }
8748 let index = sb_row * sb_cols + sb_col;
8749 match sb64 {
8750 Some((cost64, block, after)) if early64 || cost64 < sb_cost => {
8751 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
8752 for cell in 0..4 {
8753 above_mode[sb_col * 4 + cell] = block.mode;
8754 left_mode[sb_row * 4 + cell] = block.mode;
8755 }
8756 I64_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8757 if !whole_inside {
8758 I64_HITS[2].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
8759 }
8760 let mode = block.mode;
8761 coded.push((index, Superblock::Whole(block), vec![mode]));
8762 }
8763 _ => coded.push((index, Superblock::Split(blocks), modes)),
8764 }
8765 }
8766 }
8767 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
8768 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
8769 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
8770 for (&out, tile) in chroma_out.iter().zip(&chroma) {
8771 copy_rect(
8772 out,
8773 &tile.reconstruction,
8774 frame_width / 2,
8775 x0 / 2,
8776 y0 / 2,
8777 x1.div_ceil(2),
8778 y1.div_ceil(2),
8779 );
8780 }
8781 Ok(coded)
8782 };
8783 let searched = search_tiles(layout.count(), fctx, search_tile)?;
8784 // Back into frame raster order: the tile writer indexes `superblocks` by
8785 // the frame's own superblock index, and `modes` is the coding order the
8786 // ablation drivers read.
8787 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
8788 for (at, superblock, block_modes) in searched.into_iter().flatten() {
8789 in_order[at] = Some((superblock, block_modes));
8790 }
8791 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
8792 let mut modes = Vec::with_capacity(cols * rows);
8793 for slot in in_order {
8794 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
8795 superblocks.push(superblock);
8796 modes.extend_from_slice(&block_modes);
8797 }
8798
8799 #[cfg(test)]
8800 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
8801 // A key frame always starts from the defaults (`primary_ref_frame` is
8802 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
8803 // set, so what it stores into the slots it refreshes is exactly those
8804 // defaults again (spec 7.20's `started_from` arm) -- the first inter
8805 // frame after it therefore starts from the defaults too.
8806 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
8807 let mut cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
8808 // lane-txi: the ONE place the writer reads the frame's `reduced_tx_set`
8809 // from -- `Cdfs::txb` widens every luma set under it.
8810 cdfs.reduced_tx_set = header.reduced_tx_set;
8811 let start_cdfs = CdfSnapshot(cdfs);
8812 // The luma restoration-unit grid this frame's `lr_params` implies
8813 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
8814 // swallowed by the one before it), for the tile writer's own per-unit
8815 // walk.
8816 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
8817 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
8818 // Every tile is coded from this frame's OWN starting tables and leaves
8819 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
8820 // loop-restoration reference and its neighbour contexts), so the tiles
8821 // are independent of each other and of the order they are written in.
8822 let code_tiles = |bits: u8,
8823 sb_cols: usize,
8824 grid: &[u8],
8825 units: &[Option<crate::restoration::WienerInfo>]|
8826 -> Result<Vec<Vec<u8>>> {
8827 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
8828 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
8829 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
8830 crate::tile::arm_sb128(sb128_on());
8831 let mut cdfs = start_cdfs.0.clone();
8832 crate::tile::arm_screen(screen);
8833 crate::tile::arm_frame_mi_dims(frame_mi_dims);
8834 crate::tile::arm_filter_intra(filter_intra_on());
8835 crate::tile::arm_intrabc(allow_intrabc);
8836 crate::tile::arm_pricing_cdfs(None, false);
8837 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
8838 mi_cols,
8839 mi_rows,
8840 base_q_idx,
8841 &superblocks,
8842 tx_select,
8843 &mut cdfs,
8844 layout.rect(index),
8845 )?;
8846 Ok((bytes, None))
8847 })?;
8848 Ok(out)
8849 };
8850 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
8851 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
8852 // the tile just coded back to the decoder under each candidate (see
8853 // `crate::filter_search`), and keep the filtered picture that wins as
8854 // the reconstruction -- what a decoder outputs, and what the next
8855 // frame predicts from.
8856 pick_and_apply_filters(
8857 &mut header,
8858 &mut luma,
8859 &mut chroma,
8860 [&picture_y8, &picture_u8, &picture_v8],
8861 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
8862 // and loop restoration off and codes none of their parameters
8863 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
8864 // the encoder's reconstruction is already what a decoder produces.
8865 !allow_intrabc,
8866 &mut tiles,
8867 search.lambda,
8868 fctx,
8869 // A key frame codes no 128x128 root block (the writer has no intra
8870 // path at that size), so every unit carries its own literal.
8871 &[],
8872 // Every re-code starts from this frame's OWN starting tables, never
8873 // from where the first write left them: the second tile is the same
8874 // symbol sequence plus new ones, so it must adapt from the same
8875 // point the decoder will.
8876 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
8877 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
8878 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
8879 crate::decode::decode_key_frame_tiles_lr(
8880 &payloads,
8881 &header_tile_info,
8882 h.mi_cols,
8883 h.mi_rows,
8884 base_q_idx,
8885 h.frame_width,
8886 h.frame_height,
8887 seq.enable_filter_intra,
8888 cdef,
8889 lf,
8890 tx_select,
8891 h.reduced_tx_set,
8892 h.allow_screen_content_tools,
8893 h.allow_intrabc,
8894 lr,
8895 fctx,
8896 )
8897 },
8898 )?;
8899 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
8900 header.tile_info.tile_size_bytes = tile_size_bytes;
8901 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
8902 let mut stream = temporal_delimiter();
8903 stream.extend_from_slice(&sequence_header_obu(&seq)?);
8904 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
8905
8906 let [u, v] = chroma;
8907 Ok(Encoded {
8908 stream,
8909 modes,
8910 inter_block_share: 0.0,
8911 reconstruction: Picture {
8912 width: luma.width,
8913 height: luma.height,
8914 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
8915 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
8916 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
8917 },
8918 tile,
8919 mi_cols: header.mi_cols,
8920 mi_rows: header.mi_rows,
8921 base_q_idx,
8922 tx_select,
8923 // A key frame codes no inter block, so no motion_mode symbol.
8924 switchable_motion_mode: false,
8925 screen,
8926 reduced_tx_set: header.reduced_tx_set,
8927 next_cdfs: start_cdfs.clone(),
8928 start_cdfs,
8929 loop_filter: header.loop_filter,
8930 cdef: header.cdef,
8931 loop_restoration: header.loop_restoration,
8932 allow_intrabc,
8933 delta: header.delta.clone(),
8934 })
8935}
8936
8937/// Chooses this frame's deblocking levels and CDEF strengths, writes them
8938/// into `header` and
8939/// replaces the frame's own region of the encoder's reconstruction with the
8940/// filtered picture the decoder produced under them
8941/// ([`crate::filter_search::pick_deblock`]).
8942///
8943/// `search == false` leaves the header at level 0 (deblocking off) and the
8944/// reconstruction untouched: the caller's stream is one this crate's own
8945/// decoder cannot read back, so there is nothing to search against.
8946///
8947/// # Errors
8948/// The decoder's own error, when it refuses the tile the encoder just wrote
8949/// -- that is an encoder defect, not a filter one, so it is propagated
8950/// rather than swallowed into "no deblocking".
8951fn pick_and_apply_filters(
8952 header: &mut FrameHeader,
8953 luma: &mut Plane<'_>,
8954 chroma: &mut [Plane<'_>; 2],
8955 source: [&[u8]; 3],
8956 search: bool,
8957 // The coded tiles, one payload per tile of the frame's grid, replaced in
8958 // place when the search chooses a per-64x64 `cdef_idx` list
8959 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
8960 // tile is written a second time under `recode` and the winner
8961 // re-decoded from them.
8962 tiles: &mut Vec<Vec<u8>>,
8963 lambda: f64,
8964 fctx: &crate::decode::FrameCtx,
8965 // lane-edge128: `crate::tile::cdef_unit_owner` for the blocks these tiles
8966 // carry -- empty (the identity map) for a frame whose every block covers
8967 // one 64x64 CDEF unit.
8968 cdef_owner: &[u32],
8969 recode: impl Fn(
8970 u8,
8971 usize,
8972 &[u8],
8973 &[Option<crate::restoration::WienerInfo>],
8974 ) -> Result<Vec<Vec<u8>>>,
8975 decode: impl Fn(
8976 &LoopFilterParams,
8977 &CdefParams,
8978 &FrameHeader,
8979 &[Vec<u8>],
8980 &LoopRestorationParams,
8981 ) -> Result<Picture>,
8982) -> Result<()> {
8983 if !search {
8984 return Ok(());
8985 }
8986 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
8987 let hdr = header.clone();
8988 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
8989 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
8990 let damping = 3 + (header.quantization.base_q_idx >> 6);
8991 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
8992 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
8993 let none_lr = LoopRestorationParams::default();
8994 // Every candidate scores the same coded tile: decode it once and re-run
8995 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
8996 // the encoder's profile before this). The per-64x64 error the CDEF
8997 // preset search reads comes off the REPLAYED picture, which is the same
8998 // picture a decode produces -- that is what the replay is pinned on.
8999 crate::decode::clear_filter_replay();
9000 // lane-av1fpar: the per-tile search is over, so every core is idle from
9001 // here to the end of the frame -- band each candidate's deblock/CDEF
9002 // replay, the capture decode's own filter chain and the loop-restoration
9003 // passes across the same workers the search used.
9004 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
9005 let ft = crate::par::timer(crate::par::S_FILTER);
9006 let search_result = crate::filter_search::pick_filters(
9007 |lf, cdef| {
9008 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
9009 return Ok(picture);
9010 }
9011 crate::decode::arm_filter_replay();
9012 let _t = crate::par::timer(crate::par::S_FIRST);
9013 decode(lf, cdef, &hdr, tiles, &none_lr)
9014 },
9015 source,
9016 luma.width,
9017 (fw, fh),
9018 damping,
9019 (sb_cols, sb_rows),
9020 lambda,
9021 cdef_owner,
9022 );
9023 drop(ft);
9024 let (lf, cdef, idx_grid, picture) = search_result?;
9025 header.loop_filter = lf;
9026 header.cdef = cdef;
9027 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
9028 // in the frame header, so a re-decode under candidate parameters cannot
9029 // search them the way deblocking and CDEF are searched above. What the
9030 // decoder hands back instead is its own filter chain's intermediates
9031 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
9032 // those, through the decoder's own Wiener kernel.
9033 //
9034 // The capture rides the decode this stage was already going to do: the
9035 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
9036 // decode of the tile as it stands. That decode's header still says
9037 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
9038 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
9039 // an approximation inside the SEARCH only; the reconstruction this
9040 // function ends up splicing is always a real decode of the real tile.
9041 let lr_on = restoration_enabled();
9042 // The `cdef_idx` literals live in the tile payload, so a frame that
9043 // chose a per-64x64 preset list codes its tiles a second time.
9044 if !idx_grid.is_empty() {
9045 *tiles = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
9046 }
9047 // lane-av1cap: that re-coded tile used to be DECODED here as well --
9048 // 10% of a 4K frame -- purely to reach the post-CDEF plane the loop
9049 // restoration search reads (`crate::decode::FrameCtx::capture_stages`)
9050 // and the picture this function splices. Both come out of ONE more
9051 // replay of the winning parameters on the same captured pre-filter
9052 // planes every candidate was scored on: the same two filter kernels, on
9053 // the same input, in the same order, so the same bytes. Re-coding the
9054 // tile does not move the reconstruction the replay holds -- `cdef_idx`
9055 // is an equiprobable literal, so it adapts no CDF and changes no
9056 // residual.
9057 let replayed = crate::decode::replay_final(&lf, &cdef, &idx_grid, lr_on, fctx);
9058 #[cfg(test)]
9059 let replay_was_used = replayed.is_some();
9060 let (mut filtered, mut stages) = match replayed {
9061 Some((picture, stages)) => (picture, stages),
9062 // Nothing captured (the shapes [`crate::decode::FilterReplay`]
9063 // refuses): every candidate was a full decode, so the winner's own
9064 // picture stands, and the stages still need a capturing decode.
9065 None => {
9066 fctx.capture_stages.set(lr_on);
9067 let picture = if idx_grid.is_empty() && !lr_on {
9068 picture
9069 } else {
9070 let _t = crate::par::timer(crate::par::S_CAPTURE);
9071 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
9072 };
9073 fctx.capture_stages.set(false);
9074 (picture, crate::decode::take_filter_stages(fctx))
9075 }
9076 };
9077 #[cfg(test)]
9078 if crate::decode::verify_final_replay() && replay_was_used {
9079 fctx.capture_stages.set(lr_on);
9080 let want = decode(&lf, &cdef, &hdr, tiles, &none_lr)?;
9081 fctx.capture_stages.set(false);
9082 let want_stages = crate::decode::take_filter_stages(fctx);
9083 assert!(
9084 (want.width, want.height) == (filtered.width, filtered.height)
9085 && want.y == filtered.y
9086 && want.u == filtered.u
9087 && want.v == filtered.v,
9088 "the final filter replay is not the capture decode it stands in for",
9089 );
9090 // Only the frame's own cropped region: the plane is padded to the
9091 // superblock grid and the columns past the mi extent are written by
9092 // nothing (the decoder's plane pool leaves whatever the last frame
9093 // put there), while the restoration search reads strictly inside
9094 // `fw x fh` -- `restoration::lr_sample` clamps its column to
9095 // `plane_w - 1` and its row to the frame's, and
9096 // `filter_search::pick_restoration`'s own SSE walk never leaves the
9097 // crop either.
9098 let region = |a: &[u16], b: &[u16], stride: usize, w: usize, h: usize, what: &str| {
9099 for row in 0..h {
9100 let (x, y) = (&a[row * stride..][..w], &b[row * stride..][..w]);
9101 assert!(
9102 x == y,
9103 "{what}: the replayed filter stages are not the ones the capture \
9104 decode returns (row {row} of {h}, width {w}, stride {stride})",
9105 );
9106 }
9107 };
9108 match (&want_stages, &stages) {
9109 (Some(a), Some(b)) => {
9110 assert_eq!(a.stride, b.stride, "the captured plane strides moved");
9111 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9112 for (i, (w, h)) in [(fw, fh), (cw, ch), (cw, ch)].into_iter().enumerate() {
9113 region(&a.deblocked[i], &b.deblocked[i], a.stride[i], w, h, "deblocked");
9114 region(&a.cdefed[i], &b.cdefed[i], a.stride[i], w, h, "cdefed");
9115 }
9116 }
9117 (None, None) => {}
9118 _ => panic!("one path captured filter stages and the other did not"),
9119 }
9120 }
9121 // lane-av1cap2: the capture stays live past the restoration search --
9122 // `crate::decode::replay_restoration` filters the same post-CDEF plane
9123 // rather than decoding the re-coded tile. Cleared at the end instead.
9124 let mut lr = LoopRestorationParams::default();
9125 if lr_on {
9126 let unit = lr_unit();
9127 let mut want = LoopRestorationParams {
9128 loop_restoration_size: [unit, unit, unit],
9129 uses_lr: true,
9130 // spec `lr_params`: `RESTORATION_TILESIZE_MAX >> (2 - shift)`, so
9131 // 0 is the 64 unit and 1 the 128 one a 128 superblock forces.
9132 lr_unit_shift: u8::from(unit == 128),
9133 ..LoopRestorationParams::default()
9134 };
9135 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
9136 let lrt = crate::par::timer(crate::par::S_LR);
9137 let units = match stages.take() {
9138 Some(stages) => crate::filter_search::pick_restoration(
9139 &stages,
9140 source[0],
9141 luma.width,
9142 (fw, fh),
9143 &want,
9144 lambda,
9145 fctx,
9146 ),
9147 None => Vec::new(),
9148 };
9149 // A frame no unit restores keeps `RESTORE_NONE` on every plane
9150 // rather than paying ~1 bit per 64x64 for a tile full of
9151 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
9152 // clip whose units never take a filter).
9153 drop(lrt);
9154 if units.iter().any(Option::is_some) {
9155 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
9156 let _t = crate::par::timer(crate::par::S_CAPTURE);
9157 // lane-av1cap2: that re-coded tile used to be DECODED here to
9158 // reach the restored reference frame -- 5.6% of a 4K frame,
9159 // for a filter that reads nothing of the tile but the per-unit
9160 // Wiener filters this stage just chose. Run the decoder's own
9161 // restoration kernel on the replay's post-CDEF plane instead
9162 // (`crate::decode::replay_restoration`), with the real
9163 // post-deblock stripe borders.
9164 match crate::decode::replay_restoration(&want, &units, fctx) {
9165 Some(y) => {
9166 #[cfg(test)]
9167 let margin = fctx
9168 .last_frame_wide_margin
9169 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()));
9170 #[cfg(test)]
9171 if crate::decode::verify_final_replay() {
9172 let want_pic = decode(&lf, &cdef, &hdr, &coded, &want)?;
9173 assert!(
9174 (want_pic.width, want_pic.height) == (filtered.width, filtered.height)
9175 && want_pic.u == filtered.u
9176 && want_pic.v == filtered.v,
9177 "the restoration replay moved a chroma plane or the picture size",
9178 );
9179 assert!(
9180 want_pic.y == y,
9181 "the restoration replay is not the decode of the re-coded tile",
9182 );
9183 assert!(
9184 fctx.last_frame_wide_margin
9185 .with(|m| m.borrow().as_ref().map(|p| p.y.clone()))
9186 == margin,
9187 "the restoration replay's wide-margin luma is not the decode's",
9188 );
9189 }
9190 filtered.y = y;
9191 }
9192 // Nothing captured: the winner came out of a full decode,
9193 // so this one does too.
9194 None => filtered = decode(&lf, &cdef, &hdr, &coded, &want)?,
9195 }
9196 *tiles = coded;
9197 lr = want;
9198 }
9199 }
9200 crate::decode::clear_filter_replay();
9201 header.loop_restoration = lr;
9202 let dec_cw = filtered.width.div_ceil(2);
9203 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
9204 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
9205 crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
9206 crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
9207 Ok(())
9208}
9209
9210/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
9211/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
9212/// since every block this crate's inter tile writer codes is 32x32.
9213const SIZE_GROUP_32: usize = 3;
9214
9215/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
9216/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
9217/// stack this encoder builds is ever asked to predict against.
9218const LAST_FRAME: i8 = 1;
9219
9220/// What an inter frame's intra branch spends to name each of the thirteen
9221/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
9222/// context, since an inter frame's intra blocks do not read their
9223/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
9224/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
9225/// state, so it is built once per frame.
9226fn inter_mode_bits() -> [f64; 13] {
9227 std::array::from_fn(|mode| {
9228 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
9229 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
9230 } else {
9231 0.0
9232 };
9233 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
9234 + angle
9235 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
9236 })
9237}
9238
9239/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
9240/// [`mc::predict`] takes, in the units of the plane it predicts into.
9241///
9242/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
9243/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
9244/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
9245/// domain. `luma` picks which.
9246fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
9247 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
9248}
9249
9250/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
9251/// that module): the magnitude an `MV_CLASS_n` component's own bits start
9252/// counting from.
9253fn mv_class_base(class: usize) -> i32 {
9254 if class == 0 { 0 } else { 2i32 << (class + 2) }
9255}
9256
9257/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
9258/// `tile::mv_class_of`.
9259fn mv_class_of(z: i32) -> usize {
9260 let mut class = 0;
9261 while class < 10 && mv_class_base(class + 1) <= z {
9262 class += 1;
9263 }
9264 class
9265}
9266
9267/// What [`crate::tile::write_mv_component`] (private to that module) would
9268/// spend coding one non-zero motion vector component, against the same
9269/// static default CDFs the writer starts a frame from — the same
9270/// static-table approximation [`mode_bits`] costs the luma mode symbol
9271/// through, not the tile writer's own adapting state, which this encoder has
9272/// no way to read without duplicating it block for block.
9273///
9274/// Returns `None` when `diff` needs eighth-pel precision in a frame coded
9275/// without `allow_high_precision_mv`, which is what [`round_to_valid_mv`]
9276/// exists to avoid ever happening.
9277fn mv_component_bits(diff: i32) -> Option<f64> {
9278 let hp_frame = crate::tile::high_precision_mv();
9279 let mag = diff.unsigned_abs() as i32;
9280 let z = mag - 1;
9281 if !hp_frame && z & 1 == 0 {
9282 return None;
9283 }
9284 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
9285 let class = mv_class_of(z);
9286 bits += symbol_bits(&cdf::MV_CLASS, class);
9287 let local = z - mv_class_base(class);
9288 let hp = (local & 1) as usize;
9289 if class == 0 {
9290 let bit = (local >> 3) & 1;
9291 let fr = (local >> 1) & 3;
9292 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
9293 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
9294 // lane-hpmv: the writer codes the eighth-pel bit in a high-precision
9295 // frame, so the pricer charges for it there and only there.
9296 if hp_frame {
9297 bits += symbol_bits(&cdf::MV_CLASS0_HP, hp);
9298 }
9299 } else {
9300 let d = local >> 3;
9301 let fr = (local >> 1) & 3;
9302 for i in 0..class {
9303 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
9304 }
9305 bits += symbol_bits(&cdf::MV_FR, fr as usize);
9306 if hp_frame {
9307 bits += symbol_bits(&cdf::MV_HP, hp);
9308 }
9309 }
9310 Some(bits)
9311}
9312
9313/// Whether `LAST2_FRAME` gets a `NEWMV` search of its own beside the
9314/// neighbour-derived modes ([`extra_ref_new_mv`]'s per-reference switch,
9315/// `EC_AV1_LAST2_NEW=0`): the charter's "free arm", i.e. the reference's
9316/// value without the second motion search's wall.
9317fn last2_new_mv() -> bool {
9318 match std::env::var("EC_AV1_LAST2_NEW").ok() {
9319 Some(v) => v != "0",
9320 None => true,
9321 }
9322}
9323
9324/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
9325/// own -- a second motion search per block against that reference's picture,
9326/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
9327/// off in a test build (what the lane measured both arms with).
9328fn extra_ref_new_mv() -> bool {
9329 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
9330 Some(v) if cfg!(test) => v != "0",
9331 _ => crate::speed::at(&crate::speed::EXTRA_REF_NEW),
9332 }
9333}
9334
9335/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
9336/// flat slot plan (`inter_frame_headers_slots`): every reference but
9337/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
9338/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
9339/// frame two back when there is one (otherwise it, too, names the key frame's
9340/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
9341pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
9342 let last = order_hint.wrapping_sub(1) & 0x7f;
9343 let alt = if has_altref {
9344 order_hint.wrapping_sub(2) & 0x7f
9345 } else {
9346 key_hint
9347 };
9348 [last, last, last, key_hint, last, last, alt]
9349}
9350
9351/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
9352/// header bit that lets each block choose between a single and a compound
9353/// reference. Off by default until compound prediction is measured to pay;
9354/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
9355/// runs as), and every block still codes SINGLE, so the only cost is one
9356/// `comp_mode` symbol per inter block.
9357pub(crate) const REFERENCE_SELECT: bool = true;
9358
9359/// [`REFERENCE_SELECT`], with the test-build environment override.
9360pub(crate) fn reference_select() -> bool {
9361 match std::env::var("EC_AV1_COMPOUND").ok() {
9362 Some(v) if cfg!(test) => v != "0",
9363 _ => crate::speed::at(&crate::speed::COMPOUND),
9364 }
9365}
9366
9367/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
9368/// per entry past `start`, `1` to advance and `0` to stop, at most two.
9369fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
9370 let mut bits = 0.0;
9371 let mut idx = start;
9372 while idx < start + 2 && stack.entries.len() > idx + 1 {
9373 let advance = idx < target;
9374 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
9375 if !advance {
9376 break;
9377 }
9378 idx += 1;
9379 }
9380 bits
9381}
9382
9383/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
9384/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
9385/// `assign_mv`), so the same vector costs a different residual from each.
9386fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
9387 let mut best: Option<(f64, u8)> = None;
9388 for idx in 0..3usize {
9389 if idx > 0 && stack.entries.len() <= idx {
9390 break;
9391 }
9392 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
9393 if let Some(b) = mv_residual_bits(mv, base) {
9394 let total = b + drl_bits_for(stack, 0, idx);
9395 if best.is_none_or(|(t, _)| total < t) {
9396 best = Some((total, idx as u8));
9397 }
9398 }
9399 }
9400 best
9401}
9402
9403/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
9404/// zero vector and the stack's own candidates. A neighbour block's vector is
9405/// where this block's motion most often already is, which is what pays for
9406/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
9407/// vs libaom for 0.2 s off a 6 s ladder).
9408fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
9409 let mut seeds = [(0, 0); 4];
9410 let mut n = 1;
9411 for e in stack.entries.iter().take(3) {
9412 seeds[n] = e.mv;
9413 n += 1;
9414 }
9415 (seeds, n)
9416}
9417
9418/// What [`crate::tile::write_mv`] (private to that module) would spend
9419/// coding `mv` as a residual against `pred`: the joint symbol naming which
9420/// components differ, then each differing component. `None` under the same
9421/// condition [`mv_component_bits`] returns `None`.
9422/// How many frames back `ref_frame` sits from the frame being coded, off the
9423/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
9424/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
9425/// what [`crate::motion::search`] scales its starting step by.
9426fn ref_distance(ref_frame: i8) -> u32 {
9427 let (bits, order_hint, hints) = crate::tile::order_hints();
9428 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
9429 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
9430 .unsigned_abs()
9431 .max(1);
9432 if crate::envflags::env_flag!("EC_TRACE_DIST") {
9433 eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]);
9434 }
9435 d
9436}
9437
9438fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
9439 let diff = (mv.0 - pred.0, mv.1 - pred.1);
9440 let joint = match (diff.0 != 0, diff.1 != 0) {
9441 (false, false) => 0,
9442 (false, true) => 1,
9443 (true, false) => 2,
9444 (true, true) => 3,
9445 };
9446 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
9447 for d in [diff.0, diff.1] {
9448 if d != 0 {
9449 bits += mv_component_bits(d)?;
9450 }
9451 }
9452 Some(bits)
9453}
9454
9455/// Rounds `mv` so that its residual against `pred` is one
9456/// [`crate::tile::write_mv_component`] can actually code: each component's
9457/// difference is either zero or has an even magnitude (the eighth-pel bit
9458/// `allow_high_precision_mv` off always infers as one forces the coded
9459/// magnitude odd one step further in, which comes out even here since this
9460/// crate's motion search works in whole units of that same step). Rounding
9461/// down keeps every coded MV — and so every `nearest_mv` a later block's
9462/// stack votes with — built from an even displacement from `(0, 0)`, so the
9463/// invariant holds without this function seeing the whole stack.
9464/// A PROCESS-GLOBAL [`high_precision_mv_at`] override that wins over both
9465/// the threshold and the environment (`u8::MAX` = unset, `0` = never, `1` =
9466/// always), the shape [`set_frame_interp`] has: the witness that has to see
9467/// `mv_hp` symbols coded turns it on through this while holding
9468/// [`crate::speed::knob_write`].
9469static HP_MV_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
9470
9471/// Sets [`HP_MV_OVERRIDE`]; `None` clears it.
9472#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
9473pub(crate) fn set_high_precision_mv(on: Option<bool>) {
9474 HP_MV_OVERRIDE.store(on.map_or(u8::MAX, u8::from), std::sync::atomic::Ordering::Relaxed);
9475}
9476
9477/// The qindex below which an inter frame codes `allow_high_precision_mv`
9478/// (lane-hpmv). libaom's `HIGH_PRECISION_MV_QTHRESH` is 128; `0` is this
9479/// crate's shipped value, i.e. high-precision motion vectors off in every
9480/// frame -- see `lanes/hpmv.report.md` for the sweep that chose it.
9481pub(crate) const HP_MV_QTHRESH: u8 = 0;
9482
9483/// Whether an inter frame at `base_q_idx` carries `allow_high_precision_mv`:
9484/// [`HP_MV_QTHRESH`], overridable by `EC_AV1_HP_MV` (`0`/`off` never, `all`
9485/// always, any number as the threshold) so the BD gate can sweep the policy
9486/// without a rebuild.
9487pub(crate) fn high_precision_mv_at(base_q_idx: u8) -> bool {
9488 match HP_MV_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
9489 0 => return false,
9490 1 => return true,
9491 _ => {}
9492 }
9493 static T: std::sync::OnceLock<u16> = std::sync::OnceLock::new();
9494 let threshold = *T.get_or_init(|| match std::env::var("EC_AV1_HP_MV").ok().as_deref() {
9495 Some("all" | "always") => 256,
9496 Some("0" | "off") => 0,
9497 Some(v) => v.parse().unwrap_or(u16::from(HP_MV_QTHRESH)),
9498 None => u16::from(HP_MV_QTHRESH),
9499 });
9500 u16::from(base_q_idx) < threshold
9501}
9502
9503fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
9504 // lane-hpmv: with `allow_high_precision_mv` on, every eighth-pel
9505 // residual is codable and there is nothing to round away.
9506 if crate::tile::high_precision_mv() {
9507 return mv;
9508 }
9509 let round = |m: i32, p: i32| {
9510 let diff = m - p;
9511 let mag = diff.unsigned_abs() as i32;
9512 let even = mag - mag % 2;
9513 if even == 0 {
9514 p
9515 } else {
9516 p + even * diff.signum()
9517 }
9518 };
9519 (round(mv.0, pred.0), round(mv.1, pred.1))
9520}
9521
9522/// Predicts one `side`-square block by motion compensation from `reference`
9523/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
9524#[allow(clippy::too_many_arguments)]
9525fn mc_trial(
9526 plane: &Plane,
9527 x: usize,
9528 y: usize,
9529 side: usize,
9530 mv: (i32, i32),
9531 luma: bool,
9532 reference: &[u16],
9533 stride: usize,
9534 ref_width: usize,
9535 ref_height: usize,
9536 skip: bool,
9537 base_q_idx: u8,
9538 deadzone: f64,
9539 set: TxbSet,
9540 fctx: &crate::decode::FrameCtx,
9541) -> Trial {
9542 mc_trial_typed(
9543 plane, x, y, side, mv, luma, reference, stride, ref_width, ref_height, skip, base_q_idx,
9544 deadzone, set, TxType::DctDct, fctx,
9545 )
9546}
9547
9548/// [`mc_trial`] coding its residual with a named transform type (lane-txset2).
9549#[allow(clippy::too_many_arguments)]
9550fn mc_trial_typed(
9551 plane: &Plane,
9552 x: usize,
9553 y: usize,
9554 side: usize,
9555 mv: (i32, i32),
9556 luma: bool,
9557 reference: &[u16],
9558 stride: usize,
9559 ref_width: usize,
9560 ref_height: usize,
9561 skip: bool,
9562 base_q_idx: u8,
9563 deadzone: f64,
9564 set: TxbSet,
9565 tx_type: TxType,
9566 fctx: &crate::decode::FrameCtx,
9567) -> Trial {
9568 let x_q4 = mv_to_q4(x, mv.1, luma);
9569 let y_q4 = mv_to_q4(y, mv.0, luma);
9570 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
9571 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
9572 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
9573 // lane-av1speed: both buffers are per-candidate scratch on the hottest
9574 // path in the encoder, so they live on the stack -- `side` is at most
9575 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
9576 // per motion-compensated trial otherwise.
9577 let mut prediction16 = [0u16; BLOCK * BLOCK];
9578 let prediction16 = &mut prediction16[..side * side];
9579 mc::predict(
9580 reference,
9581 stride,
9582 ref_width,
9583 ref_height,
9584 x_q4,
9585 y_q4,
9586 side,
9587 side,
9588 prediction16, fctx,
9589 );
9590 let mut prediction = [0u8; BLOCK * BLOCK];
9591 let prediction = &mut prediction[..side * side];
9592 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
9593 *dst = src as u8;
9594 }
9595 plane.code_from_prediction_typed(
9596 x, y, side, prediction, skip, base_q_idx, deadzone, set, tx_type,
9597 )
9598}
9599
9600/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
9601/// references predict into the `CONV_BUF` intermediate domain
9602/// ([`mc::predict_compound_intermediate`]) and are blended by
9603/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
9604/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
9605/// block, so the encoder's reconstruction is the decoder's.
9606#[allow(clippy::too_many_arguments)]
9607fn mc_trial_compound(
9608 plane: &Plane,
9609 x: usize,
9610 y: usize,
9611 side: usize,
9612 mvs: ((i32, i32), (i32, i32)),
9613 luma: bool,
9614 ref0: (&[u16], usize, usize, usize),
9615 ref1: (&[u16], usize, usize, usize),
9616 base_q_idx: u8,
9617 deadzone: f64,
9618 set: TxbSet,
9619 fctx: &crate::decode::FrameCtx,
9620) -> Trial {
9621 mc_trial_compound_typed(
9622 plane, x, y, side, mvs, luma, ref0, ref1, base_q_idx, deadzone, set, TxType::DctDct, fctx,
9623 )
9624}
9625
9626/// [`mc_trial_compound`] coding its residual with a named transform type
9627/// (lane-txset2).
9628#[allow(clippy::too_many_arguments)]
9629fn mc_trial_compound_typed(
9630 plane: &Plane,
9631 x: usize,
9632 y: usize,
9633 side: usize,
9634 (mv0, mv1): ((i32, i32), (i32, i32)),
9635 luma: bool,
9636 ref0: (&[u16], usize, usize, usize),
9637 ref1: (&[u16], usize, usize, usize),
9638 base_q_idx: u8,
9639 deadzone: f64,
9640 set: TxbSet,
9641 tx_type: TxType,
9642 fctx: &crate::decode::FrameCtx,
9643) -> Trial {
9644 let mut inter0 = [0i32; BLOCK * BLOCK];
9645 let mut inter1 = [0i32; BLOCK * BLOCK];
9646 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
9647 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
9648 mc::predict_compound_intermediate(
9649 r.0,
9650 r.1,
9651 r.2,
9652 r.3,
9653 mv_to_q4(x, mv.1, luma),
9654 mv_to_q4(y, mv.0, luma),
9655 mc::REF_NO_SCALE,
9656 side,
9657 side,
9658 fctx.interp_filter.get(),
9659 fctx.interp_filter.get(),
9660 dst,
9661 );
9662 }
9663 let mut blended16 = [0u16; BLOCK * BLOCK];
9664 let blended16 = &mut blended16[..side * side];
9665 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
9666 let mut prediction = [0u8; BLOCK * BLOCK];
9667 let prediction = &mut prediction[..side * side];
9668 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
9669 *dst = src as u8;
9670 }
9671 plane.code_from_prediction_typed(
9672 x, y, side, prediction, false, base_q_idx, deadzone, set, tx_type,
9673 )
9674}
9675
9676/// Codes one 32x32 block of an inter frame as whichever costs least of: each
9677/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
9678/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
9679/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
9680/// coding a real residual (`skip: false`) whenever one prices out cheaper
9681/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
9682/// missing inter `tx_type` symbol (the desync this function's candidates
9683/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
9684/// fixed.
9685///
9686/// The symbol costs this ranks candidates by use fixed contexts (0) for
9687/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
9688/// contexts for those come from its own neighbour bookkeeping
9689/// (`tile::Neighbours`), which is private to that module and not worth
9690/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
9691/// `drl_mode` contexts come straight from `stack`, which is exact, because
9692/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
9693/// the tile writer derives from the same grid state.
9694#[allow(clippy::too_many_arguments)]
9695/// One prediction of `side` x `side` samples from `reference`, as `u8` --
9696/// [`mc_trial`]'s prediction half, on the heap because a 64x64 luma block is
9697/// four times the stack scratch that function sizes for [`BLOCK`].
9698fn predict_u8(
9699 reference: &[u16],
9700 stride: usize,
9701 ref_width: usize,
9702 ref_height: usize,
9703 (x, y): (usize, usize),
9704 side: usize,
9705 mv: (i32, i32),
9706 luma: bool,
9707 fctx: &crate::decode::FrameCtx,
9708) -> Vec<u8> {
9709 let mut prediction = vec![0u16; side * side];
9710 mc::predict(
9711 reference,
9712 stride,
9713 ref_width,
9714 ref_height,
9715 mv_to_q4(x, mv.1, luma),
9716 mv_to_q4(y, mv.0, luma),
9717 side,
9718 side,
9719 &mut prediction,
9720 fctx,
9721 );
9722 prediction.iter().map(|&v| v as u8).collect()
9723}
9724
9725/// [`predict_u8`]'s compound counterpart, on the heap because a 64x64 root's
9726/// side is twice what [`mc_trial_compound`]'s fixed trial buffers hold: both
9727/// references predict into the `CONV_BUF` intermediate domain and are blended
9728/// at the simple-average split `(8, 8)`, the same path (and so the same
9729/// samples) a `comp_group_idx == 0`, `compound_idx == 1` decoder computes.
9730fn predict_compound_u8(
9731 ref0: (&[u16], usize, usize, usize),
9732 ref1: (&[u16], usize, usize, usize),
9733 (x, y): (usize, usize),
9734 side: usize,
9735 (mv0, mv1): ((i32, i32), (i32, i32)),
9736 luma: bool,
9737 fctx: &crate::decode::FrameCtx,
9738) -> Vec<u8> {
9739 let mut inter = [vec![0i32; side * side], vec![0i32; side * side]];
9740 for ((mv, r), dst) in [(mv0, ref0), (mv1, ref1)].into_iter().zip(inter.iter_mut()) {
9741 mc::predict_compound_intermediate(
9742 r.0,
9743 r.1,
9744 r.2,
9745 r.3,
9746 mv_to_q4(x, mv.1, luma),
9747 mv_to_q4(y, mv.0, luma),
9748 mc::REF_NO_SCALE,
9749 side,
9750 side,
9751 fctx.interp_filter.get(),
9752 fctx.interp_filter.get(),
9753 dst,
9754 );
9755 }
9756 let mut blended = vec![0u16; side * side];
9757 mc::combine_compound(&inter[0], &inter[1], 8, 8, &mut blended, fctx);
9758 blended.iter().map(|&v| v as u8).collect()
9759}
9760
9761/// lane-b128: the 128x128 `PARTITION_NONE` candidate for a whole 128
9762/// superblock root, the lever cen3's L1 asks for -- one block, one mode and
9763/// one motion vector where the four 64x64 roots below spend four of each.
9764///
9765/// SKIP only (`residual: false`): a 128x128 block's residual is four
9766/// TX_64X64 luma units interleaved with a TX_32X32 chroma pair per 64x64 mu
9767/// chunk, which neither the writer nor [`Plane::code_from_prediction`] has a
9768/// path for -- offering one here would price a block
9769/// [`crate::tile::write_inter_block_128`] refuses. Single reference only for
9770/// the same reason: the compound arm at this size is untested against the
9771/// writer's own `write_compound_block` window.
9772///
9773/// Only a root whose whole 128x128 lies inside the true frame AND inside
9774/// this tile is offered: the writer's own root codes `PARTITION_NONE` only
9775/// where the spec's `has_rows`/`has_cols` are both set, and a straddling
9776/// block would have to be ranked over its inside part alone.
9777///
9778/// Returns `(cost, lambda, block, reconstruction)` -- the cost already
9779/// carries the root's own `PARTITION_NONE` symbol, so the caller weighs it
9780/// against the four superblocks plus the SPLIT symbol.
9781#[allow(clippy::too_many_arguments)]
9782fn search_root_128(
9783 luma: &mut Plane,
9784 chroma: &mut [Plane; 2],
9785 grid: &crate::mvstack::MiGrid,
9786 (root_r, root_c): (usize, usize),
9787 // The 32x32-block grid this tile's `blocks` vector is indexed on.
9788 (rows, cols): (usize, usize),
9789 // The frame's own mode-info grid, which bounds the root.
9790 (mi_cols, mi_rows): (u32, u32),
9791 search: Search<'_>,
9792 tpl_factors: &Option<Vec<f64>>,
9793 sb_q: Option<&Vec<u8>>,
9794 sb_cols: usize,
9795 tpl_cells_x: usize,
9796 base_q_idx: u8,
9797 // lane-rectdq: `1 << delta_q_res` when this frame codes a delta_q plan,
9798 // zero when it does not -- what [`delta_q_bits_at_root`] prices with.
9799 dq_res: i32,
9800 reference: &Picture,
9801 // The `LAST` + extra-reference pairs at THIS ROOT's own 32x32-mi window,
9802 // built by the caller off the same grid the tile writer rebuilds its
9803 // stack from (empty unless the frame carries `reference_select` and
9804 // [`b128_compound`] is on).
9805 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
9806 fctx: &crate::decode::FrameCtx,
9807) -> Option<(f64, f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> {
9808 const SIDE: usize = SUPERBLOCK * 2;
9809 const SIDE_MI: usize = SIDE / 4;
9810 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
9811 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
9812 if root_r * 2 + 3 >= rows
9813 || root_c * 2 + 3 >= cols
9814 || (mi_row + SIDE_MI) as u32 > mi_rows
9815 || (mi_col + SIDE_MI) as u32 > mi_cols
9816 || x128 + SIDE > luma.true_width
9817 || y128 + SIDE > luma.true_height
9818 {
9819 return None;
9820 }
9821 // One lambda for the whole root, the mean of what its four superblocks
9822 // would each be searched at -- the 128-vs-four comparison weighs one cost
9823 // against four, so both sides have to be priced at the same lambda (the
9824 // same rule the 64 root's own mean-of-sixteen tpl cells follows).
9825 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
9826 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
9827 (None, Some(f)) => {
9828 let mean = (0..16)
9829 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
9830 .sum::<f64>()
9831 / 16.0;
9832 search.lambda * mean
9833 }
9834 (None, None) => search.lambda,
9835 };
9836 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
9837 .iter()
9838 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
9839 .sum::<f64>()
9840 / 4.0;
9841 // The qindex this root is really quantized at: the delta_q unit is the
9842 // 128 superblock, so the root's own top-left cell is the one coded
9843 // (lane-b128m), and the residual arm below has to quantize at exactly it.
9844 let root_search = Search {
9845 lambda,
9846 ..match sb_q {
9847 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
9848 None => search,
9849 }
9850 };
9851 let stack = find_mv_stack(
9852 grid,
9853 mi_row,
9854 mi_col,
9855 SIDE_MI,
9856 SIDE_MI,
9857 LAST_FRAME,
9858 mi_cols as usize,
9859 mi_rows as usize,
9860 );
9861 let base = snapshot(luma, chroma, (x128, y128), SIDE);
9862 let found = search_skip_64(
9863 luma,
9864 chroma,
9865 (x128, y128),
9866 (SIDE, SIDE),
9867 &root_search,
9868 false,
9869 reference,
9870 &stack,
9871 compound,
9872 fctx,
9873 );
9874 let (mut cost, mut block) = found?;
9875 if block.inter.is_some_and(|i| i.ref1.is_some()) {
9876 B128_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9877 }
9878 // lane-b128r: the same prediction with a REAL residual, priced against
9879 // the skip arm the search just committed to the planes (which IS the
9880 // winner's prediction, sample for sample). The block's residual is four
9881 // TX_64X64 luma units, one per 64x64 mu chunk, each interleaved with its
9882 // own TX_32X32 chroma pair -- so it is coded here as twelve trials at
9883 // sides the forward network already reaches, never as one 128-point
9884 // transform. Var-tx depth 0 only: the four units ARE the tree's leaves.
9885 //
9886 // The four `txfm_partition` symbols the writer codes for them are not
9887 // priced, exactly as the 64 root does not price its own (their contexts
9888 // are only known at write time); at four symbols a root this is under a
9889 // bit against residuals of hundreds.
9890 if b128_residual() && block.skip {
9891 // Every unit's coded level grid is 32x32 (a 64-point transform codes
9892 // only its top-left corner), packed per plane into one 64-wide grid
9893 // with chunk (cr, cc) at (cr * 32, cc * 32) -- the layout
9894 // `write_inter_block_128` slices back out in the same chunk order.
9895 let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
9896 let mut chunks: Vec<((usize, usize), [Trial; 3])> = Vec::new();
9897 let (mut sse_skip, mut sse_res, mut coeff_bits) = (0.0f64, 0.0f64, 0.0f64);
9898 for (cr, cc) in [(0usize, 0usize), (0, 1), (1, 0), (1, 1)] {
9899 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
9900 let (cx, cy) = (px / 2, py / 2);
9901 let half = SUPERBLOCK / 2;
9902 let pred_y = rows_of(&luma.reconstruction, luma.width, px, py, SUPERBLOCK);
9903 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
9904 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
9905 sse_skip += luma.block_sse(px, py, SUPERBLOCK, &pred_y)
9906 + chroma[0].block_sse(cx, cy, half, &pred_u)
9907 + chroma[1].block_sse(cx, cy, half, &pred_v);
9908 let trials = [
9909 luma.code_from_prediction(
9910 px, py, SUPERBLOCK, &pred_y, false, root_search.base_q_idx,
9911 root_search.deadzone, TxbSet::Luma64,
9912 ),
9913 chroma[0].code_from_prediction(
9914 cx, cy, half, &pred_u, false, root_search.base_q_idx,
9915 root_search.deadzone, TxbSet::Chroma32,
9916 ),
9917 chroma[1].code_from_prediction(
9918 cx, cy, half, &pred_v, false, root_search.base_q_idx,
9919 root_search.deadzone, TxbSet::Chroma32,
9920 ),
9921 ];
9922 for (plane, trial) in trials.iter().enumerate() {
9923 sse_res += trial.sse;
9924 coeff_bits += trial.bits;
9925 for row in 0..32 {
9926 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
9927 .copy_from_slice(&trial.levels[row * 32..][..32]);
9928 }
9929 }
9930 chunks.push(((cr, cc), trials));
9931 }
9932 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual
9933 // arm pays the same syntax with `skip` coded 0 instead of 1, plus its
9934 // coefficients.
9935 let unskip = skip_bits_at(&stack, false) - skip_bits_at(&stack, true);
9936 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
9937 if res_cost < cost || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed) {
9938 B128_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
9939 for ((cr, cc), trials) in &chunks {
9940 let (px, py) = (x128 + cc * SUPERBLOCK, y128 + cr * SUPERBLOCK);
9941 let half = SUPERBLOCK / 2;
9942 luma.commit(px, py, SUPERBLOCK, &trials[0]);
9943 chroma[0].commit(px / 2, py / 2, half, &trials[1]);
9944 chroma[1].commit(px / 2, py / 2, half, &trials[2]);
9945 }
9946 cost = res_cost;
9947 block.skip = false;
9948 block.tx_depth = 0;
9949 block.luma_tx_types = Vec::new();
9950 block.luma = coeffs(&packed[0], 64);
9951 block.u = coeffs(&packed[1], 64);
9952 block.v = coeffs(&packed[2], 64);
9953 }
9954 }
9955 let after = snapshot(luma, chroma, (x128, y128), SIDE);
9956 restore(luma, chroma, (x128, y128), SIDE, &base);
9957 // lane-rectdq: a SKIPPED whole-superblock root is the one shape that
9958 // codes no delta_q group (`write_delta_q`'s `is_whole_sb && skip`); the
9959 // residual arm above codes it like every other block does.
9960 let dq = if block.skip {
9961 0.0
9962 } else {
9963 delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c))
9964 };
9965 Some((
9966 cost + lambda * (crate::tile::partition_bits(SIDE, false) + dq),
9967 lambda,
9968 block,
9969 after,
9970 ))
9971}
9972
9973/// lane-rectres: one rect/AB piece's REAL residual, priced against the skip
9974/// arm the caller's [`search_skip_64`] just committed to the planes (which
9975/// IS the winner's prediction, sample for sample -- the same rule
9976/// [`search_root_128`]'s residual arm runs at the NONE root). The piece's
9977/// residual is one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
9978/// mu chunk (two chunks for a 128x64 / 64x128 half, one for a 64x64 square),
9979/// each trial at sides the forward network already reaches, never a
9980/// rectangular transform; var-tx depth 0 only -- the units ARE the tree's
9981/// leaves, exactly what `decode_inter_block`'s mu-chunk loop reads.
9982///
9983/// The depth-0 `txfm_partition` symbols the writer codes for the units are
9984/// not priced, exactly as [`search_root_128`] does not price its four (their
9985/// contexts are only known at write time); at two symbols a half this is
9986/// under a bit against residuals of hundreds. On a win (or under the witness
9987/// force) the trials are committed to the planes, `block` is flipped to
9988/// carry the packed level grids [`crate::tile::write_inter_block_128_rect`]
9989/// slices back out, and the new cost is returned; otherwise `cost` passes
9990/// through untouched. Counts [`take_b128_rectres_hits`] on a win.
9991#[allow(clippy::too_many_arguments)]
9992fn search_rect_residual(
9993 luma: &mut Plane,
9994 chroma: &mut [Plane; 2],
9995 // The piece's own top-left, in luma samples.
9996 (px, py): (usize, usize),
9997 // Its true footprint: (128, 64) HORZ, (64, 128) VERT, (64, 64) square.
9998 (w, h): (usize, usize),
9999 cost: f64,
10000 lambda: f64,
10001 search: &Search<'_>,
10002 // The piece's own mv stack, for the skip symbol's cost either way.
10003 stack: &crate::mvstack::MvStack,
10004 block: &mut BlockCoeffs,
10005) -> f64 {
10006 /// The 64x64 "mu" chunk side, luma; chroma halves it.
10007 const MU: usize = SUPERBLOCK;
10008 let chunks: [(usize, usize); 2] = match (w, h) {
10009 (128, 64) => [(0, 0), (0, 1)],
10010 (64, 128) => [(0, 0), (1, 0)],
10011 _ => [(0, 0), (0, 0)],
10012 };
10013 let n = if w.max(h) > MU { 2 } else { 1 };
10014 // Every unit's coded level grid is 32x32 (a 64-point transform codes
10015 // only its top-left corner), packed per plane into one 64-wide grid with
10016 // chunk (cr, cc) at (cr * 32, cc * 32) -- the layout the writer slices
10017 // back out in the same chunk order.
10018 let mut packed = [vec![0i32; 64 * 64], vec![0i32; 64 * 64], vec![0i32; 64 * 64]];
10019 let mut sse_skip = 0.0f64;
10020 let mut sse_res = 0.0f64;
10021 let mut coeff_bits = 0.0f64;
10022 let mut trials_per_chunk: Vec<[Trial; 3]> = Vec::with_capacity(n);
10023 for &(cr, cc) in &chunks[..n] {
10024 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10025 let (cx, cy) = (cxx / 2, cyy / 2);
10026 let half = MU / 2;
10027 let pred_y = rows_of(&luma.reconstruction, luma.width, cxx, cyy, MU);
10028 let pred_u = rows_of(&chroma[0].reconstruction, chroma[0].width, cx, cy, half);
10029 let pred_v = rows_of(&chroma[1].reconstruction, chroma[1].width, cx, cy, half);
10030 sse_skip += luma.block_sse(cxx, cyy, MU, &pred_y)
10031 + chroma[0].block_sse(cx, cy, half, &pred_u)
10032 + chroma[1].block_sse(cx, cy, half, &pred_v);
10033 let trials = [
10034 luma.code_from_prediction(
10035 cxx, cyy, MU, &pred_y, false, search.base_q_idx, search.deadzone,
10036 TxbSet::Luma64,
10037 ),
10038 chroma[0].code_from_prediction(
10039 cx, cy, half, &pred_u, false, search.base_q_idx, search.deadzone,
10040 TxbSet::Chroma32,
10041 ),
10042 chroma[1].code_from_prediction(
10043 cx, cy, half, &pred_v, false, search.base_q_idx, search.deadzone,
10044 TxbSet::Chroma32,
10045 ),
10046 ];
10047 for (plane, trial) in trials.iter().enumerate() {
10048 sse_res += trial.sse;
10049 coeff_bits += trial.bits;
10050 for row in 0..32 {
10051 packed[plane][(cr * 32 + row) * 64 + cc * 32..][..32]
10052 .copy_from_slice(&trial.levels[row * 32..][..32]);
10053 }
10054 }
10055 trials_per_chunk.push(trials);
10056 }
10057 // `cost` is the skip arm's own `sse + lambda * syntax`; the residual arm
10058 // pays the same syntax with `skip` coded 0 instead of 1, plus its
10059 // coefficients.
10060 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10061 let res_cost = cost - sse_skip + sse_res + lambda * (unskip + coeff_bits);
10062 if res_cost < cost || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed) {
10063 for (trials, &(cr, cc)) in trials_per_chunk.iter().zip(&chunks[..n]) {
10064 let (cxx, cyy) = (px + cc * MU, py + cr * MU);
10065 let (cx, cy) = (cxx / 2, cyy / 2);
10066 let half = MU / 2;
10067 luma.commit(cxx, cyy, MU, &trials[0]);
10068 chroma[0].commit(cx, cy, half, &trials[1]);
10069 chroma[1].commit(cx, cy, half, &trials[2]);
10070 }
10071 block.skip = false;
10072 block.tx_depth = 0;
10073 block.luma_tx_types = Vec::new();
10074 block.luma = coeffs(&packed[0], 64);
10075 block.u = coeffs(&packed[1], 64);
10076 block.v = coeffs(&packed[2], 64);
10077 B128_RECTRES_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10078 res_cost
10079 } else {
10080 cost
10081 }
10082}
10083
10084/// lane-b128hv: the `PARTITION_HORZ` / `PARTITION_VERT` candidate for a whole
10085/// 128 superblock root -- two 128x64 (`horz`) or 64x128 inter blocks, the
10086/// shipped NONE machinery halved. Skip-only by default, single reference or
10087/// compound; under `EC_AV1_RECTRES` each half also prices a REAL residual
10088/// ([`search_rect_residual`]) -- exactly what
10089/// `crate::tile::write_inter_block_128_rect` codes and `decode_inter_block`
10090/// reads at `sb128_rect`.
10091///
10092/// The FIRST half is published into `grid` before the second is searched --
10093/// the writer publishes it too, so a second half searched against the stale
10094/// grid would be priced (and its mv predicted) off a stack the decoder never
10095/// derives (class `encoder-grid-drift-invisible-to-pixel-gate`). The grid and
10096/// both planes are put back before returning; the caller re-applies the
10097/// winner.
10098///
10099/// Returns `(cost, lambda, the two halves, reconstruction)`, the cost already
10100/// carrying the root's own partition symbol so it ranks against
10101/// [`search_root_128`] and against the four superblocks below.
10102#[allow(clippy::too_many_arguments)]
10103fn search_root_128_rect(
10104 luma: &mut Plane,
10105 chroma: &mut [Plane; 2],
10106 grid: &mut crate::mvstack::MiGrid,
10107 (root_r, root_c): (usize, usize),
10108 (rows, cols): (usize, usize),
10109 (mi_cols, mi_rows): (u32, u32),
10110 search: Search<'_>,
10111 tpl_factors: &Option<Vec<f64>>,
10112 sb_q: Option<&Vec<u8>>,
10113 sb_cols: usize,
10114 tpl_cells_x: usize,
10115 base_q_idx: u8,
10116 // lane-rectdq: see [`search_root_128`]'s own `dq_res`.
10117 dq_res: i32,
10118 reference: &Picture,
10119 // The `LAST` + extra-reference pairs offered at this root; only the
10120 // reference and its picture are read here, since each HALF derives its
10121 // own compound stack at its own rectangular window.
10122 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10123 horz: bool,
10124 fctx: &crate::decode::FrameCtx,
10125) -> Option<(f64, f64, [BlockCoeffs; 2], [(Vec<u8>, Vec<CoefCtx>); 3])> {
10126 const SIDE: usize = SUPERBLOCK * 2;
10127 const SIDE_MI: usize = SIDE / 4;
10128 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10129 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10130 if root_r * 2 + 3 >= rows
10131 || root_c * 2 + 3 >= cols
10132 || (mi_row + SIDE_MI) as u32 > mi_rows
10133 || (mi_col + SIDE_MI) as u32 > mi_cols
10134 || x128 + SIDE > luma.true_width
10135 || y128 + SIDE > luma.true_height
10136 {
10137 return None;
10138 }
10139 // The root's own lambda, the mean of its four superblocks' -- the same
10140 // one [`search_root_128`] prices with, so the three root candidates and
10141 // the four-superblock arm are all comparable.
10142 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10143 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10144 (None, Some(f)) => {
10145 let mean = (0..16)
10146 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10147 .sum::<f64>()
10148 / 16.0;
10149 search.lambda * mean
10150 }
10151 (None, None) => search.lambda,
10152 };
10153 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10154 .iter()
10155 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10156 .sum::<f64>()
10157 / 4.0;
10158 let root_search = Search {
10159 lambda,
10160 ..match sb_q {
10161 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10162 None => search,
10163 }
10164 };
10165 let (w, h) = if horz { (SIDE, SUPERBLOCK) } else { (SUPERBLOCK, SIDE) };
10166 let (w_mi, h_mi) = (w / 4, h / 4);
10167 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10168 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
10169 let mut cost = 0.0f64;
10170 let mut halves: Vec<BlockCoeffs> = Vec::with_capacity(2);
10171 for i in 0..2usize {
10172 let (mr, mc) = if horz {
10173 (mi_row + i * 16, mi_col)
10174 } else {
10175 (mi_row, mi_col + i * 16)
10176 };
10177 let stack = find_mv_stack(
10178 grid,
10179 mr,
10180 mc,
10181 w_mi,
10182 h_mi,
10183 LAST_FRAME,
10184 mi_cols as usize,
10185 mi_rows as usize,
10186 );
10187 let half_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
10188 .iter()
10189 .map(|&(r, pic, _)| {
10190 (
10191 r,
10192 pic,
10193 crate::mvstack::find_mv_stack_compound(
10194 grid,
10195 mr,
10196 mc,
10197 w_mi,
10198 h_mi,
10199 (LAST_FRAME, r),
10200 mi_cols as usize,
10201 mi_rows as usize,
10202 grid.sign_bias_table(),
10203 &[(0, 0); 7],
10204 None,
10205 ),
10206 )
10207 })
10208 .collect();
10209 let found = search_skip_64(
10210 luma,
10211 chroma,
10212 (mc * 4, mr * 4),
10213 (w, h),
10214 &root_search,
10215 false,
10216 reference,
10217 &stack,
10218 &half_compound,
10219 fctx,
10220 );
10221 match found {
10222 Some((mut c, mut block)) => {
10223 // lane-rectres: the same prediction with a REAL residual,
10224 // priced against the skip arm the search just committed to
10225 // the planes -- two 64x64 mu chunks for a half.
10226 if rectres() && block.skip {
10227 c = search_rect_residual(
10228 luma,
10229 chroma,
10230 (mc * 4, mr * 4),
10231 (w, h),
10232 c,
10233 root_search.lambda,
10234 &root_search,
10235 &stack,
10236 &mut block,
10237 );
10238 }
10239 cost += c;
10240 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
10241 halves.push(block);
10242 }
10243 None => {
10244 restore(luma, chroma, (x128, y128), SIDE, &base);
10245 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10246 return None;
10247 }
10248 }
10249 }
10250 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10251 restore(luma, chroma, (x128, y128), SIDE, &base);
10252 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10253 let symbol = if horz { 1 } else { 2 };
10254 let [b0, b1] = <[BlockCoeffs; 2]>::try_from(halves).ok()?;
10255 // lane-rectdq: the FIRST half sits at the root's own mode-info origin and
10256 // codes the delta_q group whether it is skipped or not
10257 // (`write_inter_block_128_rect` passes `is_whole_sb = false`); the second
10258 // half is at a non-origin mi and codes none.
10259 let dq = delta_q_bits_at_root(sb_q, sb_cols, base_q_idx, dq_res, (root_r, root_c));
10260 Some((
10261 cost + lambda * (crate::tile::partition_bits_sym(SIDE, symbol) + dq),
10262 lambda,
10263 [b0, b1],
10264 after,
10265 ))
10266}
10267
10268/// lane-ab128: one AB shape at a 128 superblock root -- two 64x64 blocks and
10269/// one 128x64 / 64x128 half, in the order [`ab128_pieces`] gives (the
10270/// decoder's own). Each piece is priced through the same `search_skip_64`
10271/// the NONE and HORZ/VERT arms use, at its own footprint, and is published
10272/// into `grid` before the next is searched -- the writer publishes it too, so
10273/// a later piece searched against a stale grid would be priced (and its mv
10274/// predicted) off a stack the decoder never derives (class
10275/// `encoder-grid-drift-invisible-to-pixel-gate`). The grid and both planes
10276/// are put back before returning; the caller re-applies the winner.
10277///
10278/// Skip-only by default; under `EC_AV1_RECTRES` each piece also prices a
10279/// REAL residual ([`search_rect_residual`]) -- the 64x64 squares are where
10280/// libaom's own AB shapes earn their keep.
10281///
10282/// Returns `(cost, lambda, the three pieces, reconstruction)`, the cost
10283/// already carrying the root's own partition symbol so it ranks against the
10284/// other root candidates and against the four superblocks below.
10285#[allow(clippy::too_many_arguments)]
10286fn search_root_128_ab(
10287 luma: &mut Plane,
10288 chroma: &mut [Plane; 2],
10289 grid: &mut crate::mvstack::MiGrid,
10290 (root_r, root_c): (usize, usize),
10291 (rows, cols): (usize, usize),
10292 (mi_cols, mi_rows): (u32, u32),
10293 search: Search<'_>,
10294 tpl_factors: &Option<Vec<f64>>,
10295 sb_q: Option<&Vec<u8>>,
10296 sb_cols: usize,
10297 tpl_cells_x: usize,
10298 base_q_idx: u8,
10299 reference: &Picture,
10300 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10301 // The partition symbol, 4..=7.
10302 symbol: usize,
10303 fctx: &crate::decode::FrameCtx,
10304) -> Option<(f64, f64, [BlockCoeffs; 3], [(Vec<u8>, Vec<CoefCtx>); 3])> {
10305 const SIDE: usize = SUPERBLOCK * 2;
10306 const SIDE_MI: usize = SIDE / 4;
10307 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
10308 let (mi_row, mi_col) = (root_r * 16, root_c * 16);
10309 if root_r * 2 + 3 >= rows
10310 || root_c * 2 + 3 >= cols
10311 || (mi_row + SIDE_MI) as u32 > mi_rows
10312 || (mi_col + SIDE_MI) as u32 > mi_cols
10313 || x128 + SIDE > luma.true_width
10314 || y128 + SIDE > luma.true_height
10315 {
10316 return None;
10317 }
10318 // The root's own lambda, the mean of its four superblocks' -- the same one
10319 // [`search_root_128`] prices with, so every root candidate and the
10320 // four-superblock arm are comparable.
10321 let cell_lambda = |sb_r: usize, sb_c: usize| match (sb_q, tpl_factors) {
10322 (Some(q), _) => sb_q_search(q, sb_cols, base_q_idx, (sb_r, sb_c), search).lambda,
10323 (None, Some(f)) => {
10324 let mean = (0..16)
10325 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
10326 .sum::<f64>()
10327 / 16.0;
10328 search.lambda * mean
10329 }
10330 (None, None) => search.lambda,
10331 };
10332 let lambda = [(0, 0), (0, 1), (1, 0), (1, 1)]
10333 .iter()
10334 .map(|&(dr, dc)| cell_lambda(root_r + dr, root_c + dc))
10335 .sum::<f64>()
10336 / 4.0;
10337 let root_search = Search {
10338 lambda,
10339 ..match sb_q {
10340 Some(q) => sb_q_search(q, sb_cols, base_q_idx, (root_r, root_c), search),
10341 None => search,
10342 }
10343 };
10344 let base = snapshot(luma, chroma, (x128, y128), SIDE);
10345 let grid_base = grid.snapshot_rect(mi_row, mi_col, SIDE_MI, SIDE_MI);
10346 let mut cost = 0.0f64;
10347 let mut pieces: Vec<BlockCoeffs> = Vec::with_capacity(3);
10348 for ((mr, mc), (w, h)) in ab128_pieces(symbol, (mi_row, mi_col)) {
10349 let (w_mi, h_mi) = (w / 4, h / 4);
10350 let stack = find_mv_stack(
10351 grid,
10352 mr,
10353 mc,
10354 w_mi,
10355 h_mi,
10356 LAST_FRAME,
10357 mi_cols as usize,
10358 mi_rows as usize,
10359 );
10360 let piece_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> = compound
10361 .iter()
10362 .map(|&(r, pic, _)| {
10363 (
10364 r,
10365 pic,
10366 crate::mvstack::find_mv_stack_compound(
10367 grid,
10368 mr,
10369 mc,
10370 w_mi,
10371 h_mi,
10372 (LAST_FRAME, r),
10373 mi_cols as usize,
10374 mi_rows as usize,
10375 grid.sign_bias_table(),
10376 &[(0, 0); 7],
10377 None,
10378 ),
10379 )
10380 })
10381 .collect();
10382 let found = search_skip_64(
10383 luma,
10384 chroma,
10385 (mc * 4, mr * 4),
10386 (w, h),
10387 &root_search,
10388 false,
10389 reference,
10390 &stack,
10391 &piece_compound,
10392 fctx,
10393 );
10394 match found {
10395 Some((mut c, mut block)) => {
10396 // lane-rectres: the same prediction with a REAL residual,
10397 // priced against the skip arm the search just committed to
10398 // the planes -- one mu chunk for a 64x64 square, two for a
10399 // half. The 64x64 squares are where libaom's own AB shapes
10400 // earn their keep.
10401 if rectres() && block.skip {
10402 c = search_rect_residual(
10403 luma,
10404 chroma,
10405 (mc * 4, mr * 4),
10406 (w, h),
10407 c,
10408 root_search.lambda,
10409 &root_search,
10410 &stack,
10411 &mut block,
10412 );
10413 }
10414 cost += c;
10415 record_mi_rect(grid, mr, mc, (w_mi, h_mi), block.inter, block.skip);
10416 pieces.push(block);
10417 }
10418 None => {
10419 restore(luma, chroma, (x128, y128), SIDE, &base);
10420 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10421 return None;
10422 }
10423 }
10424 }
10425 let after = snapshot(luma, chroma, (x128, y128), SIDE);
10426 restore(luma, chroma, (x128, y128), SIDE, &base);
10427 grid.restore_rect(mi_row, mi_col, SIDE_MI, SIDE_MI, &grid_base);
10428 let [b0, b1, b2] = <[BlockCoeffs; 3]>::try_from(pieces).ok()?;
10429 Some((
10430 cost + lambda * crate::tile::partition_bits_sym(SIDE, symbol),
10431 lambda,
10432 [b0, b1, b2],
10433 after,
10434 ))
10435}
10436
10437/// The 64x64 `PARTITION_NONE` candidate for a whole superblock ([`B64_ROOT`]):
10438/// single-reference LAST at `NEARESTMV`/`GLOBALMV`/`NEARMV`/`NEWMV`, coded
10439/// SKIP, priced through the same `symbol_bits` path every other candidate
10440/// uses. The winner's prediction is committed to the planes (it IS the
10441/// reconstruction -- a skip block has no residual); the caller restores them
10442/// if the four quadrants come out cheaper.
10443///
10444/// `None` when no candidate could be coded at all (a `NEWMV` residual the
10445/// writer cannot name is simply not offered, and the other modes always are,
10446/// so this only happens if every candidate is refused).
10447fn search_skip_64(
10448 luma: &mut Plane,
10449 chroma: &mut [Plane; 2],
10450 (x, y): (usize, usize),
10451 // The root's footprint in samples: [`SUPERBLOCK`] square at a 64 root,
10452 // twice that at the 128 one [`search_root_128`] drives (lane-b128), and
10453 // 128x64 / 64x128 at the rect halves of [`search_root_128_rect`]
10454 // (lane-b128hv). Every trial below tiles it into squares of its SHORTER
10455 // side (one square when it is square, two otherwise), and the residual
10456 // arm is only ever asked for at 64 -- a 128 block's residual is four
10457 // TX_64X64 units the writer has no path for.
10458 (bw, bh): (usize, usize),
10459 search: &Search,
10460 // Whether the non-skip arm is priced at all ([`b64_residual`], and off on
10461 // screen content -- see that function's doc).
10462 residual: bool,
10463 reference: &Picture,
10464 stack: &MvStack,
10465 // The COMPOUND stack of each `LAST` + extra-reference pair at THIS
10466 // superblock's 16x16-mi window, built off the same grid the tile writer
10467 // rebuilds it from (empty unless the frame carries `reference_select`).
10468 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10469 fctx: &crate::decode::FrameCtx,
10470) -> Option<(f64, BlockCoeffs)> {
10471 debug_assert!(
10472 (bw, bh) == (SUPERBLOCK, SUPERBLOCK) || !residual,
10473 "only a 64 root has a residual arm"
10474 );
10475 // The square units every trial below is taken on: the block itself when
10476 // it is square, its two halves otherwise. Luma first (in raster order),
10477 // then each chroma plane over the same tiling at half the side -- which is
10478 // exactly `[(0, x, y, side), (1, ..), (2, ..)]` at bw == bh.
10479 let sq = bw.min(bh);
10480 let units: Vec<(usize, usize, usize, usize, bool)> = (0..3usize)
10481 .flat_map(|plane| {
10482 let (ox, oy, s) = if plane == 0 { (x, y, sq) } else { (x / 2, y / 2, sq / 2) };
10483 (0..bh / sq).flat_map(move |j| {
10484 (0..bw / sq).map(move |i| (plane, ox + i * s, oy + j * s, s, plane == 0))
10485 })
10486 })
10487 .collect();
10488 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
10489 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
10490 let ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
10491 // What every candidate pays whatever its vector: `skip` coded 1, then
10492 // `is_inter` coded 1, then the LAST chain above.
10493 let fixed = skip_bits_at(stack, true) + intra_inter_bits_at(stack, true) + ref_bits;
10494 let info_of = |mode: InterMode, mv: (i32, i32), ref_mv_idx: u8| InterInfo {
10495 ref1: None,
10496 mv1: (0, 0),
10497 ref_frame: crate::mvstack::LAST_FRAME,
10498 mode,
10499 mv,
10500 ref_mv_idx,
10501 };
10502 let mut cands: Vec<(f64, InterInfo)> = vec![
10503 (
10504 not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
10505 info_of(InterMode::NearestMv, stack.nearest_mv, 0),
10506 ),
10507 (
10508 not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
10509 info_of(InterMode::GlobalMv, (0, 0), 0),
10510 ),
10511 ];
10512 let near_bits = not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
10513 for idx in 1..=2usize {
10514 if let Some(e) = stack.entries.get(idx) {
10515 cands.push((
10516 near_bits + drl_bits_for(stack, 1, idx),
10517 info_of(InterMode::NearMv, e.mv, idx as u8),
10518 ));
10519 }
10520 }
10521 // `LAST`'s own `NEWMV` vector, kept for the compound `NEW_NEARESTMV`
10522 // candidate below to pair with the second reference's NEAREST half.
10523 let mut last_new_mv: Option<(i32, i32)> = None;
10524 if leaf_new_mv() {
10525 let source_block = luma.source_block_rect(x, y, bw, bh);
10526 let (seeds, seed_n) = mv_seeds(stack);
10527 let found = motion::search(
10528 &reference.y,
10529 reference.width,
10530 luma.true_width,
10531 luma.true_height,
10532 &source_block,
10533 x,
10534 y,
10535 bw,
10536 bh,
10537 stack.pred_mv,
10538 &seeds[..seed_n],
10539 search.lambda,
10540 fctx,
10541 1,
10542 );
10543 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
10544 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
10545 last_new_mv = Some(mv);
10546 cands.push((
10547 symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits + mv_rate_surcharge(bits),
10548 info_of(InterMode::NewMv, mv, ref_mv_idx),
10549 ));
10550 }
10551 }
10552
10553 let mut best: Option<(f64, f64, InterInfo, Vec<Trial>)> = None;
10554 for (bits, info) in cands {
10555 let trials: Vec<Trial> = units
10556 .iter()
10557 .map(|&(plane, px, py, s, is_luma)| {
10558 let (samples, stride, w, h) = match plane {
10559 0 => (&reference.y, reference.width, luma.true_width, luma.true_height),
10560 1 => (
10561 &reference.u,
10562 reference.width / 2,
10563 chroma[0].true_width,
10564 chroma[0].true_height,
10565 ),
10566 _ => (
10567 &reference.v,
10568 reference.width / 2,
10569 chroma[1].true_width,
10570 chroma[1].true_height,
10571 ),
10572 };
10573 let prediction = predict_u8(samples, stride, w, h, (px, py), s, info.mv, is_luma, fctx);
10574 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
10575 // `skip` true: the trial is the prediction itself plus its SSE,
10576 // so no transform of any size is involved (the reason a 64x64
10577 // root can be coded at all before a forward TX_64X64 exists).
10578 target.code_from_prediction(
10579 px,
10580 py,
10581 s,
10582 &prediction,
10583 true,
10584 search.base_q_idx,
10585 search.deadzone,
10586 TxbSet::Luma32Inter,
10587 )
10588 })
10589 .collect();
10590 let cost =
10591 trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * (fixed + bits);
10592 if best.as_ref().is_none_or(|b| cost < b.0) {
10593 best = Some((cost, fixed + bits, info, trials));
10594 }
10595 }
10596
10597 // lane-b64b: the COMPOUND candidates at the 64 root, the same three a
10598 // superblock can form without a second motion search ([`b64_compound`]),
10599 // priced through the same `symbol_bits` path -- `fixed` minus the single
10600 // reference's tree, plus the pair tree and the compound mode.
10601 for (ref1, g, cstack) in compound.iter().filter(|_| b64_compound()) {
10602 let (ref1, g) = (*ref1, *g);
10603 // The whole `comp_mode` + reference-pair tree at the writer's own
10604 // contexts, for THIS pair (lane-ctx).
10605 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
10606 let mode_ctx =
10607 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
10608 let mode_bits_of =
10609 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
10610 let compound_info = |mode: InterMode, mvs: ((i32, i32), (i32, i32))| InterInfo {
10611 ref1: Some(ref1),
10612 mv1: mvs.1,
10613 ref_frame: crate::mvstack::LAST_FRAME,
10614 mode,
10615 mv: mvs.0,
10616 ref_mv_idx: 0,
10617 };
10618 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
10619 (
10620 cstack.nearest_mv,
10621 mode_bits_of(0),
10622 compound_info(InterMode::NearestNearestMv, cstack.nearest_mv),
10623 ),
10624 (
10625 ((0, 0), (0, 0)),
10626 mode_bits_of(6),
10627 compound_info(InterMode::GlobalGlobalMv, ((0, 0), (0, 0))),
10628 ),
10629 ];
10630 // `NEW_NEARESTMV`: the NEW half is `LAST`'s vector from the search
10631 // above, its residual priced against compound stack entry 0 -- what
10632 // `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
10633 let cbase = cstack
10634 .entries
10635 .first()
10636 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
10637 if let Some(new_mv) = last_new_mv
10638 && let Some(b0) = mv_residual_bits(new_mv, cbase.0)
10639 {
10640 let mvs = (new_mv, cstack.nearest_mv.1);
10641 ccands.push((
10642 mvs,
10643 mode_bits_of(3) + b0,
10644 compound_info(InterMode::NewNearestMv, mvs),
10645 ));
10646 }
10647 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
10648 ccands.dedup_by_key(|c| c.0);
10649 for (mvs, bits, info) in ccands {
10650 let trials: Vec<Trial> = units
10651 .iter()
10652 .map(|&(plane, px, py, s, is_luma)| {
10653 let (r0, r1) = match plane {
10654 0 => (
10655 (reference.y.as_slice(), reference.width, luma.true_width, luma.true_height),
10656 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
10657 ),
10658 1 => (
10659 (
10660 reference.u.as_slice(),
10661 reference.width / 2,
10662 chroma[0].true_width,
10663 chroma[0].true_height,
10664 ),
10665 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
10666 ),
10667 _ => (
10668 (
10669 reference.v.as_slice(),
10670 reference.width / 2,
10671 chroma[1].true_width,
10672 chroma[1].true_height,
10673 ),
10674 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
10675 ),
10676 };
10677 let prediction =
10678 predict_compound_u8(r0, r1, (px, py), s, mvs, is_luma, fctx);
10679 let target: &Plane = if plane == 0 { luma } else { &chroma[plane - 1] };
10680 target.code_from_prediction(
10681 px,
10682 py,
10683 s,
10684 &prediction,
10685 true,
10686 search.base_q_idx,
10687 search.deadzone,
10688 TxbSet::Luma32Inter,
10689 )
10690 })
10691 .collect();
10692 let syntax = fixed - ref_bits + bits;
10693 let cost = trials.iter().map(|t| t.sse).sum::<f64>() + search.lambda * syntax;
10694 if best.as_ref().is_none_or(|b| cost < b.0) {
10695 best = Some((cost, syntax, info, trials));
10696 }
10697 }
10698 }
10699
10700 let (skip_cost, syntax, info, skip_trials) = best?;
10701
10702 // The winner's prediction coded with a REAL residual (lane-tx64): one
10703 // TX_64X64 luma transform -- `TxbSet::Luma64`, whose coded quarter is the
10704 // 32x32 corner `code_from_prediction` hands back -- and one TX_32X32 per
10705 // chroma plane, since a 64x64 root's chroma block IS 32x32. Only the mv
10706 // the skip arm already chose is re-coded: the prediction with the lowest
10707 // SSE is also the cheapest residual to code, and a second 64x64 motion
10708 // search per superblock is the wall this root was taken to SAVE.
10709 //
10710 // Priced against the skip arm through the same `symbol_bits` path, so the
10711 // two numbers are comparable: `fixed` charged `skip` coded 1, and this
10712 // arm charges 0 instead and adds its three planes' coefficient bits.
10713 let mut chosen = (skip_cost, true, skip_trials);
10714 // Set when [`commit_inter_luma`] already wrote the residual arm's luma
10715 // into the plane, so the tail below does not commit over its units.
10716 let mut luma_committed = false;
10717 // The residual arm's luma levels and the `txfm_split` depth the writer
10718 // codes: depth 0 is the TX_64X64 corner in 32x32 coordinates, depth 1 is
10719 // four TX_32X32 units in 64x64 ones.
10720 let mut luma_levels: Option<(Vec<i32>, u8, Vec<TxType>)> = None;
10721 if residual {
10722 let sets = [TxbSet::Luma64, TxbSet::Chroma32, TxbSet::Chroma32];
10723 // Square by construction (the `debug_assert` above), so `units` is
10724 // one entry per plane and `chosen.2[plane]` is that plane's trial.
10725 let residual_trials = [0usize, 1, 2].map(|plane| {
10726 let (target, px, py, s) = if plane == 0 {
10727 (&*luma, x, y, bw)
10728 } else {
10729 (&chroma[plane - 1], x / 2, y / 2, bw / 2)
10730 };
10731 target.code_from_prediction(
10732 px,
10733 py,
10734 s,
10735 &chosen.2[plane].reconstruction,
10736 false,
10737 search.base_q_idx,
10738 search.deadzone,
10739 sets[plane],
10740 )
10741 });
10742 let unskip = skip_bits_at(stack, false) - skip_bits_at(stack, true);
10743 let coeff_bits: f64 = residual_trials.iter().map(|t| t.bits).sum();
10744 // lane-b64b: the root's own var-tx decision -- one TX_64X64 or the
10745 // four TX_32X32 units of `txfm_split = 1`, taken by the same
10746 // `commit_inter_luma` every other inter block's is (it commits the
10747 // winner and hands back the cost it took off the flat arm).
10748 let (levels, depth, gain, tx_types) = if b64_var_tx() {
10749 let second = info.ref1.and_then(|r1| {
10750 compound.iter().find(|(r, _, _)| *r == r1).map(|&(_, g, _)| {
10751 (
10752 info.mv1,
10753 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
10754 )
10755 })
10756 });
10757 luma_committed = true;
10758 commit_inter_luma(
10759 luma,
10760 (x, y),
10761 bw,
10762 info.mv,
10763 (&reference.y, reference.width, luma.true_width, luma.true_height),
10764 search,
10765 &residual_trials[0],
10766 false,
10767 second,
10768 fctx,
10769 )
10770 } else {
10771 (residual_trials[0].levels.clone(), 0, 0.0, Vec::new())
10772 };
10773 let cost = residual_trials.iter().map(|t| t.sse).sum::<f64>()
10774 + search.lambda * (syntax + unskip + coeff_bits)
10775 + gain;
10776 if cost < skip_cost {
10777 B64_RESIDUAL_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10778 if depth == 1 {
10779 B64_VAR_TX_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
10780 }
10781 luma_levels = Some((levels, depth, tx_types));
10782 chosen = (cost, false, residual_trials.to_vec());
10783 }
10784 }
10785
10786 let (cost, skip, trials) = chosen;
10787 // `commit_inter_luma` already wrote the residual arm's luma (its four
10788 // split units are not one 64-sided trial); a skip winner overwrites it.
10789 for (&(plane, px, py, s, _), trial) in units.iter().zip(&trials) {
10790 match plane {
10791 0 if skip || !luma_committed => luma.commit(px, py, s, trial),
10792 0 => {}
10793 _ => chroma[plane - 1].commit(px, py, s, trial),
10794 }
10795 }
10796 Some((
10797 cost,
10798 BlockCoeffs {
10799 skip,
10800 inter: Some(info),
10801 // The chroma grids are whole TX_32X32; the luma one is the
10802 // 64-point transform's coded 32x32 corner at depth 0 and the
10803 // whole 64-sided block at depth 1 (lane-b64b).
10804 tx_depth: luma_levels.as_ref().map_or(0, |(_, d, _)| *d),
10805 luma_tx_types: match (skip, &luma_levels) {
10806 (false, Some((_, _, types))) => types.clone(),
10807 _ => Vec::new(),
10808 },
10809 luma: match (skip, &luma_levels) {
10810 (true, _) => Vec::new(),
10811 (false, Some((levels, 1, _))) => coeffs(levels, SUPERBLOCK),
10812 (false, Some((levels, _, _))) => coeffs(levels, BLOCK),
10813 (false, None) => coeffs(&trials[0].levels, BLOCK),
10814 },
10815 u: if skip { Vec::new() } else { coeffs(&trials[1].levels, bw / 2) },
10816 v: if skip { Vec::new() } else { coeffs(&trials[2].levels, bw / 2) },
10817 ..BlockCoeffs::default()
10818 },
10819 ))
10820}
10821
10822fn search_inter_block(
10823 luma: &mut Plane,
10824 chroma: &mut [Plane; 2],
10825 (x, y): (usize, usize),
10826 search: &Search,
10827 mode_bits: &[f64; 13],
10828 reference: &Picture,
10829 stack: &MvStack,
10830 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
10831 // for the whole GOP, with the stack this block derives against it. Only
10832 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
10833 // second motion search would double the wall of the stage that already
10834 // owns most of it.
10835 extra: &[(i8, &Picture, &MvStack)],
10836 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
10837 // the caller off the same MI grid the tile writer will (empty unless the
10838 // frame carries `reference_select`).
10839 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
10840 // lane-av1obmc: the mi grid this search's neighbours were published into
10841 // (`record_mi`) and this block's own place in it -- what the OBMC
10842 // candidate's eligibility walk and neighbour plan read, the same state
10843 // the tile writer will read when it codes the `motion_mode` symbol.
10844 grid: &MiGrid,
10845 (mi_row, mi_col): (usize, usize),
10846 (mi_rows, mi_cols): (usize, usize),
10847 fctx: &crate::decode::FrameCtx,
10848) -> (BlockCoeffs, f64) {
10849 // `luma_set` is the INTRA candidates' table; the two inter candidates
10850 // below price their coefficients through `TxbSet::Luma32Inter`, which is
10851 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
10852 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
10853 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
10854 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
10855
10856 // skip / intra_inter symbol costs at a fixed context -- see this
10857 // function's doc comment.
10858 let skip_bits = |skip: bool| skip_bits_at(stack, skip);
10859 let intra_inter_bits = |inter: bool| intra_inter_bits_at(stack, inter);
10860
10861 struct Candidate {
10862 cost: f64,
10863 luma: Trial,
10864 u: Trial,
10865 v: Trial,
10866 mode: u8,
10867 skip: bool,
10868 inter: Option<InterInfo>,
10869 /// The mode/mv syntax this candidate pays for, apart from its
10870 /// residual -- what the OBMC candidate below has to re-pay when it
10871 /// re-prices the winner's prediction.
10872 mode_bits: f64,
10873 }
10874 let mut best: Option<Candidate> = None;
10875 let mut consider = |candidate: Candidate| {
10876 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
10877 best = Some(candidate);
10878 }
10879 };
10880
10881 // The chroma trial an intra candidate prices does not depend on `mode`
10882 // at all -- both planes always code `DC_PRED` here (a coding choice this
10883 // search inherited, not this loop's to second-guess) at the same `reach:
10884 // Reach::none()` -- so it is the same call with the same inputs on every
10885 // one of the thirteen iterations below; run it once and reuse the result
10886 // rather than repeat an already-priced transform/quantize/entropy call
10887 // twelve times for nothing (bit-identical: the value each iteration
10888 // reads back is exactly what it used to recompute).
10889 let u_trial = chroma[0].trial(
10890 At {
10891 x: x / 2,
10892 y: y / 2,
10893 side: BLOCK / 2,
10894 reach: Reach::none(),
10895 set: chroma_set,
10896 },
10897 DC_PRED,
10898 0,
10899 search.base_q_idx,
10900 search.deadzone, fctx,
10901 );
10902 let v_trial = chroma[1].trial(
10903 At {
10904 x: x / 2,
10905 y: y / 2,
10906 side: BLOCK / 2,
10907 reach: Reach::none(),
10908 set: chroma_set,
10909 },
10910 DC_PRED,
10911 0,
10912 search.base_q_idx,
10913 search.deadzone, fctx,
10914 );
10915
10916 let intra_modes: Vec<u8> = match search.top_k {
10917 Some(k) if k < search.modes.len() => {
10918 let scored = luma.intra_scores(
10919 At {
10920 x,
10921 y,
10922 side: BLOCK,
10923 reach,
10924 set: luma_set,
10925 },
10926 search.modes,
10927 mode_bits,
10928 search.lambda, fctx,
10929 );
10930 prune_by_sad(search.modes, scored, k)
10931 }
10932 _ => search.modes.to_vec(),
10933 };
10934 census_add(5, 1);
10935 census_add(6, intra_modes.len());
10936 for &mode in &intra_modes {
10937 let luma_trial = luma.trial(
10938 At {
10939 x,
10940 y,
10941 side: BLOCK,
10942 reach,
10943 set: luma_set,
10944 },
10945 mode,
10946 0,
10947 search.base_q_idx,
10948 search.deadzone, fctx,
10949 );
10950 let u = u_trial.clone();
10951 let v = v_trial.clone();
10952 let cost = luma_trial.sse
10953 + u.sse
10954 + v.sse
10955 + search.lambda
10956 * (luma_trial.bits
10957 + u.bits
10958 + v.bits
10959 + mode_bits[usize::from(mode)]
10960 + skip_bits(false)
10961 + intra_inter_bits(false));
10962 consider(Candidate {
10963 cost,
10964 luma: luma_trial,
10965 u,
10966 v,
10967 mode,
10968 skip: false,
10969 inter: None,
10970 mode_bits: mode_bits[usize::from(mode)],
10971 });
10972 }
10973
10974 // The reference frame buffer a spec decoder holds is exactly the true
10975 // (unpadded) coded extent -- a superblock whose partition stops early at
10976 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
10977 // beyond it, so those samples are never part of the decoded picture.
10978 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
10979 // reference sample position clamp), not to this crate's own
10980 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
10981 // here would let a fractional-pel read past the true edge pick up this
10982 // encoder's own uncoded padding instead of the true edge's replicated
10983 // value a decoder computes.
10984 let ref_luma = (
10985 &reference.y,
10986 reference.width,
10987 luma.true_width,
10988 luma.true_height,
10989 );
10990 let ref_u = (
10991 &reference.u,
10992 reference.width / 2,
10993 chroma[0].true_width,
10994 chroma[0].true_height,
10995 );
10996 let ref_v = (
10997 &reference.v,
10998 reference.width / 2,
10999 chroma[1].true_width,
11000 chroma[1].true_height,
11001 );
11002 // Every single-reference mode the writer can code (spec 5.11.24's symbol
11003 // chain, mirrored by `tile::write_inter_mode`), priced with the static
11004 // CDFs at this block's own stack contexts. A candidate is a motion
11005 // vector plus the cheapest syntax that reaches it, so two modes landing
11006 // on the same vector share one set of trials: the added modes cost
11007 // mode-bit arithmetic, not another motion compensation.
11008 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
11009 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
11010 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
11011 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
11012 // the loop cannot reach is never offered below -- every candidate's
11013 // index is one this same loop walks to.
11014 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
11015 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME, stack);
11016 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
11017 (
11018 stack.nearest_mv,
11019 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
11020 InterInfo {
11021 ref1: None,
11022 mv1: (0, 0),
11023 ref_frame: crate::mvstack::LAST_FRAME,
11024 mode: InterMode::NearestMv,
11025 mv: stack.nearest_mv,
11026 ref_mv_idx: 0,
11027 },
11028 ),
11029 // GLOBALMV is the identity model's zero vector -- this encoder writes
11030 // no `gm_params` -- and the cheapest syntax of the four on the static
11031 // content where that vector is also the right one.
11032 (
11033 (0, 0),
11034 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
11035 InterInfo {
11036 ref1: None,
11037 mv1: (0, 0),
11038 ref_frame: crate::mvstack::LAST_FRAME,
11039 mode: InterMode::GlobalMv,
11040 mv: (0, 0),
11041 ref_mv_idx: 0,
11042 },
11043 ),
11044 ];
11045 let near_bits =
11046 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
11047 for idx in 1..=2usize {
11048 if let Some(e) = stack.entries.get(idx) {
11049 cands.push((
11050 e.mv,
11051 near_bits + drl_bits(1, idx),
11052 InterInfo {
11053 ref1: None,
11054 mv1: (0, 0),
11055 ref_frame: crate::mvstack::LAST_FRAME,
11056 mode: InterMode::NearMv,
11057 mv: e.mv,
11058 ref_mv_idx: idx as u8,
11059 },
11060 ));
11061 }
11062 }
11063
11064 let source_block = luma.source_block(x, y, BLOCK);
11065 let (seeds, seed_n) = mv_seeds(stack);
11066 #[cfg(test)]
11067 let t = stage_start();
11068 let found = motion::search(
11069 ref_luma.0,
11070 ref_luma.1,
11071 ref_luma.2,
11072 ref_luma.3,
11073 &source_block,
11074 x,
11075 y,
11076 BLOCK,
11077 BLOCK,
11078 stack.pred_mv,
11079 &seeds[..seed_n],
11080 search.lambda, fctx,
11081 1,
11082 );
11083 #[cfg(test)]
11084 stage_since(0, t);
11085 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
11086 // lane-newmv: this block's own `NEWMV` vector and what its mv syntax
11087 // costs, for the census below (`None` when the writer cannot name it).
11088 let mut newmv_syntax: Option<((i32, i32), f64)> = None;
11089 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
11090 // the same vector costs a different residual from each: take the index
11091 // whose residual plus DRL bits is cheapest, not entry 0 by default.
11092 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
11093 newmv_syntax = Some((mv, bits));
11094 cands.push((
11095 mv,
11096 last_ref_bits
11097 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
11098 + bits
11099 + mv_rate_surcharge(bits),
11100 InterInfo {
11101 ref1: None,
11102 mv1: (0, 0),
11103 ref_frame: crate::mvstack::LAST_FRAME,
11104 mode: InterMode::NewMv,
11105 mv,
11106 ref_mv_idx,
11107 },
11108 ));
11109 }
11110
11111 // Each extra reference's own `NEWMV` vector, for the compound
11112 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
11113 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
11114 for &(ref_frame, g, gstack) in extra {
11115 let g_ref_bits = single_ref_bits(ref_frame, gstack);
11116 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
11117 cands.push((
11118 gstack.nearest_mv,
11119 g_ref_bits
11120 + g_not_new
11121 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
11122 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
11123 InterInfo {
11124 ref1: None,
11125 mv1: (0, 0),
11126 ref_frame,
11127 mode: InterMode::NearestMv,
11128 mv: gstack.nearest_mv,
11129 ref_mv_idx: 0,
11130 },
11131 ));
11132 cands.push((
11133 (0, 0),
11134 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
11135 InterInfo {
11136 ref1: None,
11137 mv1: (0, 0),
11138 ref_frame,
11139 mode: InterMode::GlobalMv,
11140 mv: (0, 0),
11141 ref_mv_idx: 0,
11142 },
11143 ));
11144 // A motion search of this reference's own: without it, GOLDEN/ALTREF
11145 // can only be coded at a vector some neighbour already found, which
11146 // is why they carried a third of the inter blocks at their two
11147 // search-free modes alone.
11148 // The search is skipped when this reference's own NEARESTMV already
11149 // prices out `margin` times better than LAST's best vector does --
11150 // one candidate evaluation (`motion::cost_at`) standing in for a
11151 // whole search of ~50.
11152 // lane-last2: the SEARCH-FREE arm for the second past leaf picture
11153 // (`EC_AV1_LAST2_NEW=0`) -- LAST2 is then coded only at a vector some
11154 // neighbour already found, which is how GOLDEN/ALTREF were offered
11155 // before `EXTRA_REF_NEW_MV`, and it is what separates the reference's
11156 // own value from the second motion search's wall.
11157 let searched = extra_ref_new_mv()
11158 && (ref_frame != crate::mvstack::LAST2_FRAME || last2_new_mv());
11159 let margin = extra_new_skip_margin();
11160 if searched {
11161 newmv_census_global(0);
11162 }
11163 let skip_search = searched
11164 && margin > 0.0
11165 && motion::cost_at(
11166 &g.y,
11167 g.width,
11168 luma.true_width,
11169 luma.true_height,
11170 &source_block,
11171 x,
11172 y,
11173 BLOCK,
11174 BLOCK,
11175 gstack.nearest_mv,
11176 gstack.pred_mv,
11177 search.lambda,
11178 fctx,
11179 ) * margin
11180 <= found.cost;
11181 if skip_search {
11182 newmv_census_global(1);
11183 }
11184 if searched && !skip_search {
11185 let (gseeds, gn) = mv_seeds(gstack);
11186 #[cfg(test)]
11187 let t = stage_start();
11188 let gfound = motion::search(
11189 &g.y,
11190 g.width,
11191 luma.true_width,
11192 luma.true_height,
11193 &source_block,
11194 x,
11195 y,
11196 BLOCK,
11197 BLOCK,
11198 gstack.pred_mv,
11199 &gseeds[..gn],
11200 search.lambda, fctx,
11201 ref_distance(ref_frame),
11202 );
11203 #[cfg(test)]
11204 stage_since(0, t);
11205 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
11206 extra_new_mvs.push((ref_frame, gmv));
11207 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
11208 cands.push((
11209 gmv,
11210 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
11211 InterInfo {
11212 ref1: None,
11213 mv1: (0, 0),
11214 ref_frame,
11215 mode: InterMode::NewMv,
11216 mv: gmv,
11217 ref_mv_idx,
11218 },
11219 ));
11220 }
11221 }
11222 }
11223
11224 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
11225 // trial set each: both references predict the block and the two
11226 // predictions are averaged, which is what pays on content where neither
11227 // reference alone is right. Priced with the same static-CDF approximation
11228 // the single-reference candidates use, plus the compound-only symbols
11229 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
11230 // The two compound-mode arms, each measured alone on the BD gate before
11231 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
11232 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
11233 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
11234 // RE-MEASURED on lane-av1rejudge at LAMBDA_SCALE 0.05 with warp on:
11235 // +16.6/-0.7, +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5,
11236 // +47.0/+19.1, +51.3/-14.3 -- one row 0.1/0.2 down, two flat, short of
11237 // the keep rule. Still behind the knob.
11238 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
11239 let half_new = true;
11240 for (ref1, g, cstack) in compound {
11241 let (ref1, g) = (*ref1, *g);
11242 // The whole `comp_mode` + reference-pair tree at the writer's own
11243 // contexts, for THIS pair (lane-ctx).
11244 let pair_bits = compound_ref_bits((crate::mvstack::LAST_FRAME, ref1), stack);
11245 let mode_ctx =
11246 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
11247 let mode_bits_of =
11248 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
11249 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
11250 (
11251 cstack.nearest_mv,
11252 mode_bits_of(0),
11253 InterInfo {
11254 ref_frame: crate::mvstack::LAST_FRAME,
11255 mode: InterMode::NearestNearestMv,
11256 mv: cstack.nearest_mv.0,
11257 mv1: cstack.nearest_mv.1,
11258 ref1: Some(ref1),
11259 ref_mv_idx: 0,
11260 },
11261 ),
11262 (
11263 ((0, 0), (0, 0)),
11264 mode_bits_of(6),
11265 InterInfo {
11266 ref_frame: crate::mvstack::LAST_FRAME,
11267 mode: InterMode::GlobalGlobalMv,
11268 mv: (0, 0),
11269 mv1: (0, 0),
11270 ref1: Some(ref1),
11271 ref_mv_idx: 0,
11272 },
11273 ),
11274 ];
11275 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
11276 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
11277 // the stack is deep enough for that walk to read one.
11278 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
11279 let drl = if cstack.entries.len() > 2 {
11280 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
11281 } else {
11282 0.0
11283 };
11284 ccands.push((
11285 (e.mv0, e.mv1),
11286 mode_bits_of(1) + drl,
11287 InterInfo {
11288 ref_frame: crate::mvstack::LAST_FRAME,
11289 mode: InterMode::NearNearMv,
11290 mv: e.mv0,
11291 mv1: e.mv1,
11292 ref1: Some(ref1),
11293 ref_mv_idx: 0,
11294 },
11295 ));
11296 }
11297 // The half-new modes and `NEW_NEWMV`, all seeded from the two
11298 // single-reference searches this block already ran -- no joint search
11299 // of its own. Every residual is priced against stack entry 0, which
11300 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
11301 let cbase = cstack
11302 .entries
11303 .first()
11304 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
11305 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
11306 ccands.push((
11307 (mv, cstack.nearest_mv.1),
11308 mode_bits_of(3) + b0,
11309 InterInfo {
11310 ref_frame: crate::mvstack::LAST_FRAME,
11311 mode: InterMode::NewNearestMv,
11312 mv,
11313 mv1: cstack.nearest_mv.1,
11314 ref1: Some(ref1),
11315 ref_mv_idx: 0,
11316 },
11317 ));
11318 }
11319 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
11320 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
11321 ccands.push((
11322 (cstack.nearest_mv.0, mv1),
11323 mode_bits_of(2) + b1,
11324 InterInfo {
11325 ref_frame: crate::mvstack::LAST_FRAME,
11326 mode: InterMode::NearestNewMv,
11327 mv: cstack.nearest_mv.0,
11328 mv1,
11329 ref1: Some(ref1),
11330 ref_mv_idx: 0,
11331 },
11332 ));
11333 }
11334 let base = cbase;
11335 if let (Some(b0), Some(b1)) = (
11336 mv_residual_bits(mv, base.0),
11337 mv_residual_bits(mv1, base.1),
11338 ) {
11339 ccands.push((
11340 (mv, mv1),
11341 mode_bits_of(7) + b0 + b1,
11342 InterInfo {
11343 ref_frame: crate::mvstack::LAST_FRAME,
11344 mode: InterMode::NewNewMv,
11345 mv,
11346 mv1,
11347 ref1: Some(ref1),
11348 ref_mv_idx: 0,
11349 },
11350 ));
11351 }
11352 }
11353 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
11354 ccands.dedup_by_key(|c| c.0);
11355 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
11356 let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height);
11357 let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height);
11358 for (mvs, bits, info) in ccands {
11359 let luma_trial = mc_trial_compound(
11360 luma, x, y, BLOCK, mvs, true,
11361 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
11362 search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx,
11363 );
11364 let u = mc_trial_compound(
11365 &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false,
11366 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
11367 search.base_q_idx, search.deadzone, chroma_set, fctx,
11368 );
11369 let v = mc_trial_compound(
11370 &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false,
11371 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
11372 search.base_q_idx, search.deadzone, chroma_set, fctx,
11373 );
11374 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11375 && u.levels.iter().all(|&l| l == 0)
11376 && v.levels.iter().all(|&l| l == 0);
11377 let cost = luma_trial.sse
11378 + u.sse
11379 + v.sse
11380 + search.lambda
11381 * (skip_bits(skip)
11382 + intra_inter_bits(true)
11383 + bits
11384 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
11385 consider(Candidate {
11386 cost,
11387 luma: luma_trial,
11388 u,
11389 v,
11390 mode: DC_PRED,
11391 skip,
11392 mode_bits: bits,
11393 inter: Some(info),
11394 });
11395 }
11396 }
11397
11398 // One trial set per distinct (reference, vector) pair: sort, cheapest
11399 // syntax first, and drop the rest of each pair's run.
11400 cands.sort_by(|a, b| {
11401 (a.2.ref_frame, a.0)
11402 .cmp(&(b.2.ref_frame, b.0))
11403 .then(a.1.total_cmp(&b.1))
11404 });
11405 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
11406 census_add(7, cands.len());
11407 // lane-newmv: the NEWMV candidate's own RD cost against the best cost
11408 // this block reaches WITHOUT it, taken inside the one loop that prices
11409 // them all (a second pricing pass would be a second oracle).
11410 let (mut new_cost, mut other_cost) = (f64::INFINITY, f64::INFINITY);
11411 {
11412 for (mv, mode_bits_inter, info) in cands {
11413 let (ref_luma, ref_u, ref_v) = match extra
11414 .iter()
11415 .find(|(r, _, _)| *r == info.ref_frame)
11416 {
11417 Some(&(_, g, _)) => (
11418 (&g.y, g.width, luma.true_width, luma.true_height),
11419 (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
11420 (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
11421 ),
11422 None => (ref_luma, ref_u, ref_v),
11423 };
11424 let luma_trial = mc_trial(
11425 luma,
11426 x,
11427 y,
11428 BLOCK,
11429 mv,
11430 true,
11431 ref_luma.0,
11432 ref_luma.1,
11433 ref_luma.2,
11434 ref_luma.3,
11435 false,
11436 search.base_q_idx,
11437 search.deadzone,
11438 TxbSet::Luma32Inter, fctx,
11439 );
11440 let u = mc_trial(
11441 &chroma[0],
11442 x / 2,
11443 y / 2,
11444 BLOCK / 2,
11445 mv,
11446 false,
11447 ref_u.0,
11448 ref_u.1,
11449 ref_u.2,
11450 ref_u.3,
11451 false,
11452 search.base_q_idx,
11453 search.deadzone,
11454 chroma_set, fctx,
11455 );
11456 let v = mc_trial(
11457 &chroma[1],
11458 x / 2,
11459 y / 2,
11460 BLOCK / 2,
11461 mv,
11462 false,
11463 ref_v.0,
11464 ref_v.1,
11465 ref_v.2,
11466 ref_v.3,
11467 false,
11468 search.base_q_idx,
11469 search.deadzone,
11470 chroma_set, fctx,
11471 );
11472 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11473 && u.levels.iter().all(|&l| l == 0)
11474 && v.levels.iter().all(|&l| l == 0);
11475 let cost = luma_trial.sse
11476 + u.sse
11477 + v.sse
11478 + search.lambda
11479 * (skip_bits(skip)
11480 + intra_inter_bits(true)
11481 + mode_bits_inter
11482 + if skip {
11483 0.0
11484 } else {
11485 luma_trial.bits + u.bits + v.bits
11486 });
11487 consider(Candidate {
11488 cost,
11489 luma: luma_trial,
11490 u,
11491 v,
11492 mode: DC_PRED,
11493 skip,
11494 mode_bits: mode_bits_inter,
11495 inter: Some(info),
11496 });
11497 if newmv_census_on() {
11498 if info.mode == InterMode::NewMv
11499 && info.ref1.is_none()
11500 && info.ref_frame == crate::mvstack::LAST_FRAME
11501 {
11502 new_cost = cost;
11503 } else {
11504 other_cost = other_cost.min(cost);
11505 }
11506 }
11507 }
11508 }
11509 if let Some((new_mv, bits)) = newmv_syntax {
11510 newmv_census_block(BLOCK, true, new_cost, other_cost, new_mv, stack.nearest_mv, bits);
11511 } else {
11512 newmv_census_block(BLOCK, false, f64::INFINITY, other_cost, mv, stack.nearest_mv, 0.0);
11513 }
11514
11515 let best = best.expect("the search offers at least the intra modes");
11516 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
11517 // offered to the SINGLE-REFERENCE winner only -- libaom's
11518 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
11519 // compound block, so the writer codes no symbol for one. The prediction
11520 // is built by the DECODER's own plan and blend
11521 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
11522 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
11523 // this search's `grid` already carries, so what is priced here is what a
11524 // decoder reconstructs -- never a second implementation of the blend.
11525 //
11526 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
11527 // on). Native crop BD, the standing recipe, with it on against the same
11528 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
11529 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
11530 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
11531 // one UP -- the keep rule wants two down and one flat, so it stays off.
11532 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
11533 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
11534 // things bound it and are the upgrade path: only the 32x32 winner is
11535 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
11536 // that is where libaom cashes most of its OBMC gain), and the symbol/
11537 // residual price here is the static-CDF estimate.
11538 let mut best = best;
11539 let mut motion_won = 0u8;
11540 if let Some(info) = best.inter.filter(|i| {
11541 i.ref1.is_none()
11542 && (crate::envflags::env_flag!("EC_AV1_OBMC")
11543 || warp_on())
11544 }) {
11545 let mut refs: [Option<&Picture>; 8] = [None; 8];
11546 refs[LAST_FRAME as usize] = Some(reference);
11547 for &(r, p, _) in extra {
11548 refs[r as usize] = Some(p);
11549 }
11550 // This block's OWN reference planes: the single-reference winner may
11551 // be one of the extra references, not LAST.
11552 let planes: [(&[u16], usize, usize, usize); 3] =
11553 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11554 Some(&(_, g, _)) => [
11555 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11556 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11557 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11558 ],
11559 None => [
11560 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
11561 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
11562 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
11563 ],
11564 };
11565 // The alphabet `tile::write_motion_mode` will code this block's
11566 // symbol against, mirrored term for term (libaom
11567 // `motion_mode_allowed`).
11568 let warp_alphabet = warp_on()
11569 && crate::decode::num_proj_ref(
11570 grid,
11571 mi_row,
11572 mi_col,
11573 8,
11574 8,
11575 mi_cols,
11576 mi_rows,
11577 info.ref_frame,
11578 fctx,
11579 ) >= 1;
11580 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
11581 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
11582 if crate::envflags::env_flag!("EC_AV1_OBMC") {
11583 if let Some(pred) = obmc_prediction(
11584 grid,
11585 (mi_row, mi_col),
11586 (mi_rows, mi_cols),
11587 (x, y),
11588 BLOCK,
11589 info.mv,
11590 &refs,
11591 planes,
11592 reference.width,
11593 fctx,
11594 ) {
11595 candidates.push((1, pred));
11596 }
11597 }
11598 if warp_alphabet {
11599 if let Some(pred) = warp_prediction(
11600 grid,
11601 (mi_row, mi_col),
11602 (mi_rows, mi_cols),
11603 (x, y),
11604 BLOCK,
11605 info.mv,
11606 info.ref_frame,
11607 planes,
11608 fctx,
11609 ) {
11610 candidates.push((2, pred));
11611 }
11612 }
11613 for (motion, pred) in candidates {
11614 let luma_trial = luma.code_from_prediction(
11615 x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone,
11616 TxbSet::Luma32Inter,
11617 );
11618 let u = chroma[0].code_from_prediction(
11619 x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone,
11620 chroma_set,
11621 );
11622 let v = chroma[1].code_from_prediction(
11623 x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone,
11624 chroma_set,
11625 );
11626 let skip = luma_trial.levels.iter().all(|&l| l == 0)
11627 && u.levels.iter().all(|&l| l == 0)
11628 && v.levels.iter().all(|&l| l == 0);
11629 let cost = luma_trial.sse
11630 + u.sse
11631 + v.sse
11632 + search.lambda
11633 * (skip_bits(skip)
11634 + intra_inter_bits(true)
11635 + best.mode_bits
11636 + mm(motion)
11637 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
11638 if cost < best.cost + search.lambda * mm(motion_won) {
11639 motion_won = motion;
11640 best = Candidate {
11641 cost,
11642 luma: luma_trial,
11643 u,
11644 v,
11645 mode: DC_PRED,
11646 skip,
11647 mode_bits: best.mode_bits,
11648 inter: best.inter,
11649 };
11650 }
11651 }
11652 }
11653 // The transform-depth search of a 32x32 winner (`EC_AV1_TX32_DEPTH`,
11654 // default OFF): the four 16x16 units of `commit_inter_luma` against the
11655 // flat trial, exactly as a 16x16 leaf is offered. lane-av1txbits measured
11656 // it flat-to-worse at LAMBDA_SCALE 0.1; lane-av1txdepth REBUILT it and
11657 // RE-MEASURED it at 0.05, where the rate weight is half of what rejected
11658 // it, and it is worse again on the deciding native table: film 1080p
11659 // +16.6/-0.5, film 2160p +46.6/+18.8, screen +50.9/-14.3 against the
11660 // +16.2/-1.1, +46.6/+18.8, +51.3/-14.4 of the same build with it off --
11661 // 1080p up 0.4/0.6, one row flat, screen 0.4 down against libaom and 0.1
11662 // up against rav1e. (640x384 reads it slightly the other way, +70.0/
11663 // +85.0/+48.4 and +28.3/+47.2/-3.6 against +70.4/+85.3/+48.5 and
11664 // +28.4/+47.4/-4.0 -- the native table decides.)
11665 //
11666 // NOT blindness: the split wins 62.3% of the 1080p film's 32x32 blocks,
11667 // 70.9% of the 4K film's and 53.5% of the screen's. NOT mis-pricing
11668 // either, and the census names the row: the split units' own set
11669 // `Luma16Inter` is priced within 1.4% of what it is written at in every
11670 // bucket from two non-zeros up, and its ZERO bucket (335 units) is priced
11671 // +30.1% ABOVE the written bits -- an error that biases AGAINST splitting,
11672 // so a perfect pricer would split even more, and more splitting is what
11673 // measured worse. The four extra txb_skip/eob symbols simply cost more
11674 // ladder bytes than the local RD saves. The flat 32x32 transform stays.
11675 // lane-av1txdepth REBUILT that search at LAMBDA_SCALE 0.05 (the rejection
11676 // above was measured at 0.1), behind `EC_AV1_TX32_DEPTH`, and gave the
11677 // compound winner the same offer behind `EC_AV1_COMP_VARTX`. An OBMC/warp
11678 // winner still commits flat: `commit_inter_luma` re-predicts each unit by
11679 // plain translation, which is not the prediction it was priced from.
11680 let (levels, tx_depth, dcost, luma_tx_types) = match best.inter.filter(|_| motion_won == 0) {
11681 Some(info) => {
11682 let own = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11683 Some(&(_, g, _)) => (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11684 None => (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
11685 };
11686 let second = info.ref1.and_then(|r| {
11687 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
11688 (
11689 info.mv1,
11690 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
11691 )
11692 })
11693 });
11694 match info.ref1.is_some() && second.is_none() {
11695 true => {
11696 luma.commit(x, y, BLOCK, &best.luma);
11697 (best.luma.levels.clone(), 0, 0.0, Vec::new())
11698 }
11699 false => commit_inter_luma(
11700 luma, (x, y), BLOCK, info.mv, own, search, &best.luma, best.skip, second,
11701 fctx,
11702 ),
11703 }
11704 }
11705 None => {
11706 luma.commit(x, y, BLOCK, &best.luma);
11707 (best.luma.levels.clone(), 0, 0.0, Vec::new())
11708 }
11709 };
11710 // lane-txrd: chroma follows the luma type the var-tx/type search chose.
11711 let [bu, bv] = match (best.inter.filter(|_| motion_won == 0), luma_tx_types.first().copied()) {
11712 (Some(info), Some(t)) => {
11713 let (ou, ov) = match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
11714 Some(&(_, g, _)) => (
11715 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11716 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11717 ),
11718 None => (
11719 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
11720 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
11721 ),
11722 };
11723 let sec = info.ref1.and_then(|r| {
11724 compound.iter().find(|(c, _, _)| *c == r).map(|&(_, g, _)| {
11725 (
11726 info.mv1,
11727 [
11728 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
11729 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
11730 ],
11731 )
11732 })
11733 });
11734 recode_inter_chroma(
11735 chroma, (x, y), BLOCK, info.mv, [ou, ov], sec, search, chroma_set, t, fctx,
11736 )
11737 .unwrap_or([best.u, best.v])
11738 }
11739 _ => [best.u, best.v],
11740 };
11741 let best = Candidate { u: bu, v: bv, ..best };
11742 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
11743 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
11744 (
11745 BlockCoeffs {
11746 luma_tx_types,
11747 angle_delta_y: 0,
11748 cfl_alphas: None,
11749 filter_intra: None,
11750 luma: coeffs(&levels, BLOCK),
11751 u: coeffs(&best.u.levels, BLOCK / 2),
11752 v: coeffs(&best.v.levels, BLOCK / 2),
11753 mode: best.mode,
11754 uv_mode: DC_PRED,
11755 skip: best.skip,
11756 inter: best.inter,
11757 motion_mode: motion_won,
11758 eight: None,
11759 dv: None,
11760 palette: None,
11761 palette_uv: None,
11762 tx_depth,
11763 },
11764 best.cost + dcost,
11765 )
11766}
11767
11768/// lane-av1tpl: the strength `k` of the temporal lambda weighting
11769/// ([`tpl_lambda_factors`]). 0 keeps every block at the frame's own lambda, which
11770/// is what every measurement before this lane was taken on. Swept by
11771/// `EC_AV1_TPL=<k>`.
11772///
11773/// SWEPT on lane-av1tpl at the native gate (1920x1024, 12 frames, BD-rate vs
11774/// libaom `cpu-used 6` / rav1e `speed 6`); `k=0` reproduces the pre-lane
11775/// baseline exactly, which is the control the rest of the table is read
11776/// against:
11777///
11778/// | k | film 1080p | film 2160p | screen |
11779/// |---|---|---|---|
11780/// | 0 | +16.2/-1.1 | +46.6/+18.8 | +51.3/-14.4 |
11781/// | 0.25 | +16.4/-0.7 | +46.6/+18.8 | +51.2/-14.4 |
11782/// | **0.5** | **+15.9/-1.3** | **+46.5/+18.7** | **+51.2/-14.4** |
11783/// | 1 | +16.2/-0.9 | +46.6/+18.8 | +51.2/-14.4 |
11784/// | 2 | +16.5/-0.7 | +46.7/+19.0 | +51.1/-14.4 |
11785///
11786/// 0.5 is the only arm that is at least flat on every row and down on five of
11787/// the six columns, so it ships as the default. The lookahead pass that feeds
11788/// it costs 1.5 ms per 1920x1024 frame against a ~0.8 s encode (0.2%).
11789const TPL_STRENGTH: f64 = 0.5;
11790
11791/// lane-deltaq: the per-superblock quantizer, `delta_q_present` (spec
11792/// 5.9.17/5.11.10). `EC_AV1_DELTAQ=0` switches it off (the stream is then
11793/// byte-identical to the pre-lane one); anything else is the `delta_q_res`
11794/// LOG2, so `2` is a step of 4 and `3` a step of 8. `None` = off.
11795///
11796/// A frame with no tpl map (no lookahead picture, or `EC_AV1_TPL=0`) has
11797/// nothing to vary the quantizer BY and codes no delta syntax at all.
11798fn deltaq_res_log2() -> Option<u8> {
11799 match DELTAQ_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
11800 u8::MAX => {}
11801 4 => return None,
11802 r => return Some(r),
11803 }
11804 match crate::envflags::var("EC_AV1_DELTAQ").ok().as_deref().map(str::trim) {
11805 Some("0") => None,
11806 Some(v) => v.parse::<u8>().ok().filter(|r| *r <= 3),
11807 None => Some(crate::speed::at(&crate::speed::DELTAQ_RES)).filter(|r| *r < 4),
11808 }
11809}
11810
11811/// A PROCESS-GLOBAL [`deltaq_res_log2`] override that wins over both the
11812/// environment and the preset -- `u8::MAX` = unset, `4` = off. The gate that
11813/// sets it holds [`crate::speed::knob_write`], the same exclusive lock the
11814/// speed presets take, because the streams every other test pins move under
11815/// it (the shipped default is OFF, see [`crate::speed::DELTAQ_RES`]).
11816static DELTAQ_OVERRIDE: std::sync::atomic::AtomicU8 =
11817 std::sync::atomic::AtomicU8::new(u8::MAX);
11818
11819/// Sets [`DELTAQ_OVERRIDE`]; `None` clears it.
11820#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
11821pub(crate) fn set_deltaq_res(res_log2: Option<u8>) {
11822 DELTAQ_OVERRIDE.store(
11823 res_log2.unwrap_or(u8::MAX),
11824 std::sync::atomic::Ordering::Relaxed,
11825 );
11826}
11827
11828/// How much of the derived qindex step is actually taken
11829/// (`EC_AV1_DELTAQ_K`, default 1.0 = the full derivation).
11830fn deltaq_k() -> f64 {
11831 crate::envflags::var("EC_AV1_DELTAQ_K")
11832 .ok()
11833 .and_then(|v| v.trim().parse::<f64>().ok())
11834 .filter(|k| k.is_finite() && *k >= 0.0)
11835 .unwrap_or(1.0)
11836}
11837
11838/// The largest qindex the map may move a superblock by, either way
11839/// (`EC_AV1_DELTAQ_CLAMP`, default 16 -- libaom clamps its own objective
11840/// deltaq around a quarter of the base qindex).
11841fn deltaq_clamp() -> i32 {
11842 crate::envflags::var("EC_AV1_DELTAQ_CLAMP")
11843 .ok()
11844 .and_then(|v| v.trim().parse::<i32>().ok())
11845 .filter(|c| (0..=63).contains(c))
11846 .unwrap_or(16)
11847}
11848
11849/// The qindex a lambda factor `f` asks for, derived rather than fitted.
11850///
11851/// The tpl map hands out a factor on LAMBDA, and RD lambda goes as the
11852/// square of the quantizer step (`encode_inter_frame`'s own
11853/// `lambda = .. * step * step`), so the step this superblock wants is
11854/// `sqrt(f)` times the frame's. `ac_q` is not linear in the index, so the
11855/// step ratio is inverted through the table itself -- the index whose `ac_q`
11856/// is closest to `ac_q(base) * sqrt(f)` -- rather than through a fitted
11857/// constant. `k` scales the resulting step (1.0 takes all of it), `clamp`
11858/// bounds it, and the answer is snapped onto the `res` grid so that every
11859/// superblock's qindex is congruent to `base` and the coded delta is a whole
11860/// number of steps.
11861fn deltaq_for_factor(base: u8, f: f64, k: f64, clamp: i32, res: i32) -> u8 {
11862 let base_ac = f64::from(ac_q(8, i32::from(base)));
11863 let target = base_ac * f.max(1e-6).sqrt();
11864 let exact = (1..=255)
11865 .min_by(|&a, &b| {
11866 let d = |q: i32| (f64::from(ac_q(8, q)) - target).abs();
11867 d(a).partial_cmp(&d(b)).expect("ac_q is finite")
11868 })
11869 .expect("the qindex range is not empty")
11870 - i32::from(base);
11871 let want = (exact as f64 * k).round() as i32;
11872 // Snapped to the `res` grid BEFORE the clamp: `clamp` is a qindex bound
11873 // and need not be a whole number of steps, and clamping afterwards would
11874 // hand back a qindex that is not congruent to `base`.
11875 let max_steps = clamp / res;
11876 let steps = (want as f64 / f64::from(res)).round() as i32;
11877 let delta = steps.clamp(-max_steps, max_steps) * res;
11878 (i32::from(base) + delta).clamp(1, 255) as u8
11879}
11880
11881/// lane-dq: derive the per-superblock qindex libaom's `deltaq-mode 1`
11882/// objective would, from the SAME tpl dependence ratio our own map already
11883/// carries (`EC_AV1_DQ_TPL=1`).
11884///
11885/// libaom (`av1_get_q_for_deltaq_objective`, encodeframe_utils.c) forms a
11886/// superblock dependence ratio `rk = exp((intra_cost - mc_dep_cost)/w)` in the
11887/// LOG domain, divides the frame-level `r0` (`encoder_utils.c:627`, the very
11888/// same expression at frame scope) by it, and asks
11889/// `av1_get_deltaq_offset(bit_depth, base, beta)` for the qindex whose
11890/// **DC** step is `dc_q(base)/sqrt(beta)`. With per-cell costs `intra` and
11891/// `intra + mc_dep`, `rk` is `1/(1 + r)` for this crate's `r = mc_dep/intra`,
11892/// so `beta = (1 + r_sb) / (1 + r_frame)` with `r_frame` read the log-mean way
11893/// libaom reads `r0`. The offset is clamped to libaom's own
11894/// `+-(delta_q_res * 9 - 1)`, which at `res = 4` is +-8 steps -- more than
11895/// twice the +-16 qindex [`deltaq_for_factor`] allows.
11896///
11897/// Two things differ from [`deltaq_for_factor`] and both are the point of the
11898/// arm: the table inverted is `dc_q` not `ac_q`, and the ratio is read raw
11899/// (`sqrt(1 + r)`) rather than through the map's `log2`-compressed,
11900/// `TPL_POWER`-flattened, mean-normalised lambda factor -- so this mapping is
11901/// much stronger for the same map. `strength` scales the offset.
11902fn deltaq_libaom(base: u8, r_sb: f64, r_frame: f64, strength: f64, res: i32) -> u8 {
11903 let beta = ((1.0 + r_sb.max(0.0)) / (1.0 + r_frame.max(0.0))).max(1e-6);
11904 let target = f64::from(crate::quant::dc_q(8, i32::from(base))) / beta.sqrt();
11905 let exact = (1..=255)
11906 .min_by(|&a, &b| {
11907 let d = |q: i32| (f64::from(crate::quant::dc_q(8, q)) - target).abs();
11908 d(a).partial_cmp(&d(b)).expect("dc_q is finite")
11909 })
11910 .expect("the qindex range is not empty")
11911 - i32::from(base);
11912 let want = exact as f64 * strength;
11913 // Snapped onto the `res` grid first, so the coded delta is a whole number
11914 // of steps, then bounded by libaom's own `res * 9 - 1`.
11915 let max_steps = (res * 9 - 1) / res;
11916 let steps = (want / f64::from(res)).round() as i32;
11917 let delta = steps.clamp(-max_steps, max_steps) * res;
11918 (i32::from(base) + delta).clamp(1, 255) as u8
11919}
11920
11921/// The frame-level `r0` libaom's objective divides by: the log-mean of
11922/// `1 + r` over the frame's cells, minus 1.
11923fn tpl_frame_ratio(ratio: &[f64]) -> f64 {
11924 if ratio.is_empty() {
11925 return 0.0;
11926 }
11927 let m = ratio.iter().map(|&r| (1.0 + r.max(0.0)).ln()).sum::<f64>() / ratio.len() as f64;
11928 m.exp() - 1.0
11929}
11930
11931/// The [`deltaq_libaom`] strength, or `None` to keep the shipped
11932/// [`deltaq_for_factor`] derivation.
11933///
11934/// `EC_AV1_DQ_TPL=0`/`1` forces the mapping either way and `EC_AV1_DQ_TPL_K`
11935/// the strength (default 1.0 = libaom's own offset when the flag armed it);
11936/// with neither set the preset decides, see [`crate::speed::DQ_TPL_K`].
11937fn dq_tpl_strength(level: DqLevel) -> Option<f64> {
11938 let m = dq_level_k()[level as usize];
11939 let env_k = crate::envflags::var("EC_AV1_DQ_TPL_K")
11940 .ok()
11941 .and_then(|v| v.trim().parse::<f64>().ok())
11942 .filter(|k| k.is_finite() && *k >= 0.0);
11943 let base = match crate::envflags::var("EC_AV1_DQ_TPL").ok().as_deref().map(str::trim) {
11944 Some("0") => return None,
11945 Some(_) => Some(env_k.unwrap_or(1.0)),
11946 None => env_k.or_else(|| Some(crate::speed::at(&crate::speed::DQ_TPL_K))),
11947 };
11948 base.map(|k| k * m).filter(|k| *k > 0.0)
11949}
11950
11951/// lane-arfq: which pyramid level the frame asking for a
11952/// [`dq_tpl_strength`] sits at. The KEY frame is not here on purpose: it
11953/// codes no `delta_q` syntax at all (the whole lever lives in
11954/// [`encode_inter_frame`]), so a per-level strength cannot touch it -- the
11955/// key's allocation is [`crate::encoder::Pyramid::key_q_offset`]'s job.
11956#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11957pub(crate) enum DqLevel {
11958 /// The mini-GOP's own hidden `ALTREF`, which every other frame of the
11959 /// group predicts from (directly or through the mid level).
11960 TopArf = 0,
11961 /// A hidden mid/quarter-point `ALTREF`, read by the leaves around it.
11962 MidArf = 1,
11963 /// A shown leaf -- and every frame of the flat, non-pyramid path.
11964 Leaf = 2,
11965}
11966
11967/// The per-level multiplier on the [`dq_tpl_strength`] the preset carries:
11968/// `EC_AV1_DQ_K=<top arf>:<mid arf>:<leaf>`, else
11969/// [`crate::speed::DQ_LEVEL_K`]. Three fields, not four: the key frame codes
11970/// no `delta_q` (see [`DqLevel`]).
11971fn dq_level_k() -> [f64; 3] {
11972 dq_level_k_of(crate::envflags::var("EC_AV1_DQ_K").ok().as_deref())
11973}
11974
11975/// [`dq_level_k`]'s parse, pure: a missing spec, a missing field and an
11976/// unparseable one all keep [`crate::speed::DQ_LEVEL_K`]'s entry.
11977fn dq_level_k_of(spec: Option<&str>) -> [f64; 3] {
11978 let mut k = crate::speed::DQ_LEVEL_K;
11979 if let Some(spec) = spec {
11980 for (slot, field) in k.iter_mut().zip(spec.split(':')) {
11981 if let Some(v) =
11982 field.trim().parse::<f64>().ok().filter(|v: &f64| v.is_finite() && *v >= 0.0)
11983 {
11984 *slot = v;
11985 }
11986 }
11987 }
11988 k
11989}
11990
11991/// `EC_AV1_DQ_CENSUS=1`: per inter frame, one line comparing the offsets the
11992/// shipped mapping ([`deltaq_for_factor`]) WOULD emit against the ones
11993/// libaom's objective ([`deltaq_libaom`]) gives for the same superblocks and
11994/// the same tpl map -- and which of the two the frame actually coded.
11995fn dq_census() -> bool {
11996 crate::envflags::var("EC_AV1_DQ_CENSUS").ok().as_deref().map(str::trim) == Some("1")
11997}
11998
11999/// The histogram/extent summary [`dq_census`] prints for one set of offsets.
12000fn dq_summary(offsets: &[i32]) -> String {
12001 let n = offsets.len().max(1);
12002 let (lo, hi) = offsets.iter().fold((0i32, 0i32), |(l, h), &o| (l.min(o), h.max(o)));
12003 let nz = offsets.iter().filter(|&&o| o != 0).count();
12004 let mean = offsets.iter().map(|&o| f64::from(o)).sum::<f64>() / n as f64;
12005 let absmean = offsets.iter().map(|&o| f64::from(o.abs())).sum::<f64>() / n as f64;
12006 let mut levels: Vec<i32> = offsets.to_vec();
12007 levels.sort_unstable();
12008 levels.dedup();
12009 format!(
12010 "range {lo}..{hi} mean {mean:+.2} |mean| {absmean:.2} nonzero {nz}/{} levels {}",
12011 offsets.len(),
12012 levels.len()
12013 )
12014}
12015
12016/// How many DISTINCT per-superblock quantizer levels the last inter frame's
12017/// [`sb_q`](encode_inter_frame) grid carried -- lane-deltaq's fire counter
12018/// (class `gate-blind-to-feature`: every exactness assert below passes on a
12019/// grid that is one flat value, i.e. on no delta_q at all). Process-global
12020/// like [`TX_DEPTH_HITS`], and read through [`take_deltaq_levels`], which
12021/// keeps the LARGEST count seen since the last read.
12022static DELTAQ_LEVELS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
12023
12024/// [`DELTAQ_LEVELS`], reset to 0.
12025#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
12026pub(crate) fn take_deltaq_levels() -> usize {
12027 DELTAQ_LEVELS.swap(0, std::sync::atomic::Ordering::Relaxed)
12028}
12029
12030/// This superblock's search state: the quantizer it is coded at, and the
12031/// lambda that quantizer implies. RD lambda goes as the square of the step,
12032/// which is exactly the relation [`deltaq_for_factor`] inverted, so with no
12033/// `sb_q` grid the caller keeps the tpl LAMBDA factor alone (the behaviour
12034/// before lane-deltaq).
12035fn sb_q_search<'m>(
12036 sb_q: &[u8],
12037 sb_cols: usize,
12038 base_q_idx: u8,
12039 (sb_r, sb_c): (usize, usize),
12040 base: Search<'m>,
12041) -> Search<'m> {
12042 let q = sb_q[sb_r * sb_cols + sb_c];
12043 let ratio = f64::from(ac_q(8, i32::from(q))) / f64::from(ac_q(8, i32::from(base_q_idx)));
12044 Search { base_q_idx: q, lambda: base.lambda * ratio * ratio, ..base }
12045}
12046
12047fn tpl_strength() -> f64 {
12048 std::env::var("EC_AV1_TPL")
12049 .ok()
12050 .and_then(|v| v.parse::<f64>().ok())
12051 .filter(|k| k.is_finite() && *k >= 0.0)
12052 .unwrap_or(TPL_STRENGTH)
12053}
12054
12055/// lane-av1tpl2: how many SOURCE pictures the lambda map looks at, counting
12056/// the frame being coded. 1 turns the weighting off; 2 is the shipped
12057/// one-frame area map ([`tpl_area_map`]); 3 and up only mean anything under
12058/// [`tpl_propagating`], which is the map that can actually use them and is
12059/// the default since lane-av1tpl3, so the default window is 8. Swept by
12060/// `EC_AV1_TPL_D=<d>`.
12061///
12062/// The streaming facade holds `depth - 1` pictures back so it feeds
12063/// `encode_inter_frame` the same window `encode_sequence` does; both read
12064/// THIS function, so the two paths cannot disagree about the window.
12065pub(crate) const TPL_DEPTH: usize = 8;
12066
12067/// The exponent the dependence ratio is read through ([`tpl_lambda_factors`]).
12068/// 0.5 is libaom's own square-root compression of its dependence ratio.
12069const TPL_POWER: f64 = 0.5;
12070
12071/// lane-av1tpl2: the propagating map ([`tpl_lambda_factors`]) instead of the
12072/// one-frame area map ([`tpl_area_map`]), behind `EC_AV1_TPL_PROP=1`.
12073///
12074/// MEASURED at the native gate (1920x1024, 12 frames, BD-rate vs libaom
12075/// `cpu-used 6` / rav1e `speed 6`), against the shipped one-frame map
12076/// (+15.9/-1.3, +46.5/+18.7, +51.2/-14.4). `p` is [`TPL_POWER`]:
12077///
12078/// | k | D | p | film 1080p | film 2160p | screen |
12079/// |---|---|---|---|---|---|
12080/// | 0.0625 | 8 | 1 | +15.7/-1.6 | +46.6/+18.8 | +51.1/-14.5 |
12081/// | 0.125 | 4 | 1 | +15.7/-1.6 | +46.7/+18.9 | +51.2/-14.5 |
12082/// | 0.125 | 8 | 1 | +15.9/-1.3 | +46.8/+19.0 | +50.7/-14.7 |
12083/// | 0.25 | 4 | 1 | +15.5/-1.8 | +46.8/+19.1 | +51.2/-14.5 |
12084/// | 0.25 | 8 | 1 | +15.7/-1.6 | +46.9/+19.1 | +50.7/-14.6 |
12085/// | 0.5 | 4 | 1 | +16.1/-1.2 | +47.0/+19.2 | +51.1/-14.6 |
12086/// | 0.5 | 8 | 1 | +16.0/-1.4 | +47.1/+19.3 | +51.8/-13.9 |
12087/// | 1 | 4 | 1 | +16.2/-1.3 | +47.2/+19.4 | +51.9/-13.9 |
12088/// | 2 | 4 | 1 | +17.2/-0.5 | +47.2/+19.5 | +57.0/-10.7 |
12089/// | **0.5** | **8** | **0.5** | **+15.5/-1.7** | **+46.7/+19.0** | **+50.8/-14.6** |
12090/// | 0.5 | 4 | 0.5 | +15.6/-1.6 | +46.8/+19.0 | +51.0/-14.6 |
12091/// | 1 | 8 | 0.5 | +15.9/-1.5 | +47.0/+19.2 | +51.0/-14.5 |
12092///
12093/// The map is genuinely non-flat (0.25..1.12 across 7680 cells, only 58 of
12094/// them within 0.9..1.1, where the one-frame map had 7127 of 7680 inside
12095/// 1..1.5x its own mean), and its best arm was 0.4 down on both film 1080p
12096/// columns and 0.4/0.2 down on screen -- but EVERY arm of that lane was
12097/// 0.1..0.4 UP on film 2160p, so it shipped off.
12098///
12099/// lane-av1tpl3 found why and turned it on. The denominator is the cell's own
12100/// MAD from its DC, and on the gate's film clips (ffmpeg `testsrc2`, colour
12101/// bars) 89.4% (1080p) / 90.8% (2160p) of all 16x16 cells have a MAD of
12102/// EXACTLY ZERO -- so a per-16x16 ratio is a huge number divided by 1
12103/// wherever the window leans on a flat bar, which is exactly where coding is
12104/// cheap. Summing intra and mc_dep over the 64x64 superblock before the ratio
12105/// (libaom's own granularity) puts a busy cell's denominator next to the flat
12106/// one's, and reading the ratio through `log2(1 + r)` (libaom's compressed
12107/// beta) flattens what is left of the tail. Both on, at k=0.5 D=8 p=0.5, on
12108/// the same native gate (baseline = the shipped one-frame map):
12109///
12110/// | arm | film 1080p | film 2160p | screen |
12111/// |---|---|---|---|
12112/// | one-frame map (was default) | +15.9/-1.3 | +46.5/+18.7 | +51.2/-14.4 |
12113/// | propagating, per-16x16 | +15.5/-1.7 | +46.7/+19.0 | +50.8/-14.6 |
12114/// | + denominator floor 0.25x mean | +15.7/-1.5 | +46.9/+19.1 | +50.9/-14.6 |
12115/// | + floor 0.5x mean | +15.7/-1.5 | +46.8/+19.0 | +50.8/-14.5 |
12116/// | + floor 1.0x mean | +15.8/-1.4 | +46.9/+19.1 | +51.0/-14.5 |
12117/// | + 64x64 aggregation | +15.9/-1.3 | +46.6/+18.8 | +51.1/-14.6 |
12118/// | + log2 beta | +16.0/-1.3 | +46.9/+19.0 | +51.0/-14.6 |
12119/// | + aggregation + floor 0.25x | +15.7/-1.5 | +46.6/+18.9 | +50.9/-14.6 |
12120/// | + aggregation + floor 0.5x | +16.0/-1.3 | +46.9/+19.1 | +50.8/-14.7 |
12121/// | **+ aggregation + log2 beta** | **+15.6/-1.7** | **+46.5/+18.8** | **+51.0/-14.5** |
12122///
12123/// The last row is the only arm that is down on two rows (film 1080p 0.3/0.4,
12124/// screen 0.2/0.1) and flat on the third (film 2160p 0.0/+0.1), so it ships
12125/// as the default: `EC_AV1_TPL_PROP=0` goes back to the one-frame map. The
12126/// floor is a real effect on the ratio and never a win once the aggregation
12127/// is in -- the aggregation is the same fix, done where libaom does it.
12128fn tpl_propagating() -> bool {
12129 std::env::var("EC_AV1_TPL_PROP").ok().as_deref() != Some("0")
12130}
12131
12132pub(crate) fn tpl_depth() -> usize {
12133 std::env::var("EC_AV1_TPL_D")
12134 .ok()
12135 .and_then(|v| v.parse::<usize>().ok())
12136 .filter(|d| *d >= 1)
12137 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_DEPTH))
12138 .max(1)
12139}
12140
12141/// Nanoseconds the lookahead pass ([`tpl_lambda_factors`]) has spent this
12142/// process, so the gate can price it against the encode it rides on.
12143static TPL_NANOS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
12144
12145/// One coarse full-pel 16x16 motion pass of `next` against `cur`: per cell,
12146/// the winning displacement and its SAD.
12147///
12148/// Deterministic: integer SADs, a fixed 3-step pattern seeded at zero and at
12149/// the left/above winners, first-best tie-break. Built once on the frame's
12150/// own thread and read-only afterwards, so it cannot make a tile's bytes
12151/// depend on the thread count.
12152fn tpl_coarse_pass(
12153 cur: &[u8],
12154 next: &[u8],
12155 width: usize,
12156 height: usize,
12157) -> Vec<((i32, i32), u32)> {
12158 let (cells_x, cells_y) = (width / 16, height / 16);
12159 let sad = |bx: usize, by: usize, (mx, my): (i32, i32)| -> u32 {
12160 let (sx, sy) = (bx as i32 + mx, by as i32 + my);
12161 if sx < 0 || sy < 0 || sx as usize + 16 > width || sy as usize + 16 > height {
12162 return u32::MAX;
12163 }
12164 let (sx, sy) = (sx as usize, sy as usize);
12165 let mut sum = 0u32;
12166 for r in 0..16 {
12167 let a = &next[(by + r) * width + bx..][..16];
12168 let b = &cur[(sy + r) * width + sx..][..16];
12169 sum += a.iter().zip(b).map(|(&p, &q)| u32::from(p.abs_diff(q))).sum::<u32>();
12170 }
12171 sum
12172 };
12173 let mut out = Vec::with_capacity(cells_x * cells_y);
12174 let mut above = vec![(0i32, 0i32); cells_x];
12175 for cy in 0..cells_y {
12176 let mut left = (0i32, 0i32);
12177 for cx in 0..cells_x {
12178 let (bx, by) = (cx * 16, cy * 16);
12179 let mut best = (sad(bx, by, (0, 0)), (0i32, 0i32));
12180 for cand in [left, above[cx]] {
12181 if cand != (0, 0) {
12182 let s = sad(bx, by, cand);
12183 if s < best.0 {
12184 best = (s, cand);
12185 }
12186 }
12187 }
12188 for step in [8i32, 4, 2, 1] {
12189 let centre = best.1;
12190 for (dx, dy) in [(step, 0), (-step, 0), (0, step), (0, -step)] {
12191 let mv = (centre.0 + dx, centre.1 + dy);
12192 if mv.0.abs() > 32 || mv.1.abs() > 32 {
12193 continue;
12194 }
12195 let s = sad(bx, by, mv);
12196 if s < best.0 {
12197 best = (s, mv);
12198 }
12199 }
12200 }
12201 left = best.1;
12202 above[cx] = best.1;
12203 out.push((best.1, best.0));
12204 }
12205 }
12206 out
12207}
12208
12209/// The intra-cost proxy libaom's tpl gets from a DC prediction plus a
12210/// transform: here, the mean absolute deviation of the cell from its own DC.
12211/// It is the denominator every propagated cost is read against, so only its
12212/// SHAPE across the frame matters, not its scale.
12213fn tpl_intra_costs(frame: &[u8], width: usize, height: usize) -> Vec<u32> {
12214 let (cells_x, cells_y) = (width / 16, height / 16);
12215 let mut out = Vec::with_capacity(cells_x * cells_y);
12216 for cy in 0..cells_y {
12217 for cx in 0..cells_x {
12218 let (bx, by) = (cx * 16, cy * 16);
12219 let mut sum = 0u32;
12220 for r in 0..16 {
12221 sum += frame[(by + r) * width + bx..][..16].iter().map(|&p| u32::from(p)).sum::<u32>();
12222 }
12223 let dc = ((sum + 128) / 256) as u8;
12224 let mut cost = 0u32;
12225 for r in 0..16 {
12226 cost += frame[(by + r) * width + bx..][..16]
12227 .iter()
12228 .map(|&p| u32::from(p.abs_diff(dc)))
12229 .sum::<u32>();
12230 }
12231 out.push(cost);
12232 }
12233 }
12234 out
12235}
12236
12237/// lane-av1tpl's one-frame map, in terms of the pass above: how much of THIS
12238/// frame the next one predicts from, per 16x16 cell -- each cell of `next`
12239/// splats its own area, at its winning displacement, onto the (at most four)
12240/// cells of `cur` it lands on. 1.0 is "referenced exactly once".
12241fn tpl_area_map(cur: &[u8], next: &[u8], width: usize, height: usize) -> Vec<f64> {
12242 let start = std::time::Instant::now();
12243 let (cells_x, cells_y) = (width / 16, height / 16);
12244 let pass = tpl_coarse_pass(cur, next, width, height);
12245 let mut area = vec![0.0f64; cells_x * cells_y];
12246 for cy in 0..cells_y {
12247 for cx in 0..cells_x {
12248 let (mv, _) = pass[cy * cells_x + cx];
12249 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
12250 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
12251 for ci in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
12252 let ox = (x0 + 16).min(ci * 16 + 16) - x0.max(ci * 16);
12253 for ri in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
12254 let oy = (y0 + 16).min(ri * 16 + 16) - y0.max(ri * 16);
12255 area[ri * cells_x + ci] += (ox * oy) as f64 / 256.0;
12256 }
12257 }
12258 }
12259 }
12260 TPL_NANOS.fetch_add(
12261 start.elapsed().as_nanos() as u64,
12262 std::sync::atomic::Ordering::Relaxed,
12263 );
12264 area
12265}
12266
12267/// [`tpl_area_map`]'s per-cell referenced-ness turned into one lambda
12268/// factor per 64x64 superblock: `f = (1 + k) / (1 + k * w_rel)`, where
12269/// `w_rel` is the superblock's mean referenced-ness over the FRAME's mean.
12270/// Decreasing in referenced-ness (a block the next frame leans on is coded
12271/// more distortion-averse) and 1.0 at the frame's own mean, so the frame's
12272/// total lambda scale is only redistributed, never moved -- a global move is
12273/// the thing lane-av1lambda already measured inert.
12274fn tpl_sb_factors(map: &[f64], cells_x: usize, cells_y: usize, k: f64) -> Vec<f64> {
12275 let (sb_cols, sb_rows) = (cells_x / 4, cells_y / 4);
12276 let mean = (map.iter().sum::<f64>() / map.len().max(1) as f64).max(1e-6);
12277 let mut out = Vec::with_capacity(sb_cols * sb_rows);
12278 for sr in 0..sb_rows {
12279 for sc in 0..sb_cols {
12280 let mut sum = 0.0;
12281 for r in 0..4 {
12282 for c in 0..4 {
12283 sum += map[(sr * 4 + r) * cells_x + sc * 4 + c];
12284 }
12285 }
12286 let w_rel = sum / 16.0 / mean;
12287 out.push(((1.0 + k) / (1.0 + k * w_rel)).clamp(0.25, 4.0));
12288 }
12289 }
12290 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
12291 let mut hist = [0usize; 8];
12292 for w in map {
12293 hist[((w / mean * 2.0) as usize).min(7)] += 1;
12294 }
12295 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
12296 eprintln!(
12297 "tpl k={k}: {} cells mean w={mean:.3}, w/mean hist (0-.5,.5-1,..,>3.5) {hist:?}, \
12298 sb factor {lo:.3}..{hi:.3}, lookahead wall {:.1} ms cumulative",
12299 map.len(),
12300 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
12301 );
12302 }
12303 out
12304}
12305
12306/// libaom's `tpl_model_update` in this crate's cheapest shape: one lambda
12307/// factor per 16x16 cell of `frames[0]` (the frame being coded), from how
12308/// much of the WHOLE lookahead window leans on that cell.
12309///
12310/// Per lookahead level `f` (source `frames[f]` against `frames[f-1]`) the
12311/// coarse pass gives a displacement and an inter cost; a cell's own
12312/// propagated cost is `max(intra - inter, 0) + mc_dep` -- what coding that
12313/// cell well saves the frames that predict from it -- and it is splatted,
12314/// area-weighted, onto the (at most four) cells of `frames[f-1]` its
12315/// displacement lands on. Walking `f` from the far end of the window back to
12316/// 1 accumulates the whole chain into level 0, which lane-av1tpl's one-frame
12317/// area map could not do at all.
12318///
12319/// The factor is `f = 1 / (1 + k * mc_dep / intra)`, normalised so the mean
12320/// factor over the frame is exactly 1: a cell the window leans on is coded
12321/// more distortion-averse (smaller lambda), and the frame's TOTAL lambda
12322/// scale only moves around, never up or down -- a global move is what
12323/// lane-av1lambda already measured inert.
12324/// Returns the per-cell lambda factors AND the per-cell dependence ratio
12325/// `mc_dep / intra` they were derived from -- the second half is what
12326/// [`deltaq_libaom`] needs, since the factor alone has been through a
12327/// mean normalisation the raw ratio cannot be recovered across.
12328fn tpl_lambda_factors(
12329 frames: &[&[u8]],
12330 width: usize,
12331 height: usize,
12332 k: f64,
12333) -> (Vec<f64>, Vec<f64>) {
12334 let start = std::time::Instant::now();
12335 let (cells_x, cells_y) = (width / 16, height / 16);
12336 let cells = cells_x * cells_y;
12337 let levels = frames.len();
12338 let intra: Vec<Vec<u32>> = frames.iter().map(|f| tpl_intra_costs(f, width, height)).collect();
12339 let passes: Vec<Vec<((i32, i32), u32)>> = (1..levels)
12340 .map(|f| tpl_coarse_pass(frames[f - 1], frames[f], width, height))
12341 .collect();
12342 let mut mc_dep = vec![vec![0.0f64; cells]; levels];
12343 for f in (1..levels).rev() {
12344 for cy in 0..cells_y {
12345 for cx in 0..cells_x {
12346 let ci = cy * cells_x + cx;
12347 let (mv, inter) = passes[f - 1][ci];
12348 let saved = f64::from(intra[f][ci].saturating_sub(inter));
12349 let propagate = saved + mc_dep[f][ci];
12350 if propagate <= 0.0 {
12351 continue;
12352 }
12353 // The 16x16 window of the PREVIOUS frame this cell predicted
12354 // from, spread over the cells it overlaps.
12355 let (x0, y0) = ((cx * 16) as i32 + mv.0, (cy * 16) as i32 + mv.1);
12356 let (x0, y0) = (x0.max(0) as usize, y0.max(0) as usize);
12357 for rc in x0 / 16..=((x0 + 15) / 16).min(cells_x - 1) {
12358 let ox = (x0 + 16).min(rc * 16 + 16) - x0.max(rc * 16);
12359 for rr in y0 / 16..=((y0 + 15) / 16).min(cells_y - 1) {
12360 let oy = (y0 + 16).min(rr * 16 + 16) - y0.max(rr * 16);
12361 mc_dep[f - 1][rr * cells_x + rc] += propagate * (ox * oy) as f64 / 256.0;
12362 }
12363 }
12364 }
12365 }
12366 }
12367 // The tail compression `p`: `mc_dep/intra` is a ratio with a very long
12368 // tail (a nearly flat cell the window leans on has a tiny denominator),
12369 // and at p = 1 that tail slams into the clamp. libaom reads its own
12370 // dependence ratio through a sqrt (`dr_from_beta`); `EC_AV1_TPL_P`
12371 // sweeps the exponent, 1 being the raw ratio.
12372 let power = std::env::var("EC_AV1_TPL_P")
12373 .ok()
12374 .and_then(|v| v.parse::<f64>().ok())
12375 .filter(|p| p.is_finite() && *p > 0.0)
12376 .unwrap_or(TPL_POWER);
12377 // lane-av1tpl3, the three shape fixes, each its own knob so the gate can
12378 // read them apart. `SB` and `LOG` are the shipped shape (set the knob to
12379 // `0` to take either back out); `FLOOR` defaults to off.
12380 //
12381 // * `EC_AV1_TPL_FLOOR=<f>` floors the denominator at `f` times the
12382 // frame's own mean intra cost. A cell of flat content has a near-zero
12383 // MAD, so its ratio explodes exactly where coding is cheap.
12384 // * `EC_AV1_TPL_SB=0` goes back to a per-16x16 ratio; by default intra
12385 // and mc_dep are summed over the 64x64 superblock first -- libaom's
12386 // granularity (`mc_dep_cost` and `intra_cost` are SB sums there, not
12387 // per-16x16 numbers), which is also what makes the ratio survive one
12388 // flat cell next to a busy one.
12389 // * `EC_AV1_TPL_LOG=0` reads the raw ratio; by default it goes through
12390 // `log2(1 + r)`, libaom's log-compressed beta, which flattens the tail
12391 // harder than the `p` exponent alone can.
12392 let floor_frac = std::env::var("EC_AV1_TPL_FLOOR")
12393 .ok()
12394 .and_then(|v| v.parse::<f64>().ok())
12395 .filter(|f| f.is_finite() && *f >= 0.0)
12396 .unwrap_or(0.0);
12397 let sb_agg = std::env::var("EC_AV1_TPL_SB").ok().as_deref() != Some("0");
12398 let log_beta = std::env::var("EC_AV1_TPL_LOG").ok().as_deref() != Some("0");
12399 let intra_mean =
12400 intra[0].iter().map(|&c| f64::from(c)).sum::<f64>() / cells.max(1) as f64;
12401 let floor = floor_frac * intra_mean;
12402 let denom = |c: usize| f64::from(intra[0][c].max(1)).max(floor).max(1.0);
12403 // Per-cell ratios, or one ratio per 64x64 superblock (4x4 cells) shared by
12404 // every cell under it. The edge groups are partial and summed as they are.
12405 let ratio: Vec<f64> = if sb_agg {
12406 let (sb_cols, sb_rows) = (cells_x.div_ceil(4), cells_y.div_ceil(4));
12407 let mut sb = vec![(0.0f64, 0.0f64); sb_cols * sb_rows];
12408 for cy in 0..cells_y {
12409 for cx in 0..cells_x {
12410 let e = &mut sb[(cy / 4) * sb_cols + cx / 4];
12411 e.0 += mc_dep[0][cy * cells_x + cx];
12412 e.1 += denom(cy * cells_x + cx);
12413 }
12414 }
12415 (0..cells)
12416 .map(|c| {
12417 let (dep, den) = sb[(c / cells_x / 4) * sb_cols + (c % cells_x) / 4];
12418 dep / den.max(1.0)
12419 })
12420 .collect()
12421 } else {
12422 (0..cells).map(|c| mc_dep[0][c] / denom(c)).collect()
12423 };
12424 let mut out: Vec<f64> = ratio
12425 .iter()
12426 .map(|&r| {
12427 let r = if log_beta { (1.0 + r).log2() } else { r };
12428 (1.0 + k * r).powf(-power)
12429 })
12430 .collect();
12431 let mean = (out.iter().sum::<f64>() / cells.max(1) as f64).max(1e-9);
12432 for f in &mut out {
12433 *f = (*f / mean).clamp(0.25, 4.0);
12434 }
12435 TPL_NANOS.fetch_add(
12436 start.elapsed().as_nanos() as u64,
12437 std::sync::atomic::Ordering::Relaxed,
12438 );
12439 if std::env::var("EC_AV1_TPL_HIST").ok().as_deref() == Some("1") {
12440 let mut hist = [0usize; 8];
12441 for &f in &out {
12442 hist[((f * 4.0) as usize).min(7)] += 1;
12443 }
12444 let (lo, hi) = out.iter().fold((f64::MAX, 0.0f64), |(l, h), &f| (l.min(f), h.max(f)));
12445 let flat = out.iter().filter(|&&f| (0.9..=1.1).contains(&f)).count();
12446 eprintln!(
12447 "tpl k={k} d={levels}: {cells} cells, factor hist (0-.25,.25-.5,..,>1.75) {hist:?}, \
12448 range {lo:.3}..{hi:.3}, {flat} within 0.9..1.1, lookahead wall {:.1} ms cumulative",
12449 TPL_NANOS.load(std::sync::atomic::Ordering::Relaxed) as f64 / 1e6,
12450 );
12451 }
12452 (out, ratio)
12453}
12454
12455/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
12456/// references name, which slot it refreshes, whether it is shown when it is
12457/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
12458/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
12459/// 0/2 alternation, every frame shown, every reference in the past).
12460///
12461/// The sign bias is carried rather than derived here because only the caller
12462/// knows what order hint each slot holds; it is armed onto the tile writer
12463/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
12464/// the writer scans the same stacks the decoder will.
12465#[derive(Debug, Clone, Copy)]
12466pub(crate) struct PyramidFrame {
12467 /// The slot `LAST_FRAME` (and every reference this encoder does not name
12468 /// apart) reads.
12469 pub last_slot: u8,
12470 /// The single slot `refresh_frame_flags` sets.
12471 pub self_slot: u8,
12472 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
12473 /// pyramid, which is what makes `sign_bias`'s last entry true.
12474 pub altref_slot: u8,
12475 /// lane-last2: the slot `LAST2_FRAME` reads -- a SECOND, older past
12476 /// picture (the leaf chain alternates its refresh between two slots, so
12477 /// the frame before `LAST` is still intact). `None` leaves
12478 /// `ref_frame_idx[1]` naming `last_slot`, as every frame this encoder
12479 /// wrote before, and the caller then passes no `last2` picture either.
12480 pub last2_slot: Option<u8>,
12481 /// `show_frame`: false for a hidden frame, output later by a
12482 /// `show_existing_frame` header.
12483 pub show_frame: bool,
12484 /// lane-arfq: which level's `delta_q` strength this frame reads
12485 /// ([`DqLevel`]) -- the caller knows it, since the top ARF and the mid
12486 /// one share `Level::Arf` and differ only by their q offset.
12487 pub dq_level: DqLevel,
12488 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
12489 pub sign_bias: crate::mvstack::SignBiasTable,
12490}
12491
12492/// lane-arfpred: the temporal filter of a top ARF's SOURCE picture, libaom's
12493/// `temporal_filter` in the small: every 16x16 luma block of `src` is
12494/// motion-compensated from each picture of `window` (the group's own display
12495/// neighbours, nearest first) and averaged in with weight
12496/// `exp(-mse / strength)`, so a neighbour that matches badly contributes
12497/// nothing and one that matches well cancels the grain the block's residual
12498/// would otherwise have to code.
12499///
12500/// `strength` is [`crate::speed::ARF_TF`]; `0` never reaches here. Chroma
12501/// rides the luma block's own vector (halved), which is what libaom does at
12502/// this block size. The picture is the SUPERBLOCK-padded one, so the 16x16
12503/// grid tiles it exactly.
12504///
12505/// Priced before it was built by `encode::tests::arf_pred_census`: on film B
12506/// the filtered ARF's prediction SAD at lag 8 is 11.7% below the unfiltered
12507/// one's (film A 5.9%) with the two past neighbours at strength 30, and the
12508/// filtered picture is 50.1 dB from the source it replaces -- 4 dB above the
12509/// quality the ARF is coded at, so the substitution itself costs little.
12510// lane-lookahead: the CALLER sizes `window` (`ARF_TF_WIN` past neighbours and
12511// `ARF_TF_WIN_FUT` future ones); this takes every picture in it.
12512pub(crate) fn arf_temporal_filter(src: &Picture, window: &[Picture], strength: f64) -> Picture {
12513 const SIDE: usize = 16;
12514 let neighbours: Vec<&Picture> = window
12515 .iter()
12516 .filter(|p| p.width == src.width && p.height == src.height)
12517 .collect();
12518 if neighbours.is_empty() || strength <= 0.0 {
12519 return src.clone();
12520 }
12521 let mut out = src.clone();
12522 // SAD of `src`'s block at `(bx, by)` against `r` displaced by `mv`, or
12523 // `None` when the displaced block leaves the picture.
12524 let sad = |r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
12525 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
12526 if sy < 0 || sx < 0 || sy as usize + SIDE > r.height || sx as usize + SIDE > r.width {
12527 return None;
12528 }
12529 let (sy, sx) = (sy as usize, sx as usize);
12530 let mut acc = 0u64;
12531 for row in 0..SIDE {
12532 let c = &src.y[(by + row) * src.width + bx..][..SIDE];
12533 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
12534 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
12535 }
12536 Some((acc, (sy, sx)))
12537 };
12538 // The log-step diamond `arf_pred_census` priced this with.
12539 let search = |r: &Picture, bx: usize, by: usize| -> Option<(usize, usize)> {
12540 let mut best = sad(r, bx, by, (0, 0))?;
12541 let mut centre = (0isize, 0isize);
12542 let mut step = 16isize;
12543 while step >= 1 {
12544 let from = centre;
12545 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
12546 let mv = (from.0 + dy * step, from.1 + dx * step);
12547 if let Some(s) = sad(r, bx, by, mv) {
12548 if s.0 < best.0 {
12549 best = s;
12550 centre = mv;
12551 }
12552 }
12553 }
12554 step /= 2;
12555 }
12556 Some(best.1)
12557 };
12558 let (cw, ch) = (src.width / 2, src.height / 2);
12559 for by in (0..src.height).step_by(SIDE) {
12560 for bx in (0..src.width).step_by(SIDE) {
12561 if by + SIDE > src.height || bx + SIDE > src.width {
12562 continue;
12563 }
12564 let mut y_acc = vec![0f64; SIDE * SIDE];
12565 let mut c_acc = [vec![0f64; SIDE * SIDE / 4], vec![0f64; SIDE * SIDE / 4]];
12566 let mut wsum = 1.0f64;
12567 // Chroma keeps its OWN weight sum: an edge block whose halved
12568 // vector leaves the chroma plane contributes to luma only, and
12569 // dividing chroma by the luma sum would darken it (class
12570 // `metric blind to a plane`, on the encoder side).
12571 let mut cwsum = 1.0f64;
12572 for row in 0..SIDE {
12573 for col in 0..SIDE {
12574 y_acc[row * SIDE + col] = f64::from(src.y[(by + row) * src.width + bx + col]);
12575 }
12576 }
12577 for row in 0..SIDE / 2 {
12578 for col in 0..SIDE / 2 {
12579 let i = (by / 2 + row) * cw + bx / 2 + col;
12580 c_acc[0][row * SIDE / 2 + col] = f64::from(src.u[i]);
12581 c_acc[1][row * SIDE / 2 + col] = f64::from(src.v[i]);
12582 }
12583 }
12584 for r in &neighbours {
12585 let Some((sy, sx)) = search(r, bx, by) else { continue };
12586 let mut sse = 0f64;
12587 for row in 0..SIDE {
12588 for col in 0..SIDE {
12589 let d = f64::from(src.y[(by + row) * src.width + bx + col])
12590 - f64::from(r.y[(sy + row) * r.width + sx + col]);
12591 sse += d * d;
12592 }
12593 }
12594 let w = (-sse / (SIDE * SIDE) as f64 / strength).exp();
12595 for row in 0..SIDE {
12596 for col in 0..SIDE {
12597 y_acc[row * SIDE + col] +=
12598 w * f64::from(r.y[(sy + row) * r.width + sx + col]);
12599 }
12600 }
12601 // Chroma reads the luma vector halved; a block on the picture
12602 // edge whose halved vector would leave the chroma plane is
12603 // left to luma alone rather than clamped to a different
12604 // displacement than the luma it must stay registered with.
12605 let (cy, cx) = (sy / 2, sx / 2);
12606 if cy + SIDE / 2 <= ch && cx + SIDE / 2 <= cw {
12607 for row in 0..SIDE / 2 {
12608 for col in 0..SIDE / 2 {
12609 let i = (cy + row) * cw + cx + col;
12610 c_acc[0][row * SIDE / 2 + col] += w * f64::from(r.u[i]);
12611 c_acc[1][row * SIDE / 2 + col] += w * f64::from(r.v[i]);
12612 }
12613 }
12614 cwsum += w;
12615 }
12616 wsum += w;
12617 }
12618 for row in 0..SIDE {
12619 for col in 0..SIDE {
12620 out.y[(by + row) * src.width + bx + col] =
12621 (y_acc[row * SIDE + col] / wsum).round() as u16;
12622 }
12623 }
12624 for row in 0..SIDE / 2 {
12625 for col in 0..SIDE / 2 {
12626 let i = (by / 2 + row) * cw + bx / 2 + col;
12627 out.u[i] = (c_acc[0][row * SIDE / 2 + col] / cwsum).round() as u16;
12628 out.v[i] = (c_acc[1][row * SIDE / 2 + col] / cwsum).round() as u16;
12629 }
12630 }
12631 }
12632 }
12633 out
12634}
12635
12636/// Encodes one picture as an inter frame predicting from `reference`'s
12637/// reconstruction, which the caller decoded (or, for the frame right after
12638/// the key frame, is the key frame's own reconstruction).
12639pub(crate) fn encode_inter_frame(
12640 picture: &Picture,
12641 reference: &Picture,
12642 base_q_idx: u8,
12643 deadzone: f64,
12644 order_hint: u32,
12645 // The order hint each of the seven `ref_frame_idx` entries names, which a
12646 // decoder reads out of its own reference state -- only spec 5.9.22's
12647 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
12648 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
12649 // callers that follow this crate's own flat slot plan.
12650 order_hints: [u32; 7],
12651 render: (usize, usize),
12652 // The tables this frame's writer starts from: what the previous frame
12653 // stored into the slot this one's `primary_ref_frame` names. `None`
12654 // starts from the defaults, which is right only for the frame straight
12655 // after a key frame.
12656 start_cdfs: Option<&crate::cdf_state::Cdfs>,
12657 // The key frame's own (padded) reconstruction, which every frame of the
12658 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
12659 // with `LAST_FRAME` alone, exactly as before.
12660 golden: Option<&Picture>,
12661 // The frame two back, held in the slot this frame is about to refresh
12662 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
12663 // inter frames of a GOP, where the frame two back IS the key frame.
12664 altref: Option<&Picture>,
12665 // lane-last2: the picture in [`PyramidFrame::last2_slot`] -- the shown
12666 // frame BEFORE `reference` on the leaf chain, offered to the 32x32
12667 // search as `LAST2_FRAME` through the same search path `GOLDEN`/`ALTREF`
12668 // take. `None` (every caller but the pyramid leaves) codes the frame
12669 // with the reference set unchanged.
12670 last2: Option<&Picture>,
12671 fctx: &crate::decode::FrameCtx,
12672 // Where this frame sits in the coding-order pyramid; `None` is the flat
12673 // one-shown-frame-per-picture stream this encoder wrote before.
12674 pyramid: Option<PyramidFrame>,
12675 // lane-av1tpl2: the NEXT pictures' sources (up to [`tpl_depth`] - 1 of
12676 // them), padded like this one -- the lookahead window the per-block
12677 // lambda weighting propagates back through ([`tpl_lambda_factors`]). An
12678 // EMPTY slice codes the frame at one lambda, as before.
12679 lookahead: &[Picture],
12680) -> Result<Encoded> {
12681 picture.check()?;
12682 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
12683 return Err(Error::unsupported(
12684 "AV1 encode",
12685 "an inter frame is coded only for a picture that is a whole number \
12686 of 64x64 superblocks -- the inter tile writer never splits a \
12687 superblock's partition below that",
12688 ));
12689 }
12690 if reference.width != picture.width || reference.height != picture.height {
12691 return Err(Error::unsupported(
12692 "AV1 encode",
12693 "the reference picture must be the same size as the one being coded",
12694 ));
12695 }
12696
12697 // The single slot this crate's inter frames ever predict from or
12698 // refresh (`inter_frame_headers`'s contract): every frame both reads and
12699 // overwrites slot 0, so the frame just coded is always what the next one
12700 // predicts against.
12701 const LAST_SLOT: u8 = 0;
12702 // Slot 0 and slot 2 alternate so the frame two back survives one more
12703 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
12704 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
12705 // in the very slot it will overwrite.
12706 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
12707 let last_slot = pyramid.map_or(
12708 if order_hint <= 1 {
12709 LAST_SLOT
12710 } else if (order_hint - 1) % 2 == 1 {
12711 0
12712 } else {
12713 2
12714 },
12715 |p| p.last_slot,
12716 );
12717 // `render`, not `picture.width`/`picture.height`: `picture` here is
12718 // already padded to a whole number of superblocks (`encode_sequence`'s
12719 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
12720 // every true-edge clamp downstream) must come from the frame's real,
12721 // unpadded size, same as `key_frame_headers_colour` takes `render` and
12722 // not the padded picture in `encode_key_frame_inner`.
12723 let (seq, mut header) = inter_frame_headers_slots(
12724 render.0,
12725 render.1,
12726 base_q_idx,
12727 order_hint,
12728 last_slot,
12729 self_slot,
12730 match pyramid {
12731 Some(p) => p.altref_slot,
12732 None if altref.is_some() => self_slot,
12733 None => GOLDEN_SLOT,
12734 },
12735 )?;
12736 header.render_width = render.0 as u32;
12737 header.render_height = render.1 as u32;
12738 // lane-refs: this frame's motion-compensation kernel, written into the
12739 // header AND armed on the context every prediction reads, in one place so
12740 // the two cannot disagree (a header saying SMOOTH over a REGULAR-searched
12741 // tile decodes to different pixels than the encoder scored).
12742 header.interpolation_filter = frame_interp_filter();
12743 fctx.interp_filter.set(mc::InterpFilterKind::from_header(header.interpolation_filter));
12744 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
12745 // The order hint behind each `ref_frame_idx` entry. The flat path's own
12746 // slot plan (`inter_frame_headers_slots`) is: every reference but
12747 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
12748 // `ALTREF_FRAME`, which reads the frame two back when there is one;
12749 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
12750 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
12751 header.order_hints = order_hints;
12752 // lane-last2: `inter_frame_headers_slots` points every un-named
12753 // reference at `last_slot`; the pyramid's leaf chain retains a second,
12754 // older picture and names it here. The caller's `sign_bias` /
12755 // `order_hints` entry 1 is derived from this same slot, so the stack
12756 // scans and `skipModeAllowed` read what the decoder will.
12757 if let Some(slot) = pyramid.and_then(|p| p.last2_slot) {
12758 header.ref_frame_idx[1] = slot;
12759 }
12760 header.reference_select = reference_select();
12761 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
12762 // per-reference order-hint distance is read by the block SEARCH, which
12763 // runs long before the writer arms these (the distance-scaled search step
12764 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
12765 // never reached the tool).
12766 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
12767 // lane-hpmv: armed here for the same reason the order hints are -- the
12768 // block SEARCH reads it (its eighth-pel stage) long before the writer.
12769 let hp_mv = header.allow_high_precision_mv;
12770 crate::tile::arm_high_precision_mv(hp_mv);
12771 if let Some(p) = pyramid {
12772 header.show_frame = p.show_frame;
12773 header.showable_frame = !p.show_frame;
12774 header.ref_frame_sign_bias = p.sign_bias;
12775 }
12776 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
12777 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
12778 // block inside this frame codes and searches its own `tx_depth`, the same
12779 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
12780 let tx_select = tx_select() && tx_select_inter();
12781 if tx_select {
12782 header.tx_mode = TxMode::Select;
12783 }
12784
12785 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
12786 // lane-palw: the encoder's own in-process reconstruct reads its palette
12787 // colour-index maps back through `decode::palette_onscreen`, which takes
12788 // the frame's mi dims off the `FrameCtx` -- a real decode gets them from
12789 // `set_segmentation`, which never runs on `FrameCtx::for_encoder`. Publish
12790 // them here so the reconstruct clamps a block cut by the frame edge
12791 // exactly as the writer now does.
12792 let frame_mi_dims = (header.mi_rows as usize, header.mi_cols as usize);
12793 fctx.seg_mi_dims.set(frame_mi_dims);
12794 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
12795 // here (see `encode_key_frame_inner`).
12796 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
12797 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
12798 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
12799 // This frame's own `allow_screen_content_tools`. It can only be set when
12800 // the SEQUENCE offers the bit at all, which is the key frame's decision
12801 // ([`SEQ_SCREEN`]): a frame header that contradicts
12802 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
12803 // encode.
12804 let screen = seq_screen()
12805 && screen_content(&picture_y8, picture.width, true_width, true_height);
12806 header.allow_screen_content_tools = screen;
12807 // lane-txi, as on the key frame: the header bit the writer's own
12808 // `Cdfs` then reads for every luma `tx_type` symbol.
12809 header.reduced_tx_set = !wide_tx_set(screen);
12810 // lane-intertx, desync (a): the frame context this value is read back
12811 // through ([`decode::reduce_inherited_chroma_tx_type`] inside
12812 // `recode_inter_chroma`, and every inter decode helper the search's own
12813 // trial decode shares) must carry THIS frame's bit, not whatever the
12814 // previous frame's trial decode last left in the shared cell -- a stale
12815 // `true` here narrows the chroma allowance the search reconstructs
12816 // against under the one the header's bit actually allows.
12817 fctx.reduced_tx_set_inter.set(header.reduced_tx_set);
12818 // The search prices coefficients against the tables this frame's writer
12819 // starts from, not against the defaults (lane-av1txbits) -- but only on a
12820 // frame the screen detector said no to (lane-av1price2): armed HERE, after
12821 // `screen` exists, and again on every search/tile worker below.
12822 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
12823 let mut luma = Plane {
12824 source: &picture_y8,
12825 reconstruction: vec![128; picture_y8.len()],
12826 width: picture.width,
12827 height: picture.height,
12828 true_width,
12829 true_height,
12830 tile_x0: 0,
12831 tile_y0: 0,
12832 tile_x1: picture.width,
12833 tile_y1: picture.height,
12834 ctx: CoefCtxMap::default(),
12835 };
12836 let mut chroma = [
12837 Plane {
12838 source: &picture_u8,
12839 reconstruction: vec![128; picture_u8.len()],
12840 width: picture.width / 2,
12841 height: picture.height / 2,
12842 true_width: true_width / 2,
12843 true_height: true_height / 2,
12844 tile_x0: 0,
12845 tile_y0: 0,
12846 tile_x1: picture.width / 2,
12847 tile_y1: picture.height / 2,
12848 ctx: CoefCtxMap::default(),
12849 },
12850 Plane {
12851 source: &picture_v8,
12852 reconstruction: vec![128; picture_v8.len()],
12853 width: picture.width / 2,
12854 height: picture.height / 2,
12855 true_width: true_width / 2,
12856 true_height: true_height / 2,
12857 tile_x0: 0,
12858 tile_y0: 0,
12859 tile_x1: picture.width / 2,
12860 tile_y1: picture.height / 2,
12861 ctx: CoefCtxMap::default(),
12862 },
12863 ];
12864
12865 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
12866 let search = Search {
12867 base_q_idx,
12868 deadzone,
12869 lambda: lambda_scale()
12870 * match pyramid {
12871 Some(p) if !p.show_frame => hidden_lambda_factor(),
12872 _ => 1.0,
12873 }
12874 * step
12875 * step,
12876 modes: &KEY_FRAME_MODES,
12877 top_k: prune_top_k_inter(),
12878 screen,
12879 };
12880 let mode_bits_table = inter_mode_bits();
12881 // lane-av1tpl: one lambda factor per 64x64 superblock, from how much of
12882 // this frame the NEXT one predicts from. Off (`None`) without a
12883 // lookahead picture or at strength 0.
12884 let tpl_k = tpl_strength();
12885 let window: Vec<&Picture> = lookahead
12886 .iter()
12887 .take_while(|n| n.width == picture.width && n.height == picture.height)
12888 .collect();
12889 let tpl_sources: Vec<Vec<u8>> =
12890 window.iter().map(|n| n.y.iter().map(|&v| v as u8).collect()).collect();
12891 let tpl_cells_x = picture.width / 16;
12892 // `.1` is the propagating map's raw per-cell dependence ratio, which only
12893 // [`deltaq_libaom`] reads; the one-frame area map has no such ratio.
12894 let tpl_both: Option<(Vec<f64>, Option<Vec<f64>>)> =
12895 (tpl_k > 0.0 && !tpl_sources.is_empty()).then(|| {
12896 if tpl_propagating() {
12897 let mut frames: Vec<&[u8]> = vec![&picture_y8];
12898 frames.extend(tpl_sources.iter().map(Vec::as_slice));
12899 let (f, r) = tpl_lambda_factors(&frames, picture.width, picture.height, tpl_k);
12900 (f, Some(r))
12901 } else {
12902 // The shipped map is one factor per 64x64; it is spread over that
12903 // superblock's own 16 cells so the application site below (which
12904 // averages the four cells of a 32x32 block) reads exactly the
12905 // superblock factor, whichever map fed it.
12906 let map =
12907 tpl_area_map(&picture_y8, &tpl_sources[0], picture.width, picture.height);
12908 let cells_y = picture.height / 16;
12909 let sb = tpl_sb_factors(&map, tpl_cells_x, cells_y, tpl_k);
12910 let f: Vec<f64> = (0..tpl_cells_x * cells_y)
12911 .map(|c| sb[(c / tpl_cells_x / 4) * (tpl_cells_x / 4) + (c % tpl_cells_x) / 4])
12912 .collect();
12913 (f, None)
12914 }
12915 });
12916 let (tpl_factors, tpl_ratio) = match tpl_both {
12917 Some((f, r)) => (Some(f), r),
12918 None => (None, None),
12919 };
12920
12921 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
12922 // coding surface's: `blocks` carries one entry per 32x32 block the tile
12923 // writer will actually visit, same count it checks `blocks.len()`
12924 // against, which is fewer than the padded surface's own block count
12925 // whenever the true size is not a 64x64 multiple.
12926 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
12927 let (cols, rows) = (cols as usize, rows as usize);
12928 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
12929 // lane-deltaq: one absolute qindex per 64x64 superblock, from the same
12930 // tpl map the lambda factor comes from ([`deltaq_for_factor`]). Present
12931 // only when the map is, and `delta_q_res` follows straight into the frame
12932 // header (`write_delta_q_params`) and into the tile writer's own plan.
12933 // Not on a screen frame ([`b64_residual`]'s content gate): lane-dq3
12934 // measured the per-superblock quantizer as a win on both films and a
12935 // 0.5 loss vs libaom on the desktop capture, so a frame that set
12936 // `allow_screen_content_tools` codes no delta syntax at all and stays
12937 // byte-identical to the pre-lane encoder.
12938 // lane-arfq: the level whose `delta_q` strength this frame reads; the
12939 // flat path (no pyramid) is a leaf.
12940 let dq_level = pyramid.map_or(DqLevel::Leaf, |p| p.dq_level);
12941 let deltaq_res: Option<i32> = tpl_factors
12942 .as_ref()
12943 .filter(|_| !screen)
12944 .and(deltaq_res_log2().map(|r| 1i32 << r));
12945 // The same 16-cell mean the superblock's own lambda takes, clamped to the
12946 // map the frame actually has -- read over the factors or over the raw
12947 // dependence ratios, whichever mapping is asking.
12948 let sb_mean = |m: &[f64], sb: usize| {
12949 let (sb_r, sb_c) = (sb / sb_cols, sb % sb_cols);
12950 (0..16)
12951 .map(|i| {
12952 let (cy, cx) = (sb_r * 4 + i / 4, sb_c * 4 + i % 4);
12953 m[(cy.min(m.len() / tpl_cells_x - 1)) * tpl_cells_x + cx.min(tpl_cells_x - 1)]
12954 })
12955 .sum::<f64>()
12956 / 16.0
12957 };
12958 // lane-dq: `EC_AV1_DQ_TPL=1` takes libaom's own objective mapping off the
12959 // raw dependence ratio; without it (and always without a ratio map, i.e.
12960 // on the one-frame area map) the shipped derivation stands.
12961 let r_frame = tpl_ratio.as_deref().map(tpl_frame_ratio);
12962 let sb_qindex = |f: &[f64], res: i32, sb: usize, libaom: Option<f64>| -> u8 {
12963 match (libaom, tpl_ratio.as_deref(), r_frame) {
12964 (Some(k), Some(r), Some(rf)) => deltaq_libaom(base_q_idx, sb_mean(r, sb), rf, k, res),
12965 _ => deltaq_for_factor(base_q_idx, sb_mean(f, sb), deltaq_k(), deltaq_clamp(), res),
12966 }
12967 };
12968 let sb_q: Option<Vec<u8>> = match (&tpl_factors, deltaq_res) {
12969 (Some(f), Some(res)) => {
12970 let libaom = dq_tpl_strength(dq_level);
12971 let mut g: Vec<u8> =
12972 (0..sb_cols * _sb_rows).map(|sb| sb_qindex(f, res, sb, libaom)).collect();
12973 // lane-b128m: under 128 superblocks the delta_q syntax is coded
12974 // ONCE per 128 root (the reader's own unit), so all four 64x64
12975 // cells of a root have to be searched -- and quantized -- at the
12976 // one qindex the root's top-left cell codes.
12977 if sb128_on() {
12978 for sb_r in 0.._sb_rows {
12979 for sb_c in 0..sb_cols {
12980 let q = g[(sb_r & !1) * sb_cols + (sb_c & !1)];
12981 g[sb_r * sb_cols + sb_c] = q;
12982 }
12983 }
12984 }
12985 Some(g)
12986 }
12987 _ => None,
12988 };
12989 // lane-dq census: both mappings on the SAME superblocks, whether or not
12990 // the frame codes any delta syntax (`deltaq_res` is `None` with the lever
12991 // off, and the census then prices the default `res = 4` grid).
12992 if dq_census() {
12993 if let Some(f) = &tpl_factors {
12994 let res = deltaq_res.unwrap_or(4);
12995 let off = |libaom: Option<f64>| -> Vec<i32> {
12996 (0..sb_cols * _sb_rows)
12997 .map(|sb| i32::from(sb_qindex(f, res, sb, libaom)) - i32::from(base_q_idx))
12998 .collect()
12999 };
13000 let strength = dq_tpl_strength(dq_level);
13001 let (ours, aom) = (off(None), off(Some(strength.unwrap_or(1.0))));
13002 let coded = match (deltaq_res.is_some(), strength) {
13003 (false, _) => "none".to_string(),
13004 (true, None) => "ours".to_string(),
13005 (true, Some(k)) => format!("libaom k={k}"),
13006 };
13007 eprintln!(
13008 "dq census: level={dq_level:?} base={base_q_idx} res={res} sbs={} coded={coded} r_frame={:.4}\n ours {}\n libaom {}",
13009 sb_cols * _sb_rows,
13010 r_frame.unwrap_or(f64::NAN),
13011 dq_summary(&ours),
13012 dq_summary(&aom),
13013 );
13014 }
13015 }
13016 if let Some(res) = deltaq_res.filter(|_| sb_q.is_some()) {
13017 header.delta.q_present = true;
13018 header.delta.q_res = res.trailing_zeros() as u8;
13019 }
13020 // lane-rectdq: what the tile writer's own `arm_delta_q` is armed with
13021 // below, so the root search prices the group the writer really codes.
13022 let dq_res: i32 = deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0);
13023 if let Some(g) = &sb_q {
13024 let mut levels: Vec<u8> = g.clone();
13025 levels.sort_unstable();
13026 levels.dedup();
13027 DELTAQ_LEVELS.fetch_max(levels.len(), std::sync::atomic::Ordering::Relaxed);
13028 }
13029 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
13030 // This frame's tile grid, as in `encode_key_frame_inner`.
13031 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
13032 let layout =
13033 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
13034 header.tile_info = tile_info_of(&layout, 1);
13035 let header_tile_info = header.tile_info.clone();
13036 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
13037 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
13038 // once per frame (lane-av1rd2), not once per block, which is a whole
13039 // plane's map per 32x32 block and now per leaf too.
13040 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
13041 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
13042 // availability -- intra edges and the MV stack's scans alike -- already
13043 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
13044 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
13045 // giving each job its own planes and its own `MiGrid` therefore leaves
13046 // every decision, and so every coded bit, exactly where the whole-frame
13047 // loop left it, at any tile count and any thread count.
13048 let (frame_width, frame_height) = (picture.width, picture.height);
13049 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
13050 let [cb, cr] = &mut chroma;
13051 let chroma_out = [
13052 crate::par::Shared::new(&mut cb.reconstruction),
13053 crate::par::Shared::new(&mut cr.reconstruction),
13054 ];
13055 let search_tile = |index: usize,
13056 fctx: &crate::decode::FrameCtx|
13057 -> Result<Vec<(usize, Quadrant)>> {
13058 // Thread-local, and this job may be running on a `search_tiles`
13059 // worker: `ref_distance`'s order-hint distance (the scaled motion
13060 // search step) is read by the SEARCH, so every worker arms it or the
13061 // tile's bits depend on the thread count.
13062 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
13063 crate::tile::arm_high_precision_mv(hp_mv);
13064 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
13065 let rect = layout.rect(index);
13066 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
13067 let mut chroma = [
13068 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
13069 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
13070 ];
13071 clip_planes_to_tile(&mut luma, &mut chroma, rect);
13072 let mut grid = MiGrid::new(mi_cols, mi_rows);
13073 grid.set_sign_bias(sign_bias);
13074 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
13075 // built once per tile job (`obmc_prediction`).
13076 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
13077 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
13078 obmc_refs[crate::mvstack::LAST2_FRAME as usize] = last2;
13079 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
13080 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
13081 grid.set_tile_bounds(
13082 rect.mi_row0 as usize,
13083 rect.mi_col0 as usize,
13084 rect.mi_row1 as usize,
13085 rect.mi_col1 as usize,
13086 );
13087 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
13088 // lane-b128: under a 128x128 superblock the search walks the roots the
13089 // WRITER walks (`tile::sb_write_order`: TL, TR, BL, BR inside each root),
13090 // not plain raster -- a search that visits BL before TR builds every mv
13091 // stack and neighbour context off blocks the writer has not coded yet,
13092 // which is what made the write-time drl clamp fire at all (lane-sb128b).
13093 // At a 64 superblock the two orders are identical and this is the same
13094 // raster loop as before.
13095 let sb128_search = sb128_on();
13096 let root_step = if sb128_search { 2 } else { 1 };
13097 let mut roots: Vec<(usize, usize)> = Vec::new();
13098 {
13099 let (r0, r1) = (rect.sb_row0 as usize, rect.sb_row1 as usize);
13100 let (c0, c1) = (rect.sb_col0 as usize, rect.sb_col1 as usize);
13101 let mut r = r0;
13102 while r < r1 {
13103 let mut c = c0;
13104 while c < c1 {
13105 roots.push((r, c));
13106 c += root_step;
13107 }
13108 r += root_step;
13109 }
13110 }
13111 for (root_r, root_c) in roots {
13112 // The 64x64 cells of this root, in the writer's own order.
13113 let cells: Vec<(usize, usize)> = if sb128_search {
13114 [(0, 0), (0, 1), (1, 0), (1, 1)]
13115 .into_iter()
13116 .map(|(dr, dc)| (root_r + dr, root_c + dc))
13117 .filter(|&(r, c)| r < rect.sb_row1 as usize && c < rect.sb_col1 as usize)
13118 .collect()
13119 } else {
13120 vec![(root_r, root_c)]
13121 };
13122 // What the four cells below really cost, against which the whole
13123 // 128x128 candidate is weighed.
13124 let mark128 = blocks.len();
13125 let mut root_cost = 0.0f64;
13126 // The 128 root's own compound pairs, at its 32x32-mi window (the 64
13127 // root builds the same list one size down, per superblock).
13128 let root_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13129 if header.reference_select && b128_compound() && !screen && sb128_search {
13130 [
13131 (crate::mvstack::GOLDEN_FRAME, golden),
13132 (crate::mvstack::ALTREF_FRAME, altref),
13133 ]
13134 .into_iter()
13135 .filter_map(|(r, pic)| {
13136 pic.map(|p| {
13137 (
13138 r,
13139 p,
13140 crate::mvstack::find_mv_stack_compound(
13141 &grid,
13142 root_r * 16,
13143 root_c * 16,
13144 32,
13145 32,
13146 (crate::mvstack::LAST_FRAME, r),
13147 mi_cols,
13148 mi_rows,
13149 grid.sign_bias_table(),
13150 &[(0, 0); 7],
13151 None,
13152 ),
13153 )
13154 })
13155 })
13156 .collect()
13157 } else {
13158 Vec::new()
13159 };
13160 let root128 = (sb128_search && b128_root() && cells.len() == 4)
13161 .then(|| search_root_128(
13162 &mut luma,
13163 &mut chroma,
13164 &grid,
13165 (root_r, root_c),
13166 (rows, cols),
13167 (header.mi_cols, header.mi_rows),
13168 search,
13169 &tpl_factors,
13170 sb_q.as_ref(),
13171 sb_cols,
13172 tpl_cells_x,
13173 base_q_idx,
13174 dq_res,
13175 reference,
13176 &root_compound,
13177 fctx,
13178 ))
13179 .flatten();
13180 // lane-b128hv: the same root as two 128x64 / 64x128 halves. Both cuts
13181 // are priced; the cheaper one competes with the NONE block and with
13182 // the four superblocks below.
13183 let forced_rect = FORCE_B128_RECT.load(std::sync::atomic::Ordering::Relaxed);
13184 let root_rect = (sb128_search && b128_rect() && cells.len() == 4)
13185 .then(|| {
13186 let mut best: Option<(bool, _)> = None;
13187 for horz in [true, false] {
13188 if forced_rect != 0 && forced_rect != u8::from(horz) + u8::from(!horz) * 2 {
13189 continue;
13190 }
13191 let Some(found) = search_root_128_rect(
13192 &mut luma,
13193 &mut chroma,
13194 &mut grid,
13195 (root_r, root_c),
13196 (rows, cols),
13197 (header.mi_cols, header.mi_rows),
13198 search,
13199 &tpl_factors,
13200 sb_q.as_ref(),
13201 sb_cols,
13202 tpl_cells_x,
13203 base_q_idx,
13204 dq_res,
13205 reference,
13206 &root_compound,
13207 horz,
13208 fctx,
13209 ) else {
13210 continue;
13211 };
13212 if best.as_ref().is_none_or(|b: &(bool, (f64, f64, _, _))| found.0 < b.1.0) {
13213 best = Some((horz, found));
13214 }
13215 }
13216 best
13217 })
13218 .flatten();
13219 // lane-ab128: and the same root as one of the four AB shapes -- two
13220 // 64x64 pieces plus one 128x64 / 64x128 half. All four are priced;
13221 // the cheapest joins the candidate list below.
13222 let forced_ab = FORCE_B128_AB.load(std::sync::atomic::Ordering::Relaxed);
13223 let root_ab = (sb128_search
13224 && (b128_ab() || forced_ab != 0)
13225 && cells.len() == 4
13226 && forced_rect == 0)
13227 .then(|| {
13228 let mut best: Option<(usize, _)> = None;
13229 for symbol in 4..=7usize {
13230 if forced_ab != 0 && usize::from(forced_ab) != symbol {
13231 continue;
13232 }
13233 let Some(found) = search_root_128_ab(
13234 &mut luma,
13235 &mut chroma,
13236 &mut grid,
13237 (root_r, root_c),
13238 (rows, cols),
13239 (header.mi_cols, header.mi_rows),
13240 search,
13241 &tpl_factors,
13242 sb_q.as_ref(),
13243 sb_cols,
13244 tpl_cells_x,
13245 base_q_idx,
13246 reference,
13247 &root_compound,
13248 symbol,
13249 fctx,
13250 ) else {
13251 continue;
13252 };
13253 if best.as_ref().is_none_or(|b: &(usize, (f64, f64, _, _))| found.0 < b.1.0) {
13254 best = Some((symbol, found));
13255 }
13256 }
13257 best
13258 })
13259 .flatten();
13260 for (sb_r, sb_c) in cells {
13261 // lane-b64: the whole superblock as ONE 64x64 block, tried before
13262 // its quadrants are (`search_skip_64`) and compared against the
13263 // four of them below. Only a superblock wholly inside the true
13264 // frame is offered it, and (lane-b64b, `EC_AV1_B64EDGE`) one the
13265 // edge CUTS THROUGH: the spec's own `has_cols`/`has_rows` ask
13266 // only that the block's half is inside, and the trial is ranked
13267 // over the inside part alone ([`Plane::block_sse`]).
13268 let (x64, y64) = (sb_c * SUPERBLOCK, sb_r * SUPERBLOCK);
13269 let whole_inside = (sb_c as u32 + 1) * crate::tile::SB_MI <= header.mi_cols
13270 && (sb_r as u32 + 1) * crate::tile::SB_MI <= header.mi_rows
13271 && x64 + SUPERBLOCK <= luma.true_width
13272 && y64 + SUPERBLOCK <= luma.true_height;
13273 let edge_inside = b64_edge()
13274 && crate::tile::has_half(
13275 sb_c as u32 * crate::tile::SB_MI,
13276 crate::tile::SB_MI,
13277 header.mi_cols,
13278 )
13279 && crate::tile::has_half(
13280 sb_r as u32 * crate::tile::SB_MI,
13281 crate::tile::SB_MI,
13282 header.mi_rows,
13283 );
13284 let sb64_legal = b64_root()
13285 && sb_r * 2 + 1 < rows
13286 && sb_c * 2 + 1 < cols
13287 && (whole_inside || edge_inside);
13288 // One lambda for the whole superblock, the same mean the 32x32
13289 // level takes over its own four tpl cells: the 64-vs-four-32
13290 // comparison below weighs one cost against four, so both sides
13291 // have to be priced at the same lambda.
13292 let sb_search = match &tpl_factors {
13293 // lane-deltaq: with a per-superblock quantizer the lambda
13294 // comes from that quantizer, not from the raw map factor --
13295 // the two agree exactly at `EC_AV1_DELTAQ_K=1` unclamped.
13296 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),
13297 Some(f) if sb64_legal => {
13298 let mean = (0..16)
13299 .map(|i| f[(sb_r * 4 + i / 4) * tpl_cells_x + sb_c * 4 + i % 4])
13300 .sum::<f64>()
13301 / 16.0;
13302 Search { lambda: search.lambda * mean, ..search }
13303 }
13304 _ => search,
13305 };
13306 let mark = blocks.len();
13307 let mut sb64: Option<(f64, BlockCoeffs, [(Vec<u8>, Vec<CoefCtx>); 3])> = None;
13308 let mut sb_cost = 0.0f64;
13309 if sb64_legal {
13310 let base = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
13311 let (mi_row, mi_col) = (sb_r * 16, sb_c * 16);
13312 let stack =
13313 find_mv_stack(&grid, mi_row, mi_col, 16, 16, LAST_FRAME, mi_cols, mi_rows);
13314 // lane-b64b: the `LAST` + extra-reference pairs at this
13315 // superblock's own 16x16-mi window, the same stacks the tile
13316 // writer's `Whole64` arm rebuilds. Empty unless the frame
13317 // codes `reference_select`, which is what gates the syntax.
13318 // `!screen` for the same reason the residual arm is gated
13319 // there ([`b64_residual`]): a desktop capture's superblocks
13320 // are flat runs the skip arm already codes for nothing, and
13321 // MEASURED, compound at the root cost it +33.4/-23.8 ->
13322 // +33.7/-23.6 while both film rows gained (step 1's table).
13323 let sb_compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13324 if header.reference_select && b64_compound() && !screen {
13325 [
13326 (crate::mvstack::GOLDEN_FRAME, golden),
13327 (crate::mvstack::ALTREF_FRAME, altref),
13328 ]
13329 .into_iter()
13330 .filter_map(|(r, pic)| {
13331 pic.map(|p| {
13332 (
13333 r,
13334 p,
13335 crate::mvstack::find_mv_stack_compound(
13336 &grid,
13337 mi_row,
13338 mi_col,
13339 16,
13340 16,
13341 (crate::mvstack::LAST_FRAME, r),
13342 mi_cols,
13343 mi_rows,
13344 grid.sign_bias_table(),
13345 &[(0, 0); 7],
13346 None,
13347 ),
13348 )
13349 })
13350 })
13351 .collect()
13352 } else {
13353 Vec::new()
13354 };
13355 if let Some((cost, block)) = search_skip_64(
13356 &mut luma,
13357 &mut chroma,
13358 (x64, y64),
13359 (SUPERBLOCK, SUPERBLOCK),
13360 &sb_search,
13361 b64_residual() && !screen,
13362 reference,
13363 &stack,
13364 &sb_compound,
13365 fctx,
13366 ) {
13367 let after = snapshot(&luma, &chroma, (x64, y64), SUPERBLOCK);
13368 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &base);
13369 let cost = cost
13370 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, false);
13371 sb64 = Some((cost, block, after));
13372 }
13373 }
13374 // A superblock whose 64x64 trial already codes almost nothing per
13375 // pixel is taken outright and its quadrants are never searched --
13376 // the same `split_rd_breakout` shape the 32x32 level uses one
13377 // size up, and where this lever BUYS wall instead of spending it.
13378 let early64 = sb64.as_ref().is_some_and(|(c, _, _)| {
13379 split_rd_breakout_at(
13380 b64_breakout_threshold(),
13381 *c,
13382 SUPERBLOCK,
13383 sb_search.lambda,
13384 )
13385 });
13386 for quadrant in 0..if early64 { 0 } else { 4 } {
13387 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
13388 // lane-av1tpl2: this 32x32 block's own lambda -- every RD
13389 // decision under it (partition, mode, tx, motion) reads
13390 // `search.lambda`, so scaling the one field here scales all
13391 // of them. 32x32 and not the 16x16 the map is built at
13392 // because the whole-vs-split comparison right below weighs
13393 // one 32x32 cost against four 16x16 ones: a per-leaf lambda
13394 // would make those two numbers incomparable.
13395 let search = match &tpl_factors {
13396 // lane-deltaq: the quantizer is a SUPERBLOCK-level
13397 // symbol, so all four quadrants take their superblock's
13398 // own qindex and the lambda it implies. No granularity is
13399 // lost: the shipped map (`EC_AV1_TPL_SB`) is already one
13400 // factor per superblock, shared by its sixteen cells.
13401 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),
13402 Some(f) => {
13403 let mean = (0..4)
13404 .map(|i| f[(r32 * 2 + i / 2) * tpl_cells_x + c32 * 2 + i % 2])
13405 .sum::<f64>()
13406 / 4.0;
13407 Search { lambda: search.lambda * mean, ..search }
13408 }
13409 None => search,
13410 };
13411 // Same filter as the tile writer's: a quadrant whose own mi
13412 // origin is not inside the true frame is never coded.
13413 if r32 >= rows || c32 >= cols {
13414 continue;
13415 }
13416 // spec `decode_partition`'s hasRows/hasCols recomputed at this
13417 // 32x32 block's own half (`crate::tile::has_half`), same as
13418 // the key frame search: the true frame edge can fall inside a
13419 // quadrant a superblock-level check already let through, and
13420 // such a quadrant cannot be left whole -- it must split into
13421 // the 16x16 leaves that are actually inside the true frame
13422 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
13423 // arm).
13424 let (has_cols32, has_rows32) = (
13425 crate::tile::has_half(
13426 c32 as u32 * crate::tile::BLOCK_MI,
13427 crate::tile::BLOCK_MI,
13428 header.mi_cols,
13429 ),
13430 crate::tile::has_half(
13431 r32 as u32 * crate::tile::BLOCK_MI,
13432 crate::tile::BLOCK_MI,
13433 header.mi_rows,
13434 ),
13435 );
13436 if has_cols32 && has_rows32 {
13437 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
13438 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
13439 let stack =
13440 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
13441 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
13442 (crate::mvstack::LAST2_FRAME, last2),
13443 (crate::mvstack::GOLDEN_FRAME, golden),
13444 (crate::mvstack::ALTREF_FRAME, altref),
13445 ]
13446 .into_iter()
13447 .filter_map(|(r, pic)| {
13448 pic.map(|p| {
13449 (
13450 r,
13451 p,
13452 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
13453 )
13454 })
13455 })
13456 .collect();
13457 let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
13458 .iter()
13459 .map(|(r, p, st)| (*r, *p, st))
13460 .collect();
13461 // The COMPOUND stack of each `LAST` + extra pair, off the
13462 // same grid (and the same armed sign bias) the tile writer
13463 // rebuilds it from. Empty unless this frame codes
13464 // `reference_select`, which is what gates the syntax.
13465 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13466 if header.reference_select {
13467 extra_stacks
13468 .iter()
13469 .map(|&(r, p, _)| {
13470 (
13471 r,
13472 p,
13473 crate::mvstack::find_mv_stack_compound(
13474 &grid,
13475 mi_row,
13476 mi_col,
13477 8,
13478 8,
13479 (crate::mvstack::LAST_FRAME, r),
13480 mi_cols,
13481 mi_rows,
13482 grid.sign_bias_table(),
13483 &[(0, 0); 7],
13484 None,
13485 ),
13486 )
13487 })
13488 .collect()
13489 } else {
13490 Vec::new()
13491 };
13492
13493 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
13494 let (block, mut cost_whole) = search_inter_block(
13495 &mut luma,
13496 &mut chroma,
13497 (x, y),
13498 &search,
13499 &mode_bits_table,
13500 reference,
13501 &stack,
13502 &extra,
13503 &compound,
13504 &grid,
13505 (mi_row, mi_col),
13506 (mi_rows, mi_cols),
13507 fctx,
13508 );
13509 cost_whole += search.lambda * partition_bits(BLOCK, false);
13510 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
13511
13512 // What four 16x16 leaves cost instead (spec
13513 // PARTITION_SPLIT at BLOCK_32X32, which
13514 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
13515 // already writes for a straddling quadrant). Each leaf is
13516 // searched against the reconstruction -- and the `mi`
13517 // grid -- the ones before it left, exactly as the writer
13518 // and the decoder will read them.
13519 //
13520 // A block the whole-32 search left skipped (no residual
13521 // at all) is not offered the split: libaom prunes the
13522 // same way at cpu-used 6, and it is where the wall would
13523 // otherwise go on static content.
13524 let leaf_positions: Vec<(usize, usize)> = (0..4)
13525 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
13526 .collect();
13527 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
13528 crate::tile::has_half(
13529 sc as u32 * crate::tile::SUB_MI,
13530 crate::tile::SUB_MI,
13531 header.mi_cols,
13532 ) && crate::tile::has_half(
13533 sr as u32 * crate::tile::SUB_MI,
13534 crate::tile::SUB_MI,
13535 header.mi_rows,
13536 )
13537 });
13538 // The breakout above: a 32x32 block that codes almost
13539 // nothing is not offered the split at all.
13540 let breakout = split_breakout_coeffs();
13541 let split = (!block.skip
13542 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
13543 && (breakout == 0 || block.luma.len() > 4 * breakout)
13544 && leaves_legal
13545 && split_inter_blocks())
13546 .then(|| {
13547 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
13548 let mut cost = search.lambda * partition_bits(BLOCK, true);
13549 let mut leaves = Vec::with_capacity(4);
13550 for &(sr, sc) in &leaf_positions {
13551 let (mi_row, mi_col) = (sr * 4, sc * 4);
13552 let (lx, ly) = (sc * SUB, sr * SUB);
13553 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
13554 let stack = find_mv_stack(
13555 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
13556 );
13557 let cstacks = leaf_compound_stacks(
13558 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
13559 header.reference_select, golden, altref,
13560 );
13561 let (leaf, leaf_cost) = code_square_inter(
13562 &mut luma,
13563 &mut chroma,
13564 (lx, ly),
13565 SUB,
13566 &search,
13567 &mode_bits_table,
13568 reference,
13569 &stack,
13570 &cstacks,
13571 &grid,
13572 (mi_row, mi_col),
13573 (mi_rows, mi_cols),
13574 &obmc_refs,
13575 fctx,
13576 );
13577 let leaf_cost = leaf_cost
13578 + search.lambda * partition_bits(SUB, false);
13579 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
13580
13581 // And what four 8x8 leaves cost instead --
13582 // the same tree one step further down, which
13583 // the writer codes as a real PARTITION_SPLIT
13584 // at BLOCK_16X16 (lane-av1rd2). Same
13585 // skipped-block prune as the level above.
13586 let eight = (!leaf.skip
13587 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
13588 && (breakout == 0 || leaf.luma.len() > breakout)
13589 && split_inter_8())
13590 .then(|| {
13591 restore(
13592 &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base,
13593 );
13594 let mut cost8 = search.lambda
13595 * (partition_bits(SUB, true)
13596 + 4.0 * partition_bits(8, false));
13597 let mut eight = Vec::with_capacity(4);
13598 for i in 0..4 {
13599 let (mr, mc) =
13600 (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
13601 let stack8 = find_mv_stack(
13602 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
13603 );
13604 let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
13605 if header.reference_select && leaf_compound() {
13606 [
13607 (crate::mvstack::GOLDEN_FRAME, golden),
13608 (crate::mvstack::ALTREF_FRAME, altref),
13609 ]
13610 .into_iter()
13611 .filter_map(|(r, pic)| {
13612 pic.map(|p| {
13613 (
13614 r,
13615 p,
13616 crate::mvstack::find_mv_stack_compound(
13617 &grid, mr, mc, 2, 2,
13618 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
13619 grid.sign_bias_table(), &[(0, 0); 7], None,
13620 ),
13621 )
13622 })
13623 })
13624 .collect()
13625 } else {
13626 Vec::new()
13627 };
13628 let (leaf8, cost) = code_square_inter(
13629 &mut luma,
13630 &mut chroma,
13631 (lx + (i % 2) * 8, ly + (i / 2) * 8),
13632 8,
13633 &search,
13634 &mode_bits_table,
13635 reference,
13636 &stack8,
13637 &cstacks8,
13638 &grid,
13639 (mr, mc),
13640 (mi_rows, mi_cols),
13641 &obmc_refs,
13642 fctx,
13643 );
13644 cost8 += cost;
13645 record_mi(&mut grid, mr, mc, 2, leaf8.inter, leaf8.skip);
13646 eight.push(leaf8);
13647 }
13648 (eight, cost8)
13649 });
13650 match eight {
13651 Some((eight, cost8)) if cost8 < leaf_cost => {
13652 partition_hit(3);
13653 cost += cost8;
13654 leaves.push(BlockCoeffs {
13655 eight: Some(eight),
13656 ..BlockCoeffs::default()
13657 });
13658 continue;
13659 }
13660 Some(_) => restore(
13661 &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf,
13662 ),
13663 None => {}
13664 }
13665 partition_hit(2);
13666 cost += leaf_cost;
13667 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter, leaf.skip);
13668 leaves.push(leaf);
13669 }
13670 (leaves, cost)
13671 });
13672 if let Some((leaves, cost)) = split {
13673 if cost < cost_whole {
13674 // The leaves' own `mi` cells are already in the
13675 // grid, and their reconstruction is what the
13676 // planes hold.
13677 partition_hit(1);
13678 sb_cost += cost;
13679 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
13680 continue;
13681 }
13682 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
13683 }
13684 partition_hit(0);
13685 sb_cost += cost_whole;
13686 record_mi(&mut grid, mi_row, mi_col, 8, block.inter, block.skip);
13687 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
13688 } else {
13689 // The sub-positions actually inside the true frame, same
13690 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
13691 let sub_positions: Vec<(usize, usize)> = (0..4)
13692 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
13693 .filter(|&(sr, sc)| {
13694 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
13695 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
13696 })
13697 .collect();
13698 // Each leaf searches intra against its own `NEARESTMV`
13699 // candidate (`code_square_inter`), same real-inter choice
13700 // `search_inter_block` makes for a whole 32x32 block, at
13701 // this leaf's own 4x4-mi mv-stack window -- unless the
13702 // leaf's own half itself straddles the true edge, which
13703 // it codes as two (or one, at a true corner) 8x8 leaves
13704 // (`crate::tile::write_leaf8`'s inter counterpart),
13705 // mirroring the key frame search's straddling-16x16
13706 // handling above (lane-av1inter8).
13707 let mut leaves = Vec::with_capacity(sub_positions.len());
13708 for (sr, sc) in sub_positions {
13709 let (has_cols16, has_rows16) = (
13710 crate::tile::has_half(
13711 sc as u32 * crate::tile::SUB_MI,
13712 crate::tile::SUB_MI,
13713 header.mi_cols,
13714 ),
13715 crate::tile::has_half(
13716 sr as u32 * crate::tile::SUB_MI,
13717 crate::tile::SUB_MI,
13718 header.mi_rows,
13719 ),
13720 );
13721 if has_cols16 && has_rows16 {
13722 let (x, y) = (sc * SUB, sr * SUB);
13723 let (mi_row, mi_col) = (sr * 4, sc * 4);
13724 let stack = find_mv_stack(
13725 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
13726 );
13727 let cstacks = leaf_compound_stacks(
13728 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
13729 header.reference_select, golden, altref,
13730 );
13731 let (block, _) = code_square_inter(
13732 &mut luma,
13733 &mut chroma,
13734 (x, y),
13735 SUB,
13736 &search,
13737 &mode_bits_table,
13738 reference,
13739 &stack,
13740 &cstacks,
13741 &grid,
13742 (mi_row, mi_col),
13743 (mi_rows, mi_cols),
13744 &obmc_refs,
13745 fctx,
13746 );
13747 // One publication point for every coded leaf
13748 // (`record_mi`): this site used to spell the vote
13749 // out with `ref_frame` pinned to LAST and `mv1`
13750 // to (0,0), which is the encoder-grid-drift class
13751 // -- correct only for as long as a leaf can never
13752 // be compound.
13753 record_mi(&mut grid, mi_row, mi_col, 4, block.inter, block.skip);
13754 leaves.push(block);
13755 } else {
13756 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
13757 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
13758 let mut eight = Vec::with_capacity(2);
13759 for i in 0..4 {
13760 let leaf_x = x_sub + (i % 2) * 8;
13761 let leaf_y = y_sub + (i / 2) * 8;
13762 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
13763 continue;
13764 }
13765 let (mi_row, mi_col) =
13766 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
13767 let stack = find_mv_stack(
13768 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
13769 );
13770 let cstacks = leaf_compound_stacks(
13771 &grid, mi_row, mi_col, 2, 2, mi_cols, mi_rows,
13772 header.reference_select, golden, altref,
13773 );
13774 let (leaf, _) = code_square_inter(
13775 &mut luma,
13776 &mut chroma,
13777 (leaf_x, leaf_y),
13778 8,
13779 &search,
13780 &mode_bits_table,
13781 reference,
13782 &stack,
13783 &cstacks,
13784 &grid,
13785 (mi_row, mi_col),
13786 (mi_rows, mi_cols),
13787 &obmc_refs,
13788 fctx,
13789 );
13790 // Same publication point as the 16x16
13791 // straddling leaf above (`record_mi`).
13792 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter, leaf.skip);
13793 eight.push(leaf);
13794 }
13795 leaves.push(BlockCoeffs {
13796 eight: Some(eight),
13797 ..BlockCoeffs::default()
13798 });
13799 }
13800 }
13801 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
13802 }
13803 }
13804 // The 64x64 root against what its four quadrants really cost.
13805 if let Some((cost64, block, after)) = sb64
13806 && (early64
13807 || cost64
13808 < sb_cost
13809 + sb_search.lambda * crate::tile::partition_bits(SUPERBLOCK, true))
13810 {
13811 B64_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13812 if block.inter.is_some_and(|i| i.ref1.is_some()) {
13813 B64_COMPOUND_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13814 }
13815 if !whole_inside {
13816 B64_EDGE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13817 }
13818 blocks.truncate(mark);
13819 restore(&mut luma, &mut chroma, (x64, y64), SUPERBLOCK, &after);
13820 // Overwrites every 16x16 mi cell the quadrant searches
13821 // published under this superblock, so the next block's stack
13822 // is built off the block that was really coded.
13823 record_mi(&mut grid, sb_r * 16, sb_c * 16, 16, block.inter, block.skip);
13824 blocks.push(((sb_r * 2) * cols + sb_c * 2, Quadrant::Whole64(block)));
13825 for q in 1..4 {
13826 let (r32, c32) = (sb_r * 2 + q / 2, sb_c * 2 + q % 2);
13827 blocks.push((r32 * cols + c32, Quadrant::Covered));
13828 }
13829 root_cost += cost64;
13830 } else {
13831 root_cost += sb_cost;
13832 }
13833 }
13834 // lane-b128: the whole 128x128 root (`PARTITION_NONE` at the root's
13835 // `partition_w128` symbol) against what its four superblocks really
13836 // cost, the same weighing the 64 root does one size down. Both sides
13837 // carry their own partition symbol, so the comparison is complete.
13838 // The root candidates, each tagged with the PARTITION symbol its
13839 // writer codes: 0 NONE, 1 HORZ, 2 VERT (lane-b128hv), 4..=7 the AB
13840 // shapes (lane-ab128).
13841 let mut cands: Vec<(f64, f64, usize, Vec<BlockCoeffs>, _)> = Vec::new();
13842 if let Some((c, l, b, a)) = root128 {
13843 cands.push((c, l, 0, vec![b], a));
13844 }
13845 if let Some((horz, (c, l, halves, a))) = root_rect {
13846 cands.push((c, l, usize::from(!horz) + 1, halves.to_vec(), a));
13847 }
13848 if let Some((symbol, (c, l, pieces, a))) = root_ab {
13849 cands.push((c, l, symbol, pieces.to_vec(), a));
13850 }
13851 // The witness knobs drop every other arm outright: on synthetic
13852 // content the whole block always wins its own comparison.
13853 if forced_rect != 0 {
13854 cands.retain(|c| c.2 == 1 || c.2 == 2);
13855 }
13856 if forced_ab != 0 {
13857 cands.retain(|c| c.2 == usize::from(forced_ab));
13858 }
13859 cands.sort_by(|a, b| a.0.total_cmp(&b.0));
13860 // lane-rectdq class sweep: under a 128 superblock grid the FOUR-
13861 // superblock arm codes the delta_q group too -- the Whole64 writer
13862 // (tile.rs `sb_coeff_inter_frame_tile_cdfs`, the `write_delta_q` call
13863 // with `!sb128_armed()`) and every smaller shape below it pass
13864 // `is_whole_sb = false` under a 128 grid, so the arm's first
13865 // (root-origin) superblock codes the group even when skipped. Only the skipped 128
13866 // NONE root escapes it, so the split side is charged here at the same
13867 // root lambda the candidates are priced with.
13868 let split_dq =
13869 delta_q_bits_at_root(sb_q.as_ref(), sb_cols, base_q_idx, dq_res, (root_r, root_c));
13870 if let Some((cost128, lambda128, shape, halves, after)) = cands.into_iter().next()
13871 && (cost128
13872 < root_cost + lambda128 * (crate::tile::partition_bits(128, true) + split_dq)
13873 // The witness knobs take the root whatever it costs, so the
13874 // forced block really reaches the writer.
13875 || FORCE_B128_ROOT.load(std::sync::atomic::Ordering::Relaxed)
13876 || forced_rect != 0
13877 || forced_ab != 0)
13878 {
13879 let (x128, y128) = (root_c * SUPERBLOCK, root_r * SUPERBLOCK);
13880 blocks.truncate(mark128);
13881 restore(&mut luma, &mut chroma, (x128, y128), SUPERBLOCK * 2, &after);
13882 let at = (root_r * 2) * cols + root_c * 2;
13883 match shape {
13884 0 => {
13885 B128_NONE_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13886 let block = halves.into_iter().next().expect("the NONE arm's block");
13887 record_mi(&mut grid, root_r * 16, root_c * 16, 32, block.inter, block.skip);
13888 blocks.push((at, Quadrant::Whole128(block)));
13889 }
13890 // lane-ab128: three pieces, published at their own footprints
13891 // in the writer's own order ([`ab128_pieces`]).
13892 symbol @ 4..=7 => {
13893 B128_AB_HITS[symbol - 4].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13894 for (((mr, mc), (w, h)), piece) in
13895 ab128_pieces(symbol, (root_r * 16, root_c * 16)).iter().zip(&halves)
13896 {
13897 record_mi_rect(
13898 &mut grid,
13899 *mr,
13900 *mc,
13901 (w / 4, h / 4),
13902 piece.inter,
13903 piece.skip,
13904 );
13905 }
13906 blocks.push((at, Quadrant::Ab128(symbol as u8, halves)));
13907 }
13908 symbol => {
13909 let horz = symbol == 1;
13910 if horz {
13911 B128_HORZ_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13912 } else {
13913 B128_VERT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
13914 }
13915 let (w_mi, h_mi) = if horz { (32usize, 16usize) } else { (16, 32) };
13916 for (i, half) in halves.iter().enumerate() {
13917 let (mr, mc) = if horz {
13918 (root_r * 16 + i * 16, root_c * 16)
13919 } else {
13920 (root_r * 16, root_c * 16 + i * 16)
13921 };
13922 record_mi_rect(&mut grid, mr, mc, (w_mi, h_mi), half.inter, half.skip);
13923 }
13924 blocks.push((at, Quadrant::Rect128(horz, halves)));
13925 }
13926 }
13927 for q in 1..16 {
13928 let (r32, c32) = (root_r * 2 + q / 4, root_c * 2 + q % 4);
13929 blocks.push((r32 * cols + c32, Quadrant::Covered));
13930 }
13931 }
13932 }
13933 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
13934 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
13935 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
13936 for (&out, tile) in chroma_out.iter().zip(&chroma) {
13937 copy_rect(
13938 out,
13939 &tile.reconstruction,
13940 frame_width / 2,
13941 x0 / 2,
13942 y0 / 2,
13943 x1.div_ceil(2),
13944 y1.div_ceil(2),
13945 );
13946 }
13947 Ok(blocks)
13948 };
13949 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
13950 .into_iter()
13951 .flatten()
13952 {
13953 blocks[at] = quadrant;
13954 }
13955
13956 // lane-b128, `EC_AV1_B128_CENSUS=1`: how many of this INTER frame's 128
13957 // superblock roots the search left whole, so a flat BD result is
13958 // attributable (class `gate-blind-to-feature`). A key frame codes none:
13959 // only the inter writer has a 128x128 block.
13960 if crate::envflags::env_flag!("EC_AV1_B128_CENSUS") {
13961 let whole = blocks
13962 .iter()
13963 .filter(|q| matches!(q, Quadrant::Whole128(_)))
13964 .count();
13965 let roots = blocks
13966 .iter()
13967 .filter(|q| !matches!(q, Quadrant::Covered))
13968 .count();
13969 // lane-b128r: of those roots, how many code a REAL residual rather
13970 // than the skip-only block lane-b128 shipped -- the fire count this
13971 // arm's own gate row is read against.
13972 let residual = blocks
13973 .iter()
13974 .filter(|q| matches!(q, Quadrant::Whole128(b) if !b.skip))
13975 .count();
13976 // lane-b128r: and how many named a second reference (the compound
13977 // arm at the 128 root).
13978 let compound = blocks
13979 .iter()
13980 .filter(|q| {
13981 matches!(q, Quadrant::Whole128(b) if b.inter.is_some_and(|i| i.ref1.is_some()))
13982 })
13983 .count();
13984 // lane-b128hv: and how many roots took a rect cut instead, per shape
13985 // -- the HORZ/VERT fire count the gate rows are read against.
13986 let horz = blocks
13987 .iter()
13988 .filter(|q| matches!(q, Quadrant::Rect128(true, _)))
13989 .count();
13990 let vert = blocks
13991 .iter()
13992 .filter(|q| matches!(q, Quadrant::Rect128(false, _)))
13993 .count();
13994 let rect_compound = blocks
13995 .iter()
13996 .filter(|q| {
13997 matches!(q, Quadrant::Rect128(_, hs)
13998 if hs.iter().any(|b| b.inter.is_some_and(|i| i.ref1.is_some())))
13999 })
14000 .count();
14001 // lane-ab128: and how many took each AB shape, in PARTITION_HORZ_A
14002 // .. _VERT_B order -- the per-shape fire count its gate rows are read
14003 // against.
14004 let ab: [usize; 4] = std::array::from_fn(|i| {
14005 blocks
14006 .iter()
14007 .filter(|q| matches!(q, Quadrant::Ab128(s, _) if *s as usize == i + 4))
14008 .count()
14009 });
14010 eprintln!(
14011 "B128 census: inter frame, {whole} whole 128x128 roots ({residual} with a residual, \
14012 {compound} compound), {horz} HORZ + {vert} VERT roots ({rect_compound} with a \
14013 compound half), AB roots {}/{}/{}/{} (HORZ_A/HORZ_B/VERT_A/VERT_B), \
14014 {roots} coded blocks ({:.1}% of the frame's area at 128)",
14015 ab[0],
14016 ab[1],
14017 ab[2],
14018 ab[3],
14019 100.0 * ((whole + horz + vert + ab.iter().sum::<usize>()) * 16) as f64
14020 / blocks.len().max(1) as f64,
14021 );
14022 }
14023 let modes = blocks
14024 .iter()
14025 .flat_map(Quadrant::blocks)
14026 .map(|b| b.mode)
14027 .collect::<Vec<_>>();
14028 let inter_block_share = blocks
14029 .iter()
14030 .flat_map(Quadrant::blocks)
14031 .filter(|b| b.inter.is_some())
14032 .count() as f64
14033 / modes.len() as f64;
14034 for block in blocks.iter().flat_map(Quadrant::blocks) {
14035 if let Some(info) = block.inter {
14036 let r = (info.ref_frame as usize).min(7);
14037 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
14038 }
14039 }
14040 #[cfg(test)]
14041 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
14042 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
14043 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
14044 // next frame's writer starts from them -- exactly what
14045 // `crate::stream::stored_cdfs_for` hands the decoder.
14046 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
14047 let mut cdfs = start_cdfs
14048 .cloned()
14049 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
14050 // lane-txi: set per frame, never inherited from the snapshot the
14051 // previous frame stored -- the content gate can flip the bit between
14052 // frames (class `per-tile-state-not-reset`).
14053 cdfs.reduced_tx_set = header.reduced_tx_set;
14054 let start_cdfs = CdfSnapshot(cdfs);
14055 let reference_select_bit = header.reference_select;
14056 let switchable_motion_mode = header.is_motion_mode_switchable;
14057 let warped_motion = header.allow_warped_motion;
14058 let order_hint_bits = seq.order_hint_bits;
14059 let lr_horz = crate::restoration::count_units(header.frame_width, lr_unit()) as u32;
14060 let lr_vert = crate::restoration::count_units(header.frame_height, lr_unit()) as u32;
14061 // What this frame stores is the LARGEST tile's end-of-tile tables --
14062 // its own header's `context_update_tile_id` (spec 7.20), which
14063 // `tile_info_of` set to exactly that tile.
14064 let store_tile = layout.largest_tile();
14065 let end_cdfs = std::cell::RefCell::new(None);
14066 // As in `encode_key_frame_inner`: every tile starts from this frame's
14067 // own tables, so no tile depends on any other.
14068 let code_tiles = |bits: u8,
14069 sb_cols: usize,
14070 cdef_grid: &[u8],
14071 units: &[Option<crate::restoration::WienerInfo>]|
14072 -> Result<Vec<Vec<u8>>> {
14073 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
14074 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
14075 crate::tile::arm_delta_q(
14076 deltaq_res.filter(|_| sb_q.is_some()).unwrap_or(0),
14077 sb_cols,
14078 sb_q.clone().unwrap_or_default(),
14079 base_q_idx,
14080 );
14081 crate::tile::arm_lr(lr_unit(), lr_horz, lr_vert, units.to_vec());
14082 crate::tile::arm_sb128(sb128_on());
14083 crate::tile::arm_sign_bias(sign_bias);
14084 // Thread-locals: every tile job arms its own worker.
14085 crate::tile::arm_reference_select(reference_select_bit);
14086 crate::tile::arm_motion_mode(switchable_motion_mode);
14087 crate::tile::arm_warped_motion(warped_motion);
14088 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
14089 crate::tile::arm_high_precision_mv(hp_mv);
14090 crate::tile::arm_screen(screen);
14091 crate::tile::arm_frame_mi_dims(frame_mi_dims);
14092 crate::tile::arm_filter_intra(filter_intra_on());
14093 let mut cdfs = start_cdfs.0.clone();
14094 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
14095 // Each tile's own MV grid: a candidate scan never reaches past
14096 // the tile's bounds, so a grid holding only this tile's own
14097 // blocks reads exactly as the decoder's frame-wide one does
14098 // under `MiGrid::set_tile_bounds`.
14099 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
14100 mv_grid.set_sign_bias(sign_bias);
14101 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
14102 mi_cols,
14103 mi_rows,
14104 base_q_idx,
14105 &blocks,
14106 tx_select,
14107 &mut cdfs,
14108 layout.rect(index),
14109 &mut mv_grid,
14110 )?;
14111 Ok((bytes, Some(cdfs)))
14112 })?;
14113 if let Some(cdfs) = stored {
14114 *end_cdfs.borrow_mut() = Some(cdfs);
14115 }
14116 Ok(out)
14117 };
14118 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
14119 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
14120 // this tile against the same single-slot reference this encoder predicted
14121 // from, under each candidate level.
14122 // The reference a DECODER holds is this frame's cropped size, not the
14123 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
14124 // reference whose height is not the header's own `frame_height` (spec
14125 // 7.9's compatible-size rule), and the chained-decode round trips prove
14126 // the two predict identically.
14127 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
14128 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
14129 reference.clone()
14130 } else {
14131 Picture {
14132 width: fw,
14133 height: fh,
14134 y: crop_plane(&reference.y, reference.width, fw, fh),
14135 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
14136 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
14137 }
14138 };
14139 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
14140 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
14141 // blocks may name GOLDEN needs that plane too, cropped the same way.
14142 let trial_golden = golden.map(|g| {
14143 if (g.width, g.height) == (fw, fh) {
14144 g.clone()
14145 } else {
14146 Picture {
14147 width: fw,
14148 height: fh,
14149 y: crop_plane(&g.y, g.width, fw, fh),
14150 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
14151 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
14152 }
14153 }
14154 });
14155 let trial_altref = altref.map(|a| {
14156 if (a.width, a.height) == (fw, fh) {
14157 a.clone()
14158 } else {
14159 Picture {
14160 width: fw,
14161 height: fh,
14162 y: crop_plane(&a.y, a.width, fw, fh),
14163 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
14164 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
14165 }
14166 }
14167 });
14168 let trial_last2 = last2.map(|l| {
14169 if (l.width, l.height) == (fw, fh) {
14170 l.clone()
14171 } else {
14172 Picture {
14173 width: fw,
14174 height: fh,
14175 y: crop_plane(&l.y, l.width, fw, fh),
14176 u: crop_plane(&l.u, l.width / 2, fw / 2, fh / 2),
14177 v: crop_plane(&l.v, l.width / 2, fw / 2, fh / 2),
14178 }
14179 }
14180 });
14181 let mut refs: [Option<&Picture>; 8] = [None; 8];
14182 refs[1] = Some(&trial_ref);
14183 refs[2] = trial_last2.as_ref();
14184 refs[4] = trial_golden.as_ref();
14185 refs[7] = trial_altref.as_ref();
14186 let refpix = crate::decode::RefPix::ready(refs);
14187 // lane-txrd: the frame's luma error BEFORE the loop filters, i.e. the
14188 // sum the block search believed it was minimising. Against the
14189 // post-filter per-frame PSNR the gate prints, this separates a trial
14190 // whose reconstruction is a lie from a filter stage that undoes the win.
14191 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
14192 let sse: u64 = luma
14193 .reconstruction
14194 .chunks(luma.width)
14195 .take(luma.true_height)
14196 .zip(picture_y8.chunks(luma.width))
14197 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
14198 .map(|(&r, &s)| {
14199 let d = i64::from(r) - i64::from(s);
14200 (d * d) as u64
14201 })
14202 .sum();
14203 eprintln!("EC_PREFILTER q={base_q_idx} luma sse={sse}");
14204 }
14205 let post = |luma: &Plane<'_>, tag: &str| {
14206 if !crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
14207 return;
14208 }
14209 let sse: u64 = luma
14210 .reconstruction
14211 .chunks(luma.width)
14212 .take(luma.true_height)
14213 .zip(picture_y8.chunks(luma.width))
14214 .flat_map(|(r, s)| r[..luma.true_width].iter().zip(&s[..luma.true_width]))
14215 .map(|(&r, &s)| {
14216 let d = i64::from(r) - i64::from(s);
14217 (d * d) as u64
14218 })
14219 .sum();
14220 eprintln!("{tag} q={base_q_idx} luma sse={sse}");
14221 };
14222 pick_and_apply_filters(
14223 &mut header,
14224 &mut luma,
14225 &mut chroma,
14226 [&picture_y8, &picture_u8, &picture_v8],
14227 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
14228 // this frame's own `tx_select`, so the search runs under inter
14229 // `TxMode::Select` too (it used to skip and leave every inter frame
14230 // unfiltered once Select became the default).
14231 true,
14232 &mut tiles,
14233 search.lambda,
14234 fctx,
14235 &crate::tile::cdef_unit_owner(&blocks, mi_cols, mi_rows),
14236 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
14237 // are what the NEXT frame writes from, so the winning re-code
14238 // publishes its own into `end_cdfs` -- the first write's are stale
14239 // the moment a second tile is coded.
14240 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
14241 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
14242 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
14243 crate::decode::decode_inter_frame_tiles_lr(
14244 &payloads,
14245 &header_tile_info,
14246 h.mi_cols,
14247 h.mi_rows,
14248 base_q_idx,
14249 h.frame_width,
14250 h.frame_height,
14251 &refpix,
14252 cdef,
14253 lf,
14254 h.allow_high_precision_mv,
14255 h.force_integer_mv,
14256 Some(fctx.interp_filter.get()),
14257 seq.enable_dual_filter,
14258 h.reference_select,
14259 // lane-txi: this frame's own bit, not the hardcoded `true`
14260 // the wrapper used to pass.
14261 h.reduced_tx_set,
14262 tx_select,
14263 lr,
14264 // The trial decode re-reads the tile the writer just wrote,
14265 // so it starts from the same tables the writer did (this
14266 // frame's `start_cdfs`), not from the defaults.
14267 Some(start_cdfs.0.clone()),
14268 sign_bias,
14269 h.allow_screen_content_tools,
14270 switchable_motion_mode,
14271 h.allow_warped_motion,
14272 seq.enable_filter_intra,
14273 // lane-deltaq: this frame's own delta_q/delta_lf params, so
14274 // the trial decode reads the per-superblock `delta_qindex`
14275 // syntax the writer just wrote.
14276 h.delta.clone(),
14277 fctx,
14278 )
14279 },
14280 )?;
14281 post(&luma, "EC_POSTFILTER");
14282 let mut cdfs = end_cdfs
14283 .into_inner()
14284 .unwrap_or_else(|| start_cdfs.0.clone());
14285 cdfs.reset_counts();
14286 let next_cdfs = CdfSnapshot(cdfs);
14287 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
14288 header.tile_info.tile_size_bytes = tile_size_bytes;
14289 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
14290 let mut stream = temporal_delimiter();
14291 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
14292
14293 let [u, v] = chroma;
14294 Ok(Encoded {
14295 stream,
14296 modes,
14297 inter_block_share,
14298 reconstruction: Picture {
14299 width: luma.width,
14300 height: luma.height,
14301 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14302 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14303 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
14304 },
14305 tile,
14306 mi_cols: header.mi_cols,
14307 mi_rows: header.mi_rows,
14308 base_q_idx,
14309 tx_select,
14310 switchable_motion_mode,
14311 screen,
14312 reduced_tx_set: header.reduced_tx_set,
14313 start_cdfs,
14314 next_cdfs,
14315 loop_filter: header.loop_filter,
14316 cdef: header.cdef,
14317 loop_restoration: header.loop_restoration,
14318 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
14319 // intra frames only).
14320 allow_intrabc: false,
14321 delta: header.delta.clone(),
14322 })
14323}
14324
14325/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
14326/// frame's temporal unit followed by one inter frame's temporal unit per
14327/// remaining picture, all sharing the key frame's sequence header -- and
14328/// each frame's own [`Encoded`], in coding order.
14329#[derive(Clone, Debug)]
14330pub struct EncodedSequence {
14331 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
14332 /// sequence header and the key frame) followed by each later frame's
14333 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
14334 /// the sequence header the key frame carried).
14335 pub stream: Vec<u8>,
14336 /// One entry per picture, in DISPLAY order — the order a decoder outputs
14337 /// them and the order `pictures` came in. Without a pyramid that is also
14338 /// the coding order; with one the two differ, and `coding_order` is the
14339 /// map between them.
14340 pub frames: Vec<Encoded>,
14341 /// The index into `frames` of each coded frame, in CODING order — what a
14342 /// per-coded-frame census (`take_predicted_bits`) must be zipped against.
14343 /// `0..frames.len()` on the flat path.
14344 pub coding_order: Vec<usize>,
14345}
14346
14347/// Encodes a sequence of pictures as a key frame followed by one inter frame
14348/// per remaining picture, each predicting from the previous frame's own
14349/// decoded reconstruction — never from the source, which is what a decoder
14350/// cannot see. Every picture must be the same even size (any even width and
14351/// height — each is padded to a whole number of 64x64 superblocks
14352/// internally, which is what lets an inter frame's reference always match
14353/// the frame being coded against it), and `pictures` must be non-empty.
14354///
14355/// # Errors
14356/// Returns an error when `pictures` is empty, when any picture besides the
14357/// first is not the same size as the first, or under the same conditions
14358/// [`encode_key_frame`] and the inter frame path do.
14359pub(crate) fn encode_sequence_with_ctx(
14360 pictures: &[Picture],
14361 base_q_idx: u8,
14362 deadzone: f64, fctx: &crate::decode::FrameCtx,
14363) -> Result<EncodedSequence> {
14364 let Some((first, rest)) = pictures.split_first() else {
14365 return Err(Error::unsupported(
14366 "AV1 encode",
14367 "a sequence needs at least one picture",
14368 ));
14369 };
14370 first.check_even()?;
14371 let render = (first.width, first.height);
14372 // THE CODING PYRAMID (lane-av1pyrdef): a sequence of camera material is
14373 // coded as mini-GOPs -- a hidden ALTREF ahead of its display position,
14374 // the leaves that predict backward off it, and a `show_existing_frame`
14375 // header that re-outputs it -- unless `EC_AV1_PYRAMID` turns it off for
14376 // an A/B. Screen content stays flat (the content gate in
14377 // `Av1Encoder::encode_frames`, whose detector this asks first so the
14378 // whole sequence path is decided in one place), and so does a run that
14379 // asks for a quantizer rounding offset the facade does not carry: the
14380 // facade codes at `encoder::DEADZONE` (0.5), so any other deadzone --
14381 // the ablations' -- must keep the flat path rather than be silently
14382 // ignored.
14383 //
14384 // The reordering itself is NOT reimplemented here: it is the facade's
14385 // own driver ([`crate::encoder::Av1Encoder::encode_sequence_pyramid`]),
14386 // called with this sequence's shape, so the two paths cannot drift.
14387 let pyramid = crate::encoder::Pyramid::from_env()
14388 .filter(|_| !rest.is_empty() && (deadzone - 0.5).abs() < f64::EPSILON)
14389 .filter(|_| !picture_is_screen(first));
14390 LAST_SEQ_PYRAMID.with(|c| c.set(pyramid));
14391 if let Some(pyramid) = pyramid {
14392 for picture in rest {
14393 picture.check_even()?;
14394 if (picture.width, picture.height) != render {
14395 return Err(Error::unsupported(
14396 "AV1 encode",
14397 "every picture in a sequence must be the same size as the first",
14398 ));
14399 }
14400 }
14401 return crate::encoder::Av1Encoder::encode_sequence_pyramid(
14402 pictures,
14403 base_q_idx,
14404 pyramid,
14405 armed_tiles(),
14406 );
14407 }
14408 // The key frame and every inter frame after it are coded at the same
14409 // padded size, so the reference each inter frame predicts from -- the
14410 // previous frame's own uncropped reconstruction, at the size a decoder's
14411 // reference buffer actually holds -- always matches the frame being
14412 // coded against it.
14413 let key = encode_key_frame_inner(
14414 &first.padded_to(SUPERBLOCK),
14415 base_q_idx,
14416 deadzone,
14417 &KEY_FRAME_MODES,
14418 split_blocks(),
14419 render,
14420 unspecified_color_config(), fctx,
14421 )?;
14422 let mut stream = key.stream.clone();
14423 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
14424 // key frame refreshes every slot, each inter frame only slot 0), which is
14425 // what `GOLDEN_FRAME` names.
14426 let golden = key.reconstruction.clone();
14427 // The frame two back, once there is one that is not the key frame
14428 // itself (which `GOLDEN_FRAME` already names).
14429 let mut prev2: Option<Picture> = None;
14430 let mut carried = key.next_cdfs.clone();
14431 let mut reference = key.reconstruction.clone();
14432 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
14433 for (i, picture) in rest.iter().enumerate() {
14434 picture.check_even()?;
14435 // lane-av1tpl2: the lookahead window the per-block lambda weighting
14436 // propagates back through -- the next [`tpl_depth`] - 1 pictures'
14437 // sources at this frame's coded (padded) size. The tail of the
14438 // sequence gets a shorter window, and the last frame none at all.
14439 let lookahead: Vec<Picture> = rest[(i + 1).min(rest.len())..]
14440 .iter()
14441 .take(tpl_depth() - 1)
14442 .map(|n| n.padded_to(SUPERBLOCK))
14443 .collect();
14444 if (picture.width, picture.height) != render {
14445 return Err(Error::unsupported(
14446 "AV1 encode",
14447 "every picture in a sequence must be the same size as the first",
14448 ));
14449 }
14450 let order_hint = (i + 1) as u32;
14451 let inter = encode_inter_frame(
14452 &picture.padded_to(SUPERBLOCK),
14453 &reference,
14454 base_q_idx,
14455 deadzone,
14456 order_hint,
14457 flat_order_hints(order_hint, 0, prev2.is_some()),
14458 render,
14459 Some(&carried.0),
14460 Some(&golden),
14461 prev2.as_ref(),
14462 None,
14463 fctx,
14464 None,
14465 &lookahead,
14466 )?;
14467 stream.extend_from_slice(&inter.stream);
14468 carried = inter.next_cdfs.clone();
14469 prev2 = Some(std::mem::replace(
14470 &mut reference,
14471 inter.reconstruction.clone(),
14472 ));
14473 frames.push(crop_encoded(&inter, render.0, render.1));
14474 }
14475 Ok(EncodedSequence {
14476 stream,
14477 coding_order: (0..frames.len()).collect(),
14478 frames,
14479 })
14480}
14481
14482#[cfg(test)]
14483mod tests {
14484
14485 /// Every (site, frame type, block side) the census can be called with
14486 /// lands in its own ten-counter bucket, inside the array (class
14487 /// `enumerate-table-domain`: an off-by-one here would silently add two
14488 /// sites' trials together).
14489 #[test]
14490 fn the_split_census_buckets_are_distinct_and_in_bounds() {
14491 let mut seen = std::collections::BTreeSet::new();
14492 for site in 0..2 {
14493 for key in [true, false] {
14494 for side in [8usize, 16, 32, 64] {
14495 let base = super::split_census_base(site, key, side);
14496 assert!(base + 10 <= super::SPLIT_CENSUS.len(), "{site} {key} {side}");
14497 assert!(seen.insert(base), "{site} {key} {side} collides");
14498 }
14499 }
14500 }
14501 assert_eq!(seen.len(), 16);
14502 }
14503
14504 /// An [`crate::mvstack::MvStack`] with every context at zero and no
14505 /// neighbours, for the pricer tests below to fill the one band each of
14506 /// them is about.
14507 /// lane-b128 task 0: every `ref_mv_idx` the `NEWMV`/`NEARMV` pricer
14508 /// offers must be one [`crate::tile::write_drl_idx`] can really SIGNAL
14509 /// against the same stack -- an offer the writer clamps prices the
14510 /// residual against a predictor the decoder never derives, which is the
14511 /// silent MV drift lane-sb128b root-caused (there fixed on the WRITER
14512 /// side, so the stream stays legal; here the pricer's own offer set is
14513 /// enumerated, class `enumerate-table-domain`).
14514 ///
14515 /// cargo test -p ec-av1 --lib -- every_drl_index_the_new_mv_pricer
14516 #[test]
14517 fn every_drl_index_the_new_mv_pricer_offers_is_one_the_writer_can_signal() {
14518 for n in 0..=4usize {
14519 let mut stack = bare_stack();
14520 for i in 0..n {
14521 stack.entries.push(crate::mvstack::StackEntry {
14522 mv: (8 * (i as i32 + 1), -8 * (i as i32 + 1)),
14523 weight: 1,
14524 });
14525 stack.drl_ctx.push(0);
14526 }
14527 stack.nearest_mv = stack.entries.first().map_or((0, 0), |e| e.mv);
14528 stack.near_mv = stack.entries.get(1).map_or((0, 0), |e| e.mv);
14529 stack.pred_mv = stack.nearest_mv;
14530 // Aim the vector at each entry in turn, so every index the offer
14531 // set holds is the one that wins at least once.
14532 for target in 0..n.max(1) {
14533 let mv = stack.entries.get(target).map_or(stack.pred_mv, |e| e.mv);
14534 let (_, idx) = best_new_mv_syntax(&stack, mv)
14535 .expect("a zero residual is always codable");
14536 let idx = usize::from(idx);
14537 assert_eq!(
14538 crate::tile::signalled_drl_idx(n, 0, idx),
14539 idx,
14540 "NEWMV: a {n}-entry stack cannot signal the offered drl index {idx}",
14541 );
14542 }
14543 // The NEARMV arm's own offer set (`search_inter_block`,
14544 // `search_skip_64`): indices 1 and 2, offered only when the stack
14545 // really holds that entry.
14546 for idx in 1..=2usize {
14547 if stack.entries.get(idx).is_some() {
14548 assert_eq!(
14549 crate::tile::signalled_drl_idx(n, 1, idx),
14550 idx,
14551 "NEARMV: a {n}-entry stack cannot signal the offered drl index {idx}",
14552 );
14553 }
14554 }
14555 }
14556 }
14557
14558 fn bare_stack() -> crate::mvstack::MvStack {
14559 crate::mvstack::MvStack {
14560 entries: Default::default(),
14561 nearest_mv: (0, 0),
14562 near_mv: (0, 0),
14563 pred_mv: (0, 0),
14564 new_mv_ctx: 0,
14565 ref_mv_ctx: 0,
14566 zero_mv_ctx: 0,
14567 drl_ctx: Default::default(),
14568 above_refs: (None, None),
14569 left_refs: (None, None),
14570 above_nbr: None,
14571 left_nbr: None,
14572 above_skip: false,
14573 left_skip: false,
14574 }
14575 }
14576
14577 /// [`super::compound_ref_bits`] pays exactly the symbols tile.rs'
14578 /// `write_compound_ref_frames` codes for a pair, each at that symbol's
14579 /// own neighbour-derived context. Red before lane-ctx, where the pricer
14580 /// spent four constants at CDF row 0 that assumed the pair was
14581 /// LAST+GOLDEN or LAST+ALTREF -- so a LAST+BWDREF pair was priced as
14582 /// LAST+ALTREF with its `comp_bwdref` p6 symbol missing entirely.
14583 #[test]
14584 fn the_compound_ref_pricer_pays_the_writers_own_symbol_sequence() {
14585 use crate::cdf::{COMP_BWDREF, COMP_MODE, COMP_REF, COMP_REF_TYPE, UNI_COMP_REF};
14586 use crate::encode::symbol_bits as b;
14587 use crate::mvstack::{
14588 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
14589 LAST_FRAME, NeighbourRef, comp_reference_type_ctx, reference_mode_ctx,
14590 single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx, single_ref_p4_ctx,
14591 single_ref_p5_ctx, single_ref_p6_ctx, uni_comp_ref_p1_ctx,
14592 };
14593 // (pair, unidirectional?, the tree's symbols as (table, p index,
14594 // context selector, value)) -- transcribed from the writer.
14595 // selector: 1..=6 are `single_ref_p*_ctx`, 7 is `uni_comp_ref_p1_ctx`.
14596 type Sym = (char, usize, usize, usize);
14597 let cases: [((i8, i8), bool, &[Sym]); 7] = [
14598 ((LAST_FRAME, LAST2_FRAME), true, &[('u', 0, 1, 0), ('u', 1, 7, 0)]),
14599 (
14600 (LAST_FRAME, LAST3_FRAME),
14601 true,
14602 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 0)],
14603 ),
14604 (
14605 (LAST_FRAME, GOLDEN_FRAME),
14606 true,
14607 &[('u', 0, 1, 0), ('u', 1, 7, 1), ('u', 2, 5, 1)],
14608 ),
14609 ((BWDREF_FRAME, ALTREF_FRAME), true, &[('u', 0, 1, 1)]),
14610 (
14611 (LAST_FRAME, ALTREF_FRAME),
14612 false,
14613 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 1)],
14614 ),
14615 (
14616 (LAST_FRAME, BWDREF_FRAME),
14617 false,
14618 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 0)],
14619 ),
14620 (
14621 (LAST_FRAME, ALTREF2_FRAME),
14622 false,
14623 &[('c', 0, 3, 0), ('c', 1, 4, 0), ('b', 0, 2, 0), ('b', 1, 6, 1)],
14624 ),
14625 ];
14626 let nbr = |ref0, ref1: Option<i8>| {
14627 Some(NeighbourRef {
14628 is_inter: true,
14629 ref0,
14630 ref1,
14631 uni: ref1.is_some_and(|r1| crate::mvstack::is_uni_comp_ref(ref0, r1)),
14632 })
14633 };
14634 // No neighbours (every context zero), then a mixed pair that puts the
14635 // p* rows, `comp_reference_type_ctx` and `reference_mode_ctx` off 0.
14636 for (above_nbr, left_nbr, above_refs, left_refs) in [
14637 (None, None, (None, None), (None, None)),
14638 (
14639 nbr(LAST_FRAME, None),
14640 nbr(ALTREF_FRAME, Some(GOLDEN_FRAME)),
14641 (Some(LAST_FRAME), None),
14642 (Some(ALTREF_FRAME), Some(GOLDEN_FRAME)),
14643 ),
14644 ] {
14645 let stack = crate::mvstack::MvStack {
14646 above_nbr,
14647 left_nbr,
14648 above_refs,
14649 left_refs,
14650 ..bare_stack()
14651 };
14652 let (a, a1) = above_refs;
14653 let (l, l1) = left_refs;
14654 let ctx_of = |sel: usize| match sel {
14655 1 => single_ref_p1_ctx(a, a1, l, l1),
14656 2 => single_ref_p2_ctx(a, a1, l, l1),
14657 3 => single_ref_p3_ctx(a, a1, l, l1),
14658 4 => single_ref_p4_ctx(a, a1, l, l1),
14659 5 => single_ref_p5_ctx(a, a1, l, l1),
14660 6 => single_ref_p6_ctx(a, a1, l, l1),
14661 _ => uni_comp_ref_p1_ctx(a, a1, l, l1),
14662 };
14663 for (pair, unidir, symbols) in cases {
14664 let mut want = b(&COMP_MODE[reference_mode_ctx(above_nbr, left_nbr)], 1)
14665 + b(
14666 &COMP_REF_TYPE[comp_reference_type_ctx(above_nbr, left_nbr)],
14667 usize::from(!unidir),
14668 );
14669 for &(table, p, sel, v) in symbols {
14670 let row = ctx_of(sel);
14671 want += match table {
14672 'u' => b(&UNI_COMP_REF[row][p], v),
14673 'c' => b(&COMP_REF[row][p], v),
14674 _ => b(&COMP_BWDREF[row][p], v),
14675 };
14676 }
14677 let got = super::compound_ref_bits(pair, &stack);
14678 assert!(
14679 (got - want).abs() < 1e-9,
14680 "pair {pair:?} above {above_refs:?} left {left_refs:?}: \
14681 priced {got} bits, writer codes {want}"
14682 );
14683 }
14684 }
14685 }
14686
14687 /// The `skip` and `is_inter` symbols are priced at the SAME context
14688 /// tile.rs codes them with -- `above_skip + left_skip` for the first and
14689 /// `intra_inter_ctx` for the second -- not at row 0. Red before lane-ctx
14690 /// on every neighbour configuration whose context is not zero (class
14691 /// pricer-context-zero).
14692 #[test]
14693 fn the_skip_and_intra_inter_pricers_use_the_writers_own_contexts() {
14694 use crate::cdf::{INTRA_INTER, SKIP};
14695 use crate::encode::symbol_bits as b;
14696 use crate::mvstack::NeighbourRef;
14697 let nbr = |is_inter| NeighbourRef {
14698 is_inter,
14699 ref0: if is_inter { crate::mvstack::LAST_FRAME } else { 0 },
14700 ref1: None,
14701 uni: false,
14702 };
14703 for (above, left, above_skip, left_skip) in [
14704 (None, None, false, false),
14705 (Some(nbr(true)), Some(nbr(true)), true, false),
14706 (Some(nbr(false)), Some(nbr(false)), true, true),
14707 (Some(nbr(false)), None, false, true),
14708 (None, Some(nbr(true)), true, true),
14709 ] {
14710 let stack = crate::mvstack::MvStack {
14711 above_nbr: above,
14712 left_nbr: left,
14713 above_skip,
14714 left_skip,
14715 ..bare_stack()
14716 };
14717 let skip_ctx = usize::from(above_skip) + usize::from(left_skip);
14718 let ii_ctx = crate::tile::intra_inter_ctx(
14719 above.is_some(),
14720 left.is_some(),
14721 above.is_some_and(|n| n.is_inter),
14722 left.is_some_and(|n| n.is_inter),
14723 );
14724 for v in [false, true] {
14725 let (got, want) = (
14726 super::skip_bits_at(&stack, v),
14727 b(&SKIP[skip_ctx], usize::from(v)),
14728 );
14729 assert!(
14730 (got - want).abs() < 1e-9,
14731 "skip {v} at ctx {skip_ctx}: priced {got}, writer codes {want}"
14732 );
14733 let (got, want) = (
14734 super::intra_inter_bits_at(&stack, v),
14735 b(&INTRA_INTER[ii_ctx], usize::from(v)),
14736 );
14737 assert!(
14738 (got - want).abs() < 1e-9,
14739 "is_inter {v} at ctx {ii_ctx}: priced {got}, writer codes {want}"
14740 );
14741 }
14742 }
14743 }
14744
14745 /// [`super::single_ref_bits`] pays exactly what tile.rs'
14746 /// `write_single_ref` codes: the p1/p2/p6 chain for a BACKWARD
14747 /// reference and the p1/p3/p4/p5 chain for a forward one, each symbol at
14748 /// the context that symbol's own `single_ref_p*_ctx` derives from the
14749 /// block's above/left neighbours. Red before lane-pricer, where every
14750 /// backward reference was priced as LAST (p1=0,p3=0,p4=0) at context 0.
14751 #[test]
14752 fn the_single_ref_pricer_pays_the_writers_own_symbol_sequence() {
14753 use crate::cdf::SINGLE_REF as SR;
14754 use crate::encode::symbol_bits as b;
14755 use crate::mvstack::{
14756 ALTREF2_FRAME, ALTREF_FRAME, BWDREF_FRAME, GOLDEN_FRAME, LAST2_FRAME, LAST3_FRAME,
14757 LAST_FRAME, MvStack, single_ref_p1_ctx, single_ref_p2_ctx, single_ref_p3_ctx,
14758 single_ref_p4_ctx, single_ref_p5_ctx, single_ref_p6_ctx,
14759 };
14760 let stack_with = |above_refs, left_refs, above_nbr, left_nbr| MvStack {
14761 above_refs,
14762 left_refs,
14763 above_nbr,
14764 left_nbr,
14765 ..bare_stack()
14766 };
14767 let nbr = |ref0, ref1| {
14768 Some(crate::mvstack::NeighbourRef { is_inter: true, ref0, ref1, uni: false })
14769 };
14770 // (reference, the symbols `write_single_ref` emits as (p index, value))
14771 let cases: [(i8, &[(usize, usize)]); 7] = [
14772 (LAST_FRAME, &[(0, 0), (2, 0), (3, 0)]),
14773 (LAST2_FRAME, &[(0, 0), (2, 0), (3, 1)]),
14774 (LAST3_FRAME, &[(0, 0), (2, 1), (4, 0)]),
14775 (GOLDEN_FRAME, &[(0, 0), (2, 1), (4, 1)]),
14776 (BWDREF_FRAME, &[(0, 1), (1, 0), (5, 0)]),
14777 (ALTREF2_FRAME, &[(0, 1), (1, 0), (5, 1)]),
14778 (ALTREF_FRAME, &[(0, 1), (1, 1)]),
14779 ];
14780 // Both neighbours intra, then the mixed LAST-above/ALTREF-left pair
14781 // that puts every p* context on a different row -- the second with a
14782 // COMPOUND left neighbour, which is what takes `reference_mode_ctx`
14783 // off row 0.
14784 for (above_refs, left_refs, above_nbr, left_nbr) in [
14785 ((None, None), (None, None), None, None),
14786 (
14787 (Some(LAST_FRAME), None),
14788 (Some(ALTREF_FRAME), Some(LAST_FRAME)),
14789 nbr(LAST_FRAME, None),
14790 nbr(ALTREF_FRAME, Some(LAST_FRAME)),
14791 ),
14792 ] {
14793 let stack = stack_with(above_refs, left_refs, above_nbr, left_nbr);
14794 let (a, a1) = above_refs;
14795 let (l, l1) = left_refs;
14796 let ctx_of = |p: usize| match p {
14797 0 => single_ref_p1_ctx(a, a1, l, l1),
14798 1 => single_ref_p2_ctx(a, a1, l, l1),
14799 2 => single_ref_p3_ctx(a, a1, l, l1),
14800 3 => single_ref_p4_ctx(a, a1, l, l1),
14801 4 => single_ref_p5_ctx(a, a1, l, l1),
14802 _ => single_ref_p6_ctx(a, a1, l, l1),
14803 };
14804 for (ref_frame, symbols) in cases {
14805 // Plus the `comp_mode = 0` symbol the writer codes ahead of
14806 // the reference syntax on a `reference_select` frame.
14807 let mut want: f64 = symbols.iter().map(|&(p, v)| b(&SR[ctx_of(p)][p], v)).sum();
14808 if super::reference_select() {
14809 want += b(
14810 &crate::cdf::COMP_MODE[crate::mvstack::reference_mode_ctx(
14811 above_nbr, left_nbr,
14812 )],
14813 0,
14814 );
14815 }
14816 let got = super::single_ref_bits(ref_frame, &stack);
14817 assert!(
14818 (got - want).abs() < 1e-9,
14819 "ref {ref_frame} above {above_refs:?} left {left_refs:?}: \
14820 priced {got} bits, writer codes {want}"
14821 );
14822 }
14823 }
14824 }
14825
14826 /// lane-av1tpl2's propagated map, on the two properties every decision
14827 /// under it rests on: a frame the whole lookahead window repeats exactly
14828 /// (uniform texture) leans on every cell alike, so every factor is 1 and
14829 /// the weighting is a no-op; and where the window really does save bits
14830 /// by predicting -- the textured half of a frame whose other half is
14831 /// flat -- the factor FALLS below 1, i.e. that half is coded more
14832 /// distortion-averse than the half nothing gains from.
14833 /// The distortion metric itself (lane-sse): a block the true frame edge
14834 /// cuts through is scored over its INSIDE part only, so a difference that
14835 /// lives entirely in the padding costs nothing and a block wholly past
14836 /// the edge scores zero. Before this, the search ranked modes,
14837 /// transforms and partition trees on samples the display crop throws
14838 /// away -- which lane-b64b had fixed for the 64x64 root alone.
14839 #[test]
14840 fn a_block_the_frame_edge_cuts_is_scored_over_its_inside_only() {
14841 // A 40x40 true frame on a 64x64 padded coding surface.
14842 let source = vec![10u8; 64 * 64];
14843 let plane = fresh_plane(&source, 64, 64, 40, 40);
14844 let mut reconstruction = vec![10u8; 64 * 64];
14845 // Off by 190 at (50, 50) -- past the true edge in both axes.
14846 reconstruction[50 * 64 + 50] = 200;
14847 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 0.0, "padding was scored");
14848 // Off by 10 at (39, 39) -- the last sample the decoder shows.
14849 reconstruction[39 * 64 + 39] = 20;
14850 assert_eq!(plane.block_sse(0, 0, 64, &reconstruction), 100.0, "inside was not scored");
14851 // A 16x16 block whose every sample is padding.
14852 let block = vec![200u8; 16 * 16];
14853 assert_eq!(plane.block_sse(48, 0, 16, &block), 0.0, "a block past the edge scored");
14854 // A 16x16 block the edge cuts: 8 of its columns are inside.
14855 assert_eq!(plane.block_sse(32, 32, 16, &block), (190.0 * 190.0) * 64.0);
14856 }
14857
14858 /// lane-dq: libaom's objective mapping ([`super::deltaq_libaom`]) must
14859 /// spend WHERE THE WINDOW LEANS, stay congruent to the base on the
14860 /// `delta_q_res` grid, and stop at libaom's own `+-(res * 9 - 1)` bound.
14861 #[test]
14862 fn the_objective_delta_q_mapping_leans_the_right_way_and_stops_at_libaom_s_clamp() {
14863 let (base, res) = (162u8, 4i32);
14864 let rf = 2.0;
14865 // A superblock the window leans on more than the frame average is
14866 // coded FINER (lower qindex); a slack one coarser; the average one
14867 // exactly at the base.
14868 assert!(super::deltaq_libaom(base, 8.0, rf, 1.0, res) < base, "leaned-on SB must go finer");
14869 assert!(super::deltaq_libaom(base, 0.2, rf, 1.0, res) > base, "idle SB must go coarser");
14870 assert_eq!(super::deltaq_libaom(base, rf, rf, 1.0, res), base, "the average SB moves 0");
14871 // Every offset is a whole number of steps and inside +-(res * 9 - 1).
14872 let max = ((res * 9 - 1) / res) * res;
14873 for r in [0.0f64, 0.01, 0.5, 1.0, 3.0, 50.0, 1e6] {
14874 for k in [0.5f64, 1.0, 1.5] {
14875 let q = i32::from(super::deltaq_libaom(base, r, rf, k, res));
14876 let d = q - i32::from(base);
14877 assert_eq!(d % res, 0, "r={r} k={k}: offset {d} is not a whole {res}-step");
14878 assert!(d.abs() <= max, "r={r} k={k}: offset {d} past libaom's +-{max}");
14879 }
14880 }
14881 // The clamp is REACHED from both ends, so the bound is a real bound
14882 // and not a formula that never gets there.
14883 assert_eq!(i32::from(super::deltaq_libaom(base, 1e9, rf, 1.0, res)) - i32::from(base), -max);
14884 assert_eq!(i32::from(super::deltaq_libaom(base, 0.0, 1e9, 1.0, res)) - i32::from(base), max);
14885 // A stronger `k` never moves less than a weaker one.
14886 let d = |k: f64| (i32::from(super::deltaq_libaom(base, 8.0, rf, k, res)) - i32::from(base)).abs();
14887 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));
14888 // The frame reference is libaom's log-mean: flat in, the same value out.
14889 assert!((super::tpl_frame_ratio(&[2.5; 16]) - 2.5).abs() < 1e-9);
14890 }
14891
14892 /// lane-arfq: the per-level `delta_q` strength -- the spec parses onto
14893 /// [`super::DqLevel`]'s own indices, a missing or broken field keeps the
14894 /// shipped default, and the multiplier reaches the strength.
14895 #[test]
14896 fn the_per_level_delta_q_strength_indexes_the_levels_it_names() {
14897 let d = crate::speed::DQ_LEVEL_K;
14898 assert_eq!(super::dq_level_k_of(None), d, "no spec = the shipped table");
14899 assert_eq!(super::dq_level_k_of(Some("2:3:4")), [2.0, 3.0, 4.0]);
14900 // Short and broken fields fall back per SLOT, not per spec.
14901 assert_eq!(super::dq_level_k_of(Some("2")), [2.0, d[1], d[2]]);
14902 assert_eq!(super::dq_level_k_of(Some("2:x:-1")), [2.0, d[1], d[2]]);
14903 assert_eq!(super::DqLevel::TopArf as usize, 0);
14904 assert_eq!(super::DqLevel::MidArf as usize, 1);
14905 assert_eq!(super::DqLevel::Leaf as usize, 2);
14906 }
14907
14908 #[test]
14909 fn tpl_factors_are_flat_on_a_uniform_repeat_and_fall_where_the_window_leans() {
14910 // Four 64x64 superblocks across: the shipped map forms its ratio per
14911 // SUPERBLOCK (`EC_AV1_TPL_SB`), so a frame one superblock wide could
14912 // only ever produce one ratio -- and one ratio, mean-normalised, is
14913 // the flat map, whatever the content underneath it.
14914 let (w, h) = (256usize, 64usize);
14915 let uniform: Vec<u8> = (0..w * h).map(|i| ((i * 37) % 251) as u8).collect();
14916 let frames: Vec<&[u8]> = vec![&uniform, &uniform, &uniform];
14917 let (f, _) = super::tpl_lambda_factors(&frames, w, h, 1.0);
14918 assert_eq!(f.len(), 64, "16x4 cells of 16x16");
14919 for (i, &v) in f.iter().enumerate() {
14920 assert!((v - 1.0).abs() < 1e-6, "cell {i} factor {v}, a flat map must move no lambda");
14921 }
14922
14923 // Left half textured, right half constant: the window saves bits
14924 // predicting the left half and nothing at all on the right.
14925 let split: Vec<u8> = (0..w * h)
14926 .map(|i| if i % w < w / 2 { ((i * 37) % 251) as u8 } else { 128 })
14927 .collect();
14928 let frames: Vec<&[u8]> = vec![&split, &split, &split];
14929 let cells_x = w / 16;
14930 for k in [0.25f64, 0.5, 1.0, 2.0] {
14931 let (f, _) = super::tpl_lambda_factors(&frames, w, h, k);
14932 for r in 0..h / 16 {
14933 let (lean, idle) = (f[r * cells_x], f[r * cells_x + cells_x - 1]);
14934 assert!(lean < 1.0, "k={k} row {r}: leaned-on cell factor {lean} must be < 1");
14935 assert!(idle > 1.0, "k={k} row {r}: idle cell factor {idle} must be > 1");
14936 }
14937 }
14938 }
14939
14940 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
14941 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
14942 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
14943 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
14944 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
14945 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
14946 /// only a quarter of the 16x8 table and read the wrong byte for every
14947 /// block row but the first (silently wrong above-right/below-left
14948 /// availability -- wrong pixels, no error).
14949 #[test]
14950 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
14951 for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
14952 let (bw_log2, bh_log2) =
14953 ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize);
14954 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
14955 for (name, table) in
14956 [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)]
14957 {
14958 assert_eq!(
14959 table.len() * 8,
14960 rows * cols,
14961 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
14962 );
14963 let mut seen = vec![0u32; table.len() * 8];
14964 for blk_row in 0..rows {
14965 for blk_col in 0..cols {
14966 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
14967 assert!(
14968 idx < seen.len(),
14969 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
14970 );
14971 seen[idx] += 1;
14972 }
14973 }
14974 assert!(
14975 seen.iter().all(|&n| n == 1),
14976 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
14977 (row stride is not {cols})"
14978 );
14979 }
14980 }
14981 }
14982 use super::*;
14983 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
14984 use std::io::Write;
14985 use std::process::{Command, Stdio};
14986
14987 /// Every rectangular shape this decoder codes, at every position a block
14988 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
14989 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
14990 /// (`reconintra.c`) answer, whose bodies are ported below.
14991 ///
14992 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
14993 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
14994 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
14995 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
14996 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
14997 /// oracle's own arrays, so a re-routed or truncated table fails here even
14998 /// where the two rows happen to agree.
14999 ///
15000 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
15001 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
15002 /// callers handle by predicting each transform unit as its own block.
15003 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
15004 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
15005 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
15006 /// (the horizontal shapes, which those partitions never produce).
15007 #[test]
15008 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
15009 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
15010 // it pins the 64 reach explicitly instead of following the process's
15011 // own superblock knob (`for_encoder`), which made it red under
15012 // `EC_AV1_SB128=1` for no defect of the code under test.
15013 let fctx = &crate::decode::FrameCtx::new();
15014 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
15015 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
15016 (4, 8, 64, 9280, 64, 550),
15017 (8, 4, 64, 3712, 64, 9630),
15018 (8, 16, 16, 2352, 16, 134),
15019 (16, 8, 16, 960, 16, 2400),
15020 (16, 32, 4, 620, 4, 32),
15021 (32, 16, 4, 32, 4, 184),
15022 (32, 64, 1, 127, 1, 0),
15023 (64, 32, 1, 19, 1, 34),
15024 (4, 16, 32, 5472, 32, 14),
15025 (16, 4, 32, 960, 32, 6464),
15026 (8, 32, 8, 1400, 8, 2),
15027 (32, 8, 8, 32, 8, 1136),
15028 (16, 64, 2, 382, 2, 0),
15029 (64, 16, 2, 4, 2, 84),
15030 ];
15031 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
15032 /// a block whose transform covers it whole (`row_off == col_off == 0`,
15033 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
15034 /// superblock (`sb_mi_size == 16`).
15035 fn libaom_reach(
15036 bw: usize,
15037 bh: usize,
15038 x: usize,
15039 y: usize,
15040 width: usize,
15041 height: usize, _fctx: &crate::decode::FrameCtx,
15042 ) -> (bool, bool) {
15043 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
15044 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
15045 let sb_mi_size = 16usize;
15046 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
15047 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
15048 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
15049 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
15050 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
15051 // has_top_right: top_available && right_available, then row_off == 0.
15052 let top_right = if y == 0 || x + bw >= width {
15053 false
15054 } else if blk_row_in_sb == 0 {
15055 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
15056 // `bw_unit < bw_unit`, false for a whole-block transform.)
15057 true
15058 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
15059 false
15060 } else {
15061 bit(tr_table)
15062 };
15063 // has_bottom_left: bottom_available && left_available, col_off == 0.
15064 let bottom_left = if x == 0 || y + bh >= height {
15065 false
15066 } else if blk_col_in_sb == 0 {
15067 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
15068 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
15069 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
15070 false
15071 } else {
15072 bit(bl_table)
15073 };
15074 (top_right, bottom_left)
15075 }
15076 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
15077 let (tr, bl) = rect_reach_tables(bw, bh);
15078 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
15079 assert_eq!(
15080 (tr.len(), sum(tr), bl.len(), sum(bl)),
15081 (tr_len, tr_sum, bl_len, bl_sum),
15082 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
15083 );
15084 // Two superblocks across and down, so the superblock-relative
15085 // position (and not the frame position) is what decides.
15086 for sb_y in [0usize, 64] {
15087 for sb_x in [0usize, 64] {
15088 for y in (sb_y..sb_y + 64).step_by(bh) {
15089 for x in (sb_x..sb_x + 64).step_by(bw) {
15090 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
15091 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
15092 assert_eq!(
15093 (got.above_right, got.below_left),
15094 want,
15095 "{bw}x{bh} at ({x}, {y})"
15096 );
15097 }
15098 }
15099 }
15100 }
15101 }
15102 }
15103
15104 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
15105 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
15106 /// aomenc gate decodes its stream through ffmpeg and is meaningless
15107 /// without it -- turns it into a hard failure. Without this the require
15108 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
15109 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
15110 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
15111 fn have_ffmpeg() -> bool {
15112 let present = Command::new("ffmpeg")
15113 .arg("-version")
15114 .stdout(Stdio::null())
15115 .stderr(Stdio::null())
15116 .status()
15117 .is_ok_and(|s| s.success());
15118 assert!(
15119 present
15120 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
15121 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
15122 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
15123 );
15124 present
15125 }
15126
15127 /// Whether this ffmpeg was built with `encoder` (lane-pareto2: the
15128 /// SVT-AV1 Pareto rows are skipped, never failed, on a build without it).
15129 fn have_encoder(encoder: &str) -> bool {
15130 Command::new("ffmpeg")
15131 .args(["-hide_banner", "-encoders"])
15132 .stderr(Stdio::null())
15133 .output()
15134 .is_ok_and(|o| {
15135 String::from_utf8_lossy(&o.stdout)
15136 .lines()
15137 .any(|l| l.split_whitespace().nth(1) == Some(encoder))
15138 })
15139 }
15140
15141 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
15142 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
15143 let mut child = Command::new("ffmpeg")
15144 .args([
15145 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
15146 ])
15147 .stdin(Stdio::piped())
15148 .stdout(Stdio::piped())
15149 .stderr(Stdio::piped())
15150 .spawn()
15151 .expect("ffmpeg failed to start");
15152 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
15153 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
15154 // fills before the last input byte is written -- which is exactly what
15155 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
15156 // (measured: 45 min, both processes at 0% CPU). A write error here is
15157 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
15158 // below, are the real diagnosis.
15159 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
15160 let payload = stream.to_vec();
15161 let writer = std::thread::spawn(move || {
15162 let _ = stdin.write_all(&payload);
15163 });
15164 let out = child.wait_with_output().expect("ffmpeg failed to run");
15165 writer.join().expect("ffmpeg stdin writer thread");
15166 assert!(
15167 out.status.success(),
15168 "ffmpeg refused the stream: {}",
15169 String::from_utf8_lossy(&out.stderr)
15170 );
15171 let (luma, chroma) = (width * height, width * height / 4);
15172 assert_eq!(
15173 out.stdout.len(),
15174 luma + 2 * chroma,
15175 "expected one 4:2:0 frame"
15176 );
15177 Picture {
15178 width,
15179 height,
15180 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
15181 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
15182 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
15183 }
15184 }
15185
15186 /// A picture with something of everything in it: a gradient, an edge, a
15187 /// ripple and a block of flat colour, none of them aligned to the block
15188 /// grid.
15189 /// The in-loop filters actually FIRE and the stream still decodes to
15190 /// exactly what the encoder kept as its reconstruction
15191 /// (gate-blind-to-feature: a filter search that always answered "off"
15192 /// would leave every other test just as green, and the BD gate that
15193 /// would notice is `#[ignore]`d).
15194 ///
15195 /// Run:
15196 /// cargo test -p ec-av1 --release --lib -- \
15197 /// encode::tests::the_filter_search_picks_real_filters
15198 #[test]
15199 fn the_filter_search_picks_real_filters() {
15200 let _knobs = crate::speed::knob_read();
15201 let fctx = &crate::decode::FrameCtx::for_encoder();
15202 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
15203 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
15204 let fired = encoded
15205 .frames
15206 .iter()
15207 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
15208 .count();
15209 assert!(
15210 fired > 0,
15211 "no frame of this sequence chose any in-loop filtering: {:?}",
15212 encoded
15213 .frames
15214 .iter()
15215 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
15216 .collect::<Vec<_>>()
15217 );
15218 // The reconstruction the encoder predicts from is the FILTERED one,
15219 // and it is what a decoder of the stream produces -- byte for byte,
15220 // frame for frame.
15221 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
15222 assert_eq!(decoded.len(), encoded.frames.len());
15223 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
15224 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
15225 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
15226 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
15227 }
15228 }
15229
15230 fn test_card(width: usize, height: usize) -> Picture {
15231 let mut picture = Picture::grey(width, height);
15232 for y in 0..height {
15233 for x in 0..width {
15234 let gradient = x as f64 * 200.0 / width as f64;
15235 let ripple = 30.0
15236 * (x as f64 * std::f64::consts::PI / 23.0).sin()
15237 * (y as f64 * std::f64::consts::PI / 37.0).cos();
15238 let edge = if x > width * 3 / 7 && y > height / 3 {
15239 40.0
15240 } else {
15241 0.0
15242 };
15243 picture.y[y * width + x] =
15244 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
15245 }
15246 }
15247 for y in 0..height / 2 {
15248 for x in 0..width / 2 {
15249 let i = y * width / 2 + x;
15250 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
15251 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
15252 }
15253 }
15254 picture
15255 }
15256
15257 fn psnr(a: &[u16], b: &[u16]) -> f64 {
15258 let squared: f64 = a
15259 .iter()
15260 .zip(b)
15261 .map(|(&x, &y)| {
15262 let d = f64::from(x) - f64::from(y);
15263 d * d
15264 })
15265 .sum();
15266 if squared == 0.0 {
15267 return f64::INFINITY;
15268 }
15269 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
15270 }
15271
15272 /// lane-i64's witness: a smooth gradient is exactly the picture a whole
15273 /// 64x64 intra block predicts as well as four 32x32 ones, so the key
15274 /// frame's new root fires on most superblocks -- and what BOTH decoders
15275 /// produce is the encoder's own reconstruction, sample for sample.
15276 ///
15277 /// The fire count is the `gate-blind-to-feature` guard: without it every
15278 /// assert below passes on a stream that codes no whole superblock at all.
15279 #[test]
15280 fn a_smooth_gradient_key_frame_codes_whole_superblocks_and_decodes_exactly() {
15281 let _knobs = crate::speed::knob_read();
15282 let fctx = &crate::decode::FrameCtx::for_encoder();
15283 // 4 x 3 superblocks, all of them wholly inside the frame.
15284 let (width, height) = (256usize, 192usize);
15285 let mut picture = Picture::grey(width, height);
15286 for y in 0..height {
15287 for x in 0..width {
15288 picture.y[y * width + x] = (16 + (x + y) * 200 / (width + height)) as u16;
15289 }
15290 }
15291 for y in 0..height / 2 {
15292 for x in 0..width / 2 {
15293 picture.u[y * width / 2 + x] = (110 + x * 20 / (width / 2)) as u16;
15294 picture.v[y * width / 2 + x] = (130 - y * 20 / (height / 2)) as u16;
15295 }
15296 }
15297 let _ = take_i64_root_hits();
15298 let encoded = encode_key_frame_with_ctx(&picture, 120, 0.5, fctx).unwrap();
15299 let [roots, _offered, _edge] = take_i64_root_hits();
15300 // The counters are process-global, so another test encoding in
15301 // parallel can only ADD to them -- the per-FRAME fact is the mode
15302 // list, which carries one entry per coded block and so exactly 12
15303 // when every superblock was coded as one 64x64 intra block.
15304 assert_eq!(
15305 encoded.modes.len(),
15306 12,
15307 "not every superblock was coded as one 64x64 intra block"
15308 );
15309 assert!(
15310 roots >= 8,
15311 "a smooth-gradient key frame coded only {roots} whole 64x64 intra roots of 12"
15312 );
15313 eprintln!("whole 64x64 intra roots on a smooth gradient: {roots} of 12");
15314
15315 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
15316 assert_eq!(ours.len(), 1, "our decoder's frames");
15317 assert_eq!(ours[0].y, encoded.reconstruction.y, "our decoder: luma");
15318 assert_eq!(ours[0].u, encoded.reconstruction.u, "our decoder: U");
15319 assert_eq!(ours[0].v, encoded.reconstruction.v, "our decoder: V");
15320
15321 if !have_ffmpeg() {
15322 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15323 return;
15324 }
15325 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15326 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15327 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15328 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15329 }
15330
15331 /// The claim the whole encoder rests on: what a decoder produces is what
15332 /// the encoder said it would, sample for sample, on every plane.
15333 ///
15334 /// Prediction reads the reconstruction, so a single sample of drift
15335 /// anywhere would spread into every block below and to the right of it —
15336 /// which is why this is an equality and not a tolerance.
15337 #[test]
15338 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
15339 let _knobs = crate::speed::knob_read();
15340 let fctx = &crate::decode::FrameCtx::for_encoder();
15341 if !have_ffmpeg() {
15342 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
15343 return;
15344 }
15345 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48), (248, 152)] {
15346 let picture = test_card(width, height);
15347 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15348 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15349 assert_eq!(
15350 decoded.y, encoded.reconstruction.y,
15351 "{width}x{height}: luma"
15352 );
15353 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
15354 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
15355 }
15356 // One q index from each of the four coefficient-CDF contexts
15357 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
15358 let (width, height) = (64usize, 64usize);
15359 let picture = test_card(width, height);
15360 let _ = take_tx_depth_hits();
15361 for &q in &[15u8, 45, 100, 200] {
15362 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
15363 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15364 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
15365 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
15366 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
15367 }
15368 // lane-av1tx: the exactness above is only a claim about SPLIT
15369 // transforms if some block actually split one (`gate-blind-to-feature`
15370 // -- with `tx_depth` stuck at 0 every assert here passes on the
15371 // pre-lane stream). The test card's edges split at these four
15372 // quantizers; the counter is per-process (another test encoding in
15373 // parallel can only ADD to it, so this can be masked, never falsely
15374 // failed), so it is read once for the whole q ladder.
15375 let depths = take_tx_depth_hits();
15376 assert!(
15377 depths[1] + depths[2] > 0,
15378 "no block split its transform: depths {depths:?}"
15379 );
15380 }
15381
15382 /// A synthetic screen-content picture -- a few flat colours in a grid of
15383 /// boxes with hard edges and text-like bars, the shape a desktop capture
15384 /// has -- so the palette path is exercised on content it is for.
15385 #[cfg(test)]
15386 fn screen_card(width: usize, height: usize) -> Picture {
15387 const INK: [u16; 4] = [16, 90, 180, 235];
15388 let mut picture = Picture::grey(width, height);
15389 for y in 0..height {
15390 for x in 0..width {
15391 let cell = (x / 24 + y / 24) % 2;
15392 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
15393 picture.y[y * width + x] = INK[cell * 2 + bar];
15394 }
15395 }
15396 // Four chroma colours, not two: a two-colour chroma block only ever
15397 // codes a `PaletteSizeUV` of 2, which leaves
15398 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
15399 // deltas and the neighbour cache flags, exercised only when
15400 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
15401 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
15402 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
15403 for y in 0..height / 2 {
15404 for x in 0..width / 2 {
15405 let cell = (x / 12 + 2 * (y / 12)) % 4;
15406 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
15407 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
15408 }
15409 }
15410 picture
15411 }
15412
15413 /// The lane's own end-to-end check: on screen content the detector fires,
15414 /// blocks really take a palette (fire count, class
15415 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
15416 /// symbol this lane writes -- reconstructs exactly what the encoder did.
15417 /// The film-shaped `test_card` must NOT trip the detector, which is what
15418 /// keeps every non-screen stream byte-identical.
15419 #[test]
15420 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
15421 let _knobs = crate::speed::knob_read();
15422 let fctx = &crate::decode::FrameCtx::for_encoder();
15423 let (width, height) = (192usize, 96usize);
15424 let _ = crate::tile::take_palette_hits();
15425 let picture = screen_card(width, height);
15426 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15427 assert!(
15428 encoded.screen,
15429 "the detector did not fire on screen content -- no palette syntax was coded at all"
15430 );
15431 let hits = crate::tile::take_palette_hits();
15432 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
15433 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
15434 // The chroma half is a claim about the plane-1 syntax only if some
15435 // block really took a chroma palette (`gate-blind-to-feature`): every
15436 // exactness assert below passes on a stream that codes
15437 // `palette_uv_mode == 0` everywhere.
15438 let uv_hits = crate::tile::take_palette_uv_hits();
15439 assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
15440 let uv_cached = crate::tile::take_palette_uv_cache_hits();
15441 eprintln!(
15442 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
15443 uv_hits[0],
15444 &uv_hits[2..]
15445 );
15446 assert!(
15447 uv_cached > 0,
15448 "no chroma base colour came out of the neighbour cache -- \
15449 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
15450 );
15451 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
15452 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
15453 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
15454 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
15455 if !have_ffmpeg() {
15456 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15457 return;
15458 }
15459 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15460 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15461 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15462 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15463 // A whole GOP: the inter frames' own intra blocks carry the palette
15464 // syntax too (the three intra arms of the inter writers), which only
15465 // ffmpeg reading the frames back can prove.
15466 let moved: Vec<Picture> = (0..4)
15467 .map(|f| {
15468 let base = screen_card(width, height);
15469 let mut out = Picture::grey(width, height);
15470 for y in 0..height {
15471 for x in 0..width {
15472 let sx = (x + f * 7) % width;
15473 out.y[y * width + x] = base.y[y * width + sx];
15474 }
15475 }
15476 for y in 0..height / 2 {
15477 for x in 0..width / 2 {
15478 let sx = (x + f * 3) % (width / 2);
15479 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
15480 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
15481 }
15482 }
15483 out
15484 })
15485 .collect();
15486 let _ = crate::tile::take_palette_hits();
15487 let _ = crate::tile::take_palette_uv_hits();
15488 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
15489 let gop_hits = crate::tile::take_palette_hits();
15490 let gop_uv_hits = crate::tile::take_palette_uv_hits();
15491 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
15492 eprintln!(
15493 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
15494 {} chroma palette blocks",
15495 inter_screen, gop_hits[0], gop_uv_hits[0]
15496 );
15497 assert!(
15498 gop_uv_hits[0] > 0,
15499 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
15500 );
15501 assert!(
15502 inter_screen > 0,
15503 "no inter frame set allow_screen_content_tools"
15504 );
15505 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
15506 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
15507 assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
15508 }
15509 if have_ffmpeg() {
15510 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
15511 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
15512 assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
15513 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
15514 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
15515 }
15516 }
15517
15518 // The other half of the keep rule: film-shaped content leaves the
15519 // detector (and so the whole sequence header) alone.
15520 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
15521 assert!(!film.screen, "the detector fired on the film-shaped test card");
15522 }
15523
15524 /// The lane's keep-rule measurement: the gate's own screen capture, one
15525 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
15526 /// Setting the bit forces deblocking, CDEF and loop restoration off for
15527 /// that frame, so the table is exactly the filter loss against the bytes
15528 /// the copied blocks save.
15529 #[test]
15530 #[ignore = "needs the real-library manifest and ffmpeg"]
15531 fn probe_intrabc_key_frame() {
15532 let _knobs = crate::speed::knob_write();
15533 let fctx = &crate::decode::FrameCtx::for_encoder();
15534 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
15535 .join("../../fixtures");
15536 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
15537 eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest");
15538 return;
15539 };
15540 let Some(clip) = manifest
15541 .lines()
15542 .skip(1)
15543 .filter_map(|l| l.split('\t').next())
15544 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
15545 else {
15546 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
15547 return;
15548 };
15549 let (width, height) = (1280usize, 768usize);
15550 let picture = clip_frame(clip, "0", width, height);
15551 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
15552 for q in [5u8, 20, 35, 45] {
15553 for on in [false, true] {
15554 force_intrabc(Some(on));
15555 let _ = crate::tile::take_intrabc_hits();
15556 let _ = take_intrabc_search();
15557 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
15558 let hits = crate::tile::take_intrabc_hits();
15559 let search = take_intrabc_search();
15560 eprintln!(
15561 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
15562 if encoded.allow_intrabc { "on" } else { "off" },
15563 encoded.stream.len(),
15564 psnr_all(&encoded.reconstruction, &picture),
15565 hits[0],
15566 &hits[1..],
15567 search[0], search[1], search[2],
15568 );
15569 }
15570 }
15571 force_intrabc(None);
15572 }
15573
15574 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
15575 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
15576 /// take a block vector (fire count + DV histogram, class
15577 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
15578 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
15579 /// exactly what the encoder did.
15580 #[test]
15581 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
15582 let _knobs = crate::speed::knob_write();
15583 let fctx = &crate::decode::FrameCtx::for_encoder();
15584 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
15585 // superblocks of 64) and tall enough for a source superblock row
15586 // above the blocks that copy from it.
15587 let (width, height) = (512usize, 256usize);
15588 let picture = screen_card(width, height);
15589 let _ = crate::tile::take_intrabc_hits();
15590 // The default is OFF (it measured worse on the real screen capture --
15591 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
15592 // the arm on for its own encode and puts it back straight after.
15593 force_intrabc(Some(true));
15594 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15595 force_intrabc(None);
15596 assert!(
15597 encoded.allow_intrabc,
15598 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
15599 intrabc_source_share() * 100.0
15600 );
15601 let hits = crate::tile::take_intrabc_hits();
15602 eprintln!(
15603 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
15604 hits[0],
15605 &hits[1..],
15606 intrabc_source_share() * 100.0
15607 );
15608 let search = take_intrabc_search();
15609 eprintln!(
15610 "intrabc searches {} found-valid {} won-RD {}",
15611 search[0], search[1], search[2]
15612 );
15613 assert!(
15614 hits[0] > 0,
15615 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
15616 );
15617 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
15618 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
15619 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
15620 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
15621 if !have_ffmpeg() {
15622 eprintln!("SKIP the ffmpeg half: no ffmpeg");
15623 return;
15624 }
15625 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15626 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
15627 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
15628 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
15629 }
15630
15631 /// The minimal repro that isolated the inter-residual desync: a key frame
15632 /// followed by one inter frame whose single superblock carries one
15633 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
15634 /// coefficient, its three sibling blocks all `skip: true`. Before the
15635 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
15636 /// found when processing input") even though every symbol either block
15637 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
15638 /// same coefficient syntax decodes clean on every intra key-frame gate).
15639 #[test]
15640 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
15641 let _knobs = crate::speed::knob_write();
15642 let fctx = &crate::decode::FrameCtx::for_encoder();
15643 if !have_ffmpeg() {
15644 eprintln!(
15645 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
15646 );
15647 return;
15648 }
15649 let (width, height) = (64usize, 64usize);
15650 let picture = Picture::grey(width, height);
15651 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15652
15653 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
15654 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
15655
15656 let residual_block = BlockCoeffs {
15657 luma_tx_types: Vec::new(),
15658 angle_delta_y: 0,
15659 cfl_alphas: None,
15660 filter_intra: None,
15661 luma: vec![Coeff {
15662 row: 0,
15663 col: 0,
15664 level: 4,
15665 }],
15666 u: Vec::new(),
15667 v: Vec::new(),
15668 mode: 0,
15669 uv_mode: 0,
15670 skip: false,
15671 eight: None,
15672 dv: None,
15673 palette: None,
15674 palette_uv: None,
15675 tx_depth: 0,
15676 inter: Some(InterInfo {
15677 ref1: None,
15678 mv1: (0, 0),
15679 ref_frame: crate::mvstack::LAST_FRAME,
15680 mode: InterMode::NearestMv,
15681 mv: (0, 0),
15682 ref_mv_idx: 0,
15683 }),
15684 motion_mode: 0,
15685 };
15686 let skipped_block = BlockCoeffs {
15687 skip: true,
15688 inter: Some(InterInfo {
15689 ref1: None,
15690 mv1: (0, 0),
15691 ref_frame: crate::mvstack::LAST_FRAME,
15692 mode: InterMode::NearestMv,
15693 mv: (0, 0),
15694 ref_mv_idx: 0,
15695 }),
15696 ..BlockCoeffs::default()
15697 };
15698 let blocks = vec![
15699 Quadrant::Whole(residual_block),
15700 Quadrant::Whole(skipped_block.clone()),
15701 Quadrant::Whole(skipped_block.clone()),
15702 Quadrant::Whole(skipped_block),
15703 ];
15704 // lane-av1obmc: the header this tile is decoded under carries
15705 // `is_motion_mode_switchable`, so the writer must be armed with it
15706 // too or the decoder reads a `motion_mode` symbol nobody wrote.
15707 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
15708 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
15709 let tile =
15710 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
15711 .unwrap();
15712
15713 // `key.stream` is already a temporal delimiter, the sequence header
15714 // and the key frame's own OBU (`encode_key_frame` built it from the
15715 // same `key_frame_headers(width, height, 100)` this test calls), so
15716 // the inter frame's OBU is appended straight onto it rather than
15717 // re-deriving the key frame's tile bytes.
15718 let mut stream = key.stream.clone();
15719 stream.extend_from_slice(&temporal_delimiter());
15720 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
15721
15722 ffmpeg_decode_sequence(&stream, width, height, 2);
15723 }
15724
15725 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
15726 /// frame size an AV1 decoder allocates, not necessarily the render size
15727 /// (see [`a_frame_round_trips_at_its_own_size`]).
15728 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
15729 // Distinct per call, not per process: the test binary runs callers on
15730 // parallel threads, and a shared name lets one test's cleanup delete
15731 // the stream another test's ffprobe is still reading.
15732 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
15733 let path = std::env::temp_dir().join(format!(
15734 "ec-av1-probe-{}-{}.obu",
15735 std::process::id(),
15736 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
15737 ));
15738 let _ = std::fs::remove_file(&path);
15739 std::fs::write(&path, stream).expect("writing the probe stream");
15740 let out = Command::new("ffprobe")
15741 .args([
15742 "-v",
15743 "error",
15744 "-f",
15745 "obu",
15746 "-select_streams",
15747 "v:0",
15748 "-show_entries",
15749 "stream=width,height",
15750 "-of",
15751 "csv=p=0",
15752 ])
15753 .arg(&path)
15754 .output()
15755 .expect("ffprobe failed to run");
15756 let _ = std::fs::remove_file(&path);
15757 assert!(
15758 out.status.success(),
15759 "ffprobe refused the stream: {}",
15760 String::from_utf8_lossy(&out.stderr)
15761 );
15762 let text = String::from_utf8_lossy(&out.stdout);
15763 let mut fields = text.trim().split(',');
15764 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
15765 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
15766 (width, height)
15767 }
15768
15769 /// lane-av1cap: the final filter replay against the capture decode it
15770 /// replaced, at the block-padded and straddling sizes the whole-frame
15771 /// tests cover -- `set_verify_final_replay` makes
15772 /// [`pick_and_apply_filters`] run both on every frame and assert, per
15773 /// frame, that the spliced picture and the two filter stages the
15774 /// restoration search reads are bit-identical over the frame's own crop.
15775 #[test]
15776 fn the_final_filter_replay_matches_the_capture_decode_at_odd_sizes() {
15777 let _knobs = crate::speed::knob_write();
15778 let fctx = &crate::decode::FrameCtx::for_encoder();
15779 crate::decode::set_verify_final_replay(true);
15780 for &(width, height) in
15781 &[(64usize, 56usize), (216, 96), (192, 120), (640, 352), (1280, 720)]
15782 {
15783 eprintln!("--- {width}x{height}");
15784 let picture = test_card(width, height);
15785 let _ = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15786 }
15787 crate::decode::set_verify_final_replay(false);
15788 }
15789
15790 /// A key frame at an arbitrary even size round-trips through ffmpeg over
15791 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
15792 /// picture's own size, and what ffmpeg decodes over that same top-left
15793 /// region equals it sample for sample.
15794 ///
15795 /// This does not check that `ffprobe` reports the picture's own size,
15796 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
15797 /// (block-padded) frame size, the same one libaom itself would code for
15798 /// a non-block-aligned picture. `render_width`/`render_height` (which
15799 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
15800 /// decoder is required to crop pixels by, and ffmpeg's does not --
15801 /// checked empirically against ffprobe here and against a real libaom
15802 /// encode separately. So the coded size, not the render size, is what
15803 /// `ffprobe` is asserted to report below.
15804 #[test]
15805 fn a_frame_round_trips_at_its_own_size() {
15806 let _knobs = crate::speed::knob_read();
15807 let fctx = &crate::decode::FrameCtx::for_encoder();
15808 if !have_ffmpeg() {
15809 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
15810 return;
15811 }
15812 // 854x480 is covered separately by
15813 // `an_854x480_picture_round_trips_through_its_padding`, which its own
15814 // doc comment explains was worth keeping as its own test.
15815 for &(width, height) in &[
15816 (1920usize, 1080usize),
15817 (640, 352),
15818 (1280, 720),
15819 (64, 56),
15820 (854, 480),
15821 (216, 96),
15822 (192, 120),
15823 ] {
15824 let picture = test_card(width, height);
15825 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15826 assert_eq!(
15827 (encoded.reconstruction.width, encoded.reconstruction.height),
15828 (width, height),
15829 "{width}x{height}: reconstruction is cropped to the picture's own size"
15830 );
15831 assert_eq!(
15832 ffprobe_size(&encoded.stream),
15833 (width as u32, height as u32),
15834 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
15835 );
15836 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15837 assert_eq!(
15838 decoded.y, encoded.reconstruction.y,
15839 "{width}x{height}: luma"
15840 );
15841 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
15842 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
15843 }
15844 }
15845
15846 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
15847 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
15848 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
15849 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
15850 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
15851 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
15852 /// col`) -- different bits of an 8-byte table, one true, one false. The
15853 /// stride libaom indexes by is fixed at its compile-time maximum
15854 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
15855 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
15856 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
15857 /// row/col position within the (correctly 64-relative) superblock stayed
15858 /// right, only the table's own row stride was wrong. Fixed in
15859 /// `Reach::table_stride`; not an arithmetic-coder desync (an
15860 /// EC_RNG-per-symbol trace against the same debug decoder found the
15861 /// bitstream byte-for-byte identical to libaom's across all 51188
15862 /// symbols of this frame before this bug was found).
15863 ///
15864 /// Since the frame header started writing the true (unpadded) display
15865 /// size into `frame_width`/`frame_height` rather than the padded coded
15866 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
15867 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
15868 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
15869 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
15870 /// the header's own size before output).
15871 #[test]
15872 fn an_854x480_picture_round_trips_through_its_padding() {
15873 let _knobs = crate::speed::knob_read();
15874 let fctx = &crate::decode::FrameCtx::for_encoder();
15875 if !have_ffmpeg() {
15876 return;
15877 }
15878 let (width, height) = (854usize, 480usize);
15879 let picture = test_card(width, height);
15880 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
15881 let decoded = ffmpeg_decode(&encoded.stream, width, height);
15882 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
15883 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
15884 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
15885 }
15886
15887 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
15888 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
15889 /// superblock, both partition tables:
15890 ///
15891 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
15892 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
15893 /// wiring the TU sites onto it changes no existing stream;
15894 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
15895 /// NULL in libaom because that lookup never happens, and reading a
15896 /// 4x4 row out of the three-row vert tables is what crashed a real
15897 /// `--enable-tx-size-search=1` stream (r2);
15898 /// 3. and it must be the BLOCK's vert answer where the two tables
15899 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
15900 /// row 1, column 0 reads its above-right samples from the 8x8 to its
15901 /// upper right, which a vertical AB partition codes AFTER it
15902 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
15903 #[test]
15904 fn of_tu_follows_the_block_row_including_under_vert_ab() {
15905 let fctx = &crate::decode::FrameCtx::for_encoder();
15906 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
15907 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
15908 // above-right answer is the BLOCK's, which is the whole reason a unit
15909 // asks the block instead of looking itself up (the
15910 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
15911 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
15912 assert_eq!(
15913 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
15914 plain.above_right,
15915 "ordinary table: the top-right TX4 unit takes the block's row"
15916 );
15917 let guard = Reach::vert_ab_partition();
15918 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
15919 assert_eq!(
15920 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
15921 vert.above_right,
15922 "vert AB: the unit follows the vert row the block just picked"
15923 );
15924 assert_ne!(
15925 plain.above_right, vert.above_right,
15926 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
15927 );
15928 drop(guard);
15929 }
15930
15931 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
15932 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
15933 /// reconintra.c`), for every 16x16 and 32x32 block position across three
15934 /// superblocks square -- interior and every superblock edge (top row,
15935 /// left column, right column, bottom row) both sizes reach. Written to
15936 /// catch the class the `table_stride` bug was: an index stride silently
15937 /// wrong for one block size while looking plausible for the other.
15938 #[test]
15939 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
15940 // lane-b128m: this test's oracle is libaom's 64-SUPERBLOCK table, so
15941 // it pins the 64 reach explicitly instead of following the process's
15942 // own superblock knob (`for_encoder`), which made it red under
15943 // `EC_AV1_SB128=1` for no defect of the code under test.
15944 let fctx = &crate::decode::FrameCtx::new();
15945 // Transcribed from has_top_right/has_bottom_left's row_off==0,
15946 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
15947 // 128px reference grid) pinned as libaom pins it, independent of the
15948 // 64px superblock this crate actually codes.
15949 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
15950 if y == 0 || x + side >= width {
15951 return false;
15952 }
15953 let (row, col, per_side) = (
15954 (y % SUPERBLOCK) / side,
15955 (x % SUPERBLOCK) / side,
15956 SUPERBLOCK / side,
15957 );
15958 if row == 0 {
15959 return true;
15960 }
15961 if col + 1 == per_side {
15962 return false;
15963 }
15964 let stride = 128 / side;
15965 let index = row * stride + col;
15966 let table = if side == BLOCK {
15967 [95u8, 87].to_vec()
15968 } else {
15969 vec![255, 85, 119, 85, 127, 85, 119, 85]
15970 };
15971 (table[index / 8] >> (index % 8)) & 1 != 0
15972 }
15973
15974 fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool {
15975 if x == 0 || y + side >= height {
15976 return false;
15977 }
15978 let (row, col, per_side) = (
15979 (y % SUPERBLOCK) / side,
15980 (x % SUPERBLOCK) / side,
15981 SUPERBLOCK / side,
15982 );
15983 if col == 0 {
15984 return row * side + side < SUPERBLOCK;
15985 }
15986 if row + 1 == per_side {
15987 return false;
15988 }
15989 let stride = 128 / side;
15990 let index = row * stride + col;
15991 let table = if side == BLOCK {
15992 [4u8, 4].to_vec()
15993 } else {
15994 vec![84, 16, 84, 0, 84, 16, 84, 0]
15995 };
15996 (table[index / 8] >> (index % 8)) & 1 != 0
15997 }
15998
15999 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
16000 for side in [16usize, BLOCK] {
16001 for y in (0..height).step_by(side) {
16002 for x in (0..width).step_by(side) {
16003 let reach = Reach::of(side, x, y, width, height, fctx);
16004 assert_eq!(
16005 reach.above_right,
16006 libaom_top_right(side, x, y, width, height),
16007 "side={side} x={x} y={y}: above_right"
16008 );
16009 assert_eq!(
16010 reach.below_left,
16011 libaom_bottom_left(side, x, y, height, fctx),
16012 "side={side} x={x} y={y}: below_left"
16013 );
16014 }
16015 }
16016 }
16017 }
16018
16019 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
16020 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
16021 /// column inside the superblock) may read the below-left samples the
16022 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
16023 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
16024 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
16025 /// stream that partitions that small first hits the still-refused
16026 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
16027 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
16028 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
16029 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
16030 /// pixels -- lane-palette2 r12: the square multi-TU path used the
16031 /// standalone-block tables instead of this rule and granted a 16x16
16032 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
16033 #[test]
16034 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
16035 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
16036 // *_count_unit = tx size / 4.
16037 fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
16038 let (plane_bw_unit, count) = (bw / 4, tx / 4);
16039 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
16040 let _ = bh;
16041 if row_off_u > 0 {
16042 col_off_u + count < plane_bw_unit
16043 } else if col_off_u + count < plane_bw_unit {
16044 true
16045 } else {
16046 blk
16047 }
16048 }
16049 fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
16050 let (plane_bh_unit, count) = (bh / 4, tx / 4);
16051 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
16052 let _ = bw;
16053 if col_off_u > 0 {
16054 false
16055 } else if row_off_u + count < plane_bh_unit {
16056 true
16057 } else {
16058 blk
16059 }
16060 }
16061 for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
16062 for &tx in &[4usize, 8, 16, 32] {
16063 if tx > bw.min(bh) {
16064 continue;
16065 }
16066 for row_off in (0..bh).step_by(tx) {
16067 for col_off in (0..bw).step_by(tx) {
16068 for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] {
16069 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
16070 assert_eq!(
16071 got.above_right,
16072 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
16073 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
16074 );
16075 assert_eq!(
16076 got.below_left,
16077 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
16078 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
16079 );
16080 }
16081 }
16082 }
16083 }
16084 }
16085 }
16086
16087 #[test]
16088 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
16089 let fctx = &crate::decode::FrameCtx::for_encoder();
16090 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
16091 // Interior superblock, so neither the frame edge nor the col == 0 /
16092 // last-row early returns answer instead of the table.
16093 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
16094 let mut flipped = 0;
16095 for row in 0..8 {
16096 for col in 1..8 {
16097 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
16098 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
16099 let vert = {
16100 let _guard = Reach::vert_ab_partition();
16101 Reach::of(8, x, y, width, height, fctx).below_left
16102 };
16103 // The TR square of a VERT_A/_B sits at an even row, odd
16104 // column; every other slot must be untouched by the guard.
16105 if row % 2 == 0 && col % 2 == 1 {
16106 assert!(!raster, "raster below_left at row={row} col={col}");
16107 assert!(vert, "vert below_left at row={row} col={col}");
16108 flipped += 1;
16109 } else {
16110 assert_eq!(raster, vert, "guard moved row={row} col={col}");
16111 }
16112 }
16113 }
16114 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
16115 // The guard is scoped: it must not leak past its own block.
16116 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
16117 }
16118
16119 /// An odd width or height is refused by name, not by however the padder
16120 /// or the block coder would happen to fail on it.
16121 #[test]
16122 fn odd_dimensions_are_refused() {
16123 let _knobs = crate::speed::knob_read();
16124 let fctx = &crate::decode::FrameCtx::for_encoder();
16125 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
16126 let picture = Picture::grey(width, height);
16127 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
16128 .expect_err(&format!("{width}x{height} is odd and must be refused"));
16129 assert!(
16130 err.to_string().contains("even"),
16131 "{width}x{height}: error was {err}"
16132 );
16133 }
16134 }
16135
16136 /// A sequence at a size that is not a multiple of the block grid decodes
16137 /// to the right frame count and the right size for every frame,
16138 /// including the inter frames whose reference is the previous frame's
16139 /// own (padded) reconstruction.
16140 #[test]
16141 fn sequence_round_trips_at_a_non_multiple_size() {
16142 let _knobs = crate::speed::knob_read();
16143 let fctx = &crate::decode::FrameCtx::for_encoder();
16144 if !have_ffmpeg() {
16145 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
16146 return;
16147 }
16148 let (width, height) = (160usize, 96usize);
16149 let pictures: Vec<Picture> = (0..3)
16150 .map(|i| panned_test_card(width, height, i * 3))
16151 .collect();
16152 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16153 assert_eq!(encoded.frames.len(), 3);
16154 for (i, frame) in encoded.frames.iter().enumerate() {
16155 assert_eq!(
16156 (frame.reconstruction.width, frame.reconstruction.height),
16157 (width, height),
16158 "frame {i}: reconstruction size"
16159 );
16160 }
16161 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
16162 // true (display) size a sequence's frames share, not the padded one.
16163 assert_eq!(
16164 ffprobe_size(&encoded.stream),
16165 (width as u32, height as u32),
16166 "sequence: ffprobe reports the true (display) size"
16167 );
16168 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
16169 assert_eq!(decoded.len(), 3, "decoded frame count");
16170 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16171 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16172 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16173 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16174 }
16175 }
16176
16177 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
16178 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
16179 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
16180 /// `pos + side_mi / 2 < bound` boundary), which is the case
16181 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
16182 /// refusing. A key frame alone already covered this size; this proves the
16183 /// inter tile writer's parity with it across a real multi-frame export.
16184 #[test]
16185 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
16186 let _knobs = crate::speed::knob_read();
16187 let fctx = &crate::decode::FrameCtx::for_encoder();
16188 if !have_ffmpeg() {
16189 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
16190 return;
16191 }
16192 let (width, height) = (1280usize, 720usize);
16193 let pictures: Vec<Picture> = (0..3)
16194 .map(|i| panned_test_card(width, height, i * 3))
16195 .collect();
16196 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16197 assert_eq!(encoded.frames.len(), 3);
16198 for (i, frame) in encoded.frames.iter().enumerate() {
16199 assert_eq!(
16200 (frame.reconstruction.width, frame.reconstruction.height),
16201 (width, height),
16202 "frame {i}: reconstruction size"
16203 );
16204 }
16205 assert_eq!(
16206 ffprobe_size(&encoded.stream),
16207 (width as u32, height as u32),
16208 "ffprobe reports the true (display) 1280x720 size"
16209 );
16210 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
16211 assert_eq!(decoded.len(), 3, "decoded frame count");
16212 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16213 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16214 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16215 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16216 }
16217 }
16218
16219 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
16220 /// leaf's own half (`has_half` at the SUB level) itself straddles the
16221 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
16222 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
16223 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
16224 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
16225 /// straddling-16x16 branch), so an inter frame no longer refuses this
16226 /// size either. This only proves the encoder does not error out -- see
16227 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
16228 /// decoder-clean proof (a 3-frame sequence, so the inter path is
16229 /// actually exercised).
16230 #[test]
16231 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
16232 let _knobs = crate::speed::knob_read();
16233 let fctx = &crate::decode::FrameCtx::for_encoder();
16234 let (width, height) = (640usize, 360usize);
16235 let picture = Picture::grey(width, height);
16236 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
16237
16238 // `encode_sequence`'s second frame is the inter path: same size, now
16239 // wired the same way.
16240 let pictures = vec![picture.clone(), picture];
16241 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
16242 .expect("inter frame now codes the mod-32==8 straddle too");
16243 }
16244
16245 /// The r15 fix at production size: three 640x360 key frames (inter is
16246 /// still refused at this size, per the test above, so this stands in for
16247 /// the charter's "3-frame sequence" using three independent key frames of
16248 /// shifted content), each proven decoder-clean through ffmpeg rather than
16249 /// only encoder-clean.
16250 #[test]
16251 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
16252 let _knobs = crate::speed::knob_read();
16253 let fctx = &crate::decode::FrameCtx::for_encoder();
16254 if !have_ffmpeg() {
16255 eprintln!(
16256 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
16257 no ffmpeg"
16258 );
16259 return;
16260 }
16261 let (width, height) = (640usize, 360usize);
16262 for shift in [0i64, 7, 19] {
16263 let picture = panned_test_card(width, height, shift);
16264 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16265 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16266 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
16267 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
16268 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
16269 }
16270 }
16271
16272 /// The 640x360 straddle class, but through the inter path an actual
16273 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
16274 /// proves the leaf-8 inter stream this round wires up is not just
16275 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
16276 #[test]
16277 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
16278 let _knobs = crate::speed::knob_read();
16279 let fctx = &crate::decode::FrameCtx::for_encoder();
16280 if !have_ffmpeg() {
16281 eprintln!(
16282 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
16283 );
16284 return;
16285 }
16286 let (width, height) = (640usize, 360usize);
16287 let pictures: Vec<Picture> = (0..4)
16288 .map(|i| panned_test_card(width, height, i * 3))
16289 .collect();
16290 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
16291 assert_eq!(encoded.frames.len(), 4);
16292 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
16293 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
16294 }
16295 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
16296 assert_eq!(decoded.len(), 4, "decoded frame count");
16297 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
16298 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
16299 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
16300 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
16301 }
16302 }
16303
16304 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
16305 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
16306 let out = Command::new("ffmpeg")
16307 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
16308 .args(["-vf", &format!("scale={width}:{height}")])
16309 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
16310 .output()
16311 .expect("ffmpeg failed to run");
16312 assert!(
16313 out.status.success(),
16314 "ffmpeg: {}",
16315 String::from_utf8_lossy(&out.stderr)
16316 );
16317 let (luma, chroma) = (width * height, width * height / 4);
16318 assert_eq!(
16319 out.stdout.len(),
16320 luma + 2 * chroma,
16321 "expected one 4:2:0 frame"
16322 );
16323 Picture {
16324 width,
16325 height,
16326 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
16327 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
16328 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
16329 }
16330 }
16331
16332 /// Prints what the mode search saves over DC prediction alone, for the
16333 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
16334 /// weight the search puts on rate can be swept.
16335 #[test]
16336 #[ignore = "a sweep, not a gate"]
16337 fn probe_lambda() {
16338 let _knobs = crate::speed::knob_read();
16339 let fctx = &crate::decode::FrameCtx::for_encoder();
16340 let mut pictures = vec![
16341 ("test card".to_string(), test_card(160, 96)),
16342 ("stripes".to_string(), stripes(160, 96, true)),
16343 ];
16344 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
16345 for entry in clips.split(':').filter(|e| !e.is_empty()) {
16346 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
16347 let name = path.rsplit('/').next().unwrap_or(path).to_string();
16348 pictures.push((name, clip_frame(path, skip, 640, 352)));
16349 }
16350 }
16351 for (name, picture) in pictures {
16352 let dc = ladder(&picture, &[DC_PRED], fctx);
16353 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
16354 println!(
16355 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
16356 bd_rate(&dc, &searched) * 100.0,
16357 10f64.powf(searched[1].1),
16358 searched[1].0,
16359 10f64.powf(dc[1].1),
16360 dc[1].0,
16361 );
16362 }
16363 }
16364
16365 /// Prints the whole mode-search ladder, so two builds of the search can be
16366 /// compared against each other rather than each against its own baseline.
16367 #[test]
16368 #[ignore = "a sweep, not a gate"]
16369 fn probe_ladder() {
16370 let _knobs = crate::speed::knob_read();
16371 let fctx = &crate::decode::FrameCtx::for_encoder();
16372 for (name, picture) in sweep_pictures() {
16373 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
16374 let points = all
16375 .iter()
16376 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
16377 .collect::<Vec<_>>()
16378 .join(" ");
16379 println!("ladder {name}: {points}");
16380 }
16381 }
16382
16383 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
16384 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
16385 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
16386 #[test]
16387 #[ignore = "a sweep, not a gate"]
16388 fn probe_split() {
16389 let _knobs = crate::speed::knob_read();
16390 let fctx = &crate::decode::FrameCtx::for_encoder();
16391 for (name, picture) in sweep_pictures() {
16392 let ladder = |split: bool| {
16393 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
16394 .iter()
16395 .map(|&q| {
16396 let encoded = encode_key_frame_inner(
16397 &picture,
16398 q,
16399 0.5,
16400 &KEY_FRAME_MODES,
16401 split,
16402 (picture.width, picture.height),
16403 unspecified_color_config(), fctx,
16404 )
16405 .unwrap();
16406 (
16407 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
16408 (encoded.stream.len() as f64).log10(),
16409 )
16410 })
16411 .collect();
16412 points.sort_by(|a, b| a.0.total_cmp(&b.0));
16413 points
16414 };
16415 let (whole, split) = (ladder(false), ladder(true));
16416 let blocks = encode_key_frame_inner(
16417 &picture,
16418 90,
16419 0.5,
16420 &KEY_FRAME_MODES,
16421 true,
16422 (picture.width, picture.height),
16423 unspecified_color_config(), fctx,
16424 )
16425 .unwrap()
16426 .modes
16427 .len();
16428 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
16429 println!(
16430 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
16431 bd_rate(&whole, &split) * 100.0
16432 );
16433 }
16434 }
16435
16436 /// A striped picture, running one way or the other. The stripes are what
16437 /// separates a vertical predictor from a horizontal one: a mode search
16438 /// reading a transposed edge would pick the wrong one of the pair, which no
16439 /// symmetric picture would show.
16440 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
16441 let mut picture = Picture::grey(width, height);
16442 for y in 0..height {
16443 for x in 0..width {
16444 let along = if vertical { x } else { y };
16445 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
16446 }
16447 }
16448 picture
16449 }
16450
16451 /// Where two planes first disagree, and by how much: a mismatch reported as
16452 /// a position says which block and which sample of it went wrong, which a
16453 /// pair of thousand-sample arrays does not.
16454 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
16455 let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
16456 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
16457 Some(format!(
16458 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
16459 i % width,
16460 i / width,
16461 ours[i],
16462 theirs[i]
16463 ))
16464 }
16465
16466 /// Every mode the encoder offers has to predict what the decoder predicts,
16467 /// not just the ones a particular picture happens to choose: each is forced
16468 /// over a whole picture and the reconstruction gated against ffmpeg.
16469 #[test]
16470 fn every_mode_decodes_to_what_the_encoder_predicted() {
16471 let _knobs = crate::speed::knob_write();
16472 let fctx = &crate::decode::FrameCtx::for_encoder();
16473 if !have_ffmpeg() {
16474 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
16475 return;
16476 }
16477 // A mode ablation measures the MODE search: a filter-intra block is
16478 // coded `DC_PRED` whatever mode the arm forces, so it would fail the
16479 // "the encoder coded something else" check for a reason that is not
16480 // about the mode search at all.
16481 force_filter_intra(Some(false));
16482 // 128 wide is a whole number of superblocks and 160 is not: the last
16483 // superblock of a 160-wide row is half a one, whose blocks have no
16484 // above-right samples inside the frame at all.
16485 for (width, height) in [(128, 96), (160, 96)] {
16486 let picture = test_card(width, height);
16487 for mode in KEY_FRAME_MODES {
16488 let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap();
16489 let decoded = ffmpeg_decode(&encoded.stream, width, height);
16490 for (plane, ours, theirs, stride) in [
16491 ("luma", &encoded.reconstruction.y, &decoded.y, width),
16492 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
16493 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
16494 ] {
16495 assert!(
16496 first_difference(ours, theirs, stride).is_none(),
16497 "{width}x{height} mode {mode}, {plane}: {}",
16498 first_difference(ours, theirs, stride).unwrap()
16499 );
16500 }
16501 assert!(
16502 encoded.modes.iter().all(|&m| m == mode),
16503 "mode {mode}: the encoder coded something else"
16504 );
16505 }
16506 }
16507 }
16508
16509 /// The search has to follow the picture: vertical stripes are cheapest
16510 /// predicted from the row above, horizontal ones from the column to the
16511 /// left. Reading the edges the other way round would swap the two answers
16512 /// while leaving every fidelity gate intact.
16513 #[test]
16514 fn the_search_picks_the_direction_the_picture_runs() {
16515 let _knobs = crate::speed::knob_write();
16516 let fctx = &crate::decode::FrameCtx::for_encoder();
16517 // Same confound as [`every_mode_decodes_to_what_the_encoder_predicted`]:
16518 // a filter-intra block is coded `DC_PRED` whatever mode the arm
16519 // offers, and these stripes are SCREEN content, where the filter arm
16520 // now searches its own transform depth (lane-fitu) and wins outright
16521 // -- which says nothing about the mode search this gate measures.
16522 force_filter_intra(Some(false));
16523 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
16524 let picture = stripes(128, 96, vertical);
16525 // Only the pair, because on stripes a third mode predicts exactly
16526 // what the right one of the pair does -- PAETH reads the corner and
16527 // the left column, which a striped picture makes equal -- and the
16528 // tie then goes to whichever is cheaper to name, which is not what
16529 // this gate is about.
16530 let encoded =
16531 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
16532 // The first block of the picture has neither neighbour, so it
16533 // cannot tell the modes apart; every other one can.
16534 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
16535 assert!(
16536 picked * 2 > encoded.modes.len() - 1,
16537 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
16538 encoded.modes.len() - 1,
16539 encoded.modes
16540 );
16541 }
16542 }
16543
16544 /// What the search is for: the same picture, at the same quantizer, coded
16545 /// smaller and more faithfully than DC alone can manage.
16546 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
16547 /// between the two rate-distortion curves in log-rate against PSNR, as a
16548 /// fraction of the reference's rate. Negative means the second curve costs
16549 /// less for the same picture.
16550 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
16551 let low = reference[0].0.max(other[0].0);
16552 let high = reference[reference.len() - 1]
16553 .0
16554 .min(other[other.len() - 1].0);
16555 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
16556 // the non-directional one on the synthetic diagonals -- every point
16557 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
16558 // to integrate over any more. A curve that dominates that way has
16559 // saved everything the measure can express (the
16560 // `instrument-at-bound` class: the answer is at the instrument's own
16561 // edge, not undefined), so name it rather than panicking; anything
16562 // less clean than strict dominance still is.
16563 if high <= low {
16564 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
16565 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
16566 let dominates = other[0].0 > reference[reference.len() - 1].0
16567 && other_hi_rate <= ref_lo_rate;
16568 assert!(
16569 dominates,
16570 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
16571 );
16572 return -1.0;
16573 }
16574 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
16575 let i = curve
16576 .windows(2)
16577 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
16578 .unwrap_or(0);
16579 let (x0, y0) = curve[i];
16580 let (x1, y1) = curve[i + 1];
16581 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
16582 };
16583 let steps = 64;
16584 let mut area = 0.0;
16585 for step in 0..steps {
16586 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
16587 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
16588 }
16589 10f64.powf(area / f64::from(steps)) - 1.0
16590 }
16591
16592 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
16593 /// fidelity.
16594 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
16595 // A mode ablation measures the MODE search: the palette would code
16596 // these synthetic two-colour pictures losslessly under every arm and
16597 // leave nothing to compare (see [`force_screen`]).
16598 force_screen(Some(false));
16599 // Same reason, for the filter-intra candidate: it wins blocks under
16600 // BOTH arms of a mode ablation and so cancels the difference the
16601 // ablation measures (class `gate-recipe-confound`).
16602 force_filter_intra(Some(false));
16603 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
16604 .iter()
16605 .map(|&q| {
16606 let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
16607 (
16608 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
16609 (encoded.stream.len() as f64).log10(),
16610 )
16611 })
16612 .collect();
16613 points.sort_by(|a, b| a.0.total_cmp(&b.0));
16614 points
16615 }
16616
16617 /// What the search is for: the same pictures cost less to code at the same
16618 /// fidelity than DC prediction alone can manage. A picture that runs one
16619 /// way saves far more than a busy one, which is the shape a working
16620 /// directional pair has.
16621 #[test]
16622 fn the_search_beats_dc_alone() {
16623 let _knobs = crate::speed::knob_read();
16624 let fctx = &crate::decode::FrameCtx::for_encoder();
16625 for (name, picture, want) in [
16626 ("test card", test_card(160, 96), -0.05),
16627 ("stripes", stripes(160, 96, true), -0.40),
16628 ] {
16629 let saved = bd_rate(
16630 &ladder(&picture, &[DC_PRED], fctx),
16631 &ladder(&picture, &NON_DIRECTIONAL, fctx),
16632 );
16633 assert!(
16634 saved < want,
16635 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
16636 saved * 100.0,
16637 -want * 100.0
16638 );
16639 }
16640 }
16641
16642 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
16643 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
16644 fn sweep_pictures() -> Vec<(String, Picture)> {
16645 let mut pictures = vec![
16646 ("test card".to_string(), test_card(160, 96)),
16647 ("stripes".to_string(), stripes(160, 96, true)),
16648 ("diagonal".to_string(), diagonal(160, 96, true)),
16649 ];
16650 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
16651 for entry in clips.split(':').filter(|e| !e.is_empty()) {
16652 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
16653 let name = path.rsplit('/').next().unwrap_or(path).to_string();
16654 pictures.push((name, clip_frame(path, skip, 640, 352)));
16655 }
16656 }
16657 pictures
16658 }
16659
16660 /// What the six directional modes are worth, per picture, at whatever
16661 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
16662 /// no further, and how often the search picks one.
16663 #[test]
16664 #[ignore = "a sweep, not a gate"]
16665 fn probe_directional() {
16666 let _knobs = crate::speed::knob_write();
16667 let fctx = &crate::decode::FrameCtx::for_encoder();
16668 for (name, picture) in sweep_pictures() {
16669 let dc = ladder(&picture, &[DC_PRED], fctx);
16670 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
16671 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
16672 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
16673 let directional = encoded
16674 .modes
16675 .iter()
16676 .filter(|&&m| (3..=8).contains(&m))
16677 .count();
16678 // A picture whose ladders sit at different fidelities altogether
16679 // has no BD-rate to report -- see the flat-sample-window class.
16680 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
16681 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
16682 };
16683 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
16684 if overlap(a, b) {
16685 format!("{:+.2}%", bd_rate(a, b) * 100.0)
16686 } else {
16687 "no overlap".to_string()
16688 }
16689 };
16690 println!(
16691 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
16692 against(&flat, &all),
16693 against(&dc, &all),
16694 encoded.modes.len(),
16695 );
16696 }
16697 }
16698
16699 /// A picture whose stripes run along a diagonal, one way or the other.
16700 /// This is to the directional modes what [`stripes`] is to the vertical and
16701 /// horizontal pair: a predictor that walked the edge in the wrong direction
16702 /// would answer the two pictures the same way round.
16703 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
16704 let mut picture = Picture::grey(width, height);
16705 for y in 0..height {
16706 for x in 0..width {
16707 let along = if down_right { x + height - y } else { x + y };
16708 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
16709 }
16710 }
16711 picture
16712 }
16713
16714 /// The mode picked by the most blocks of a picture, ignoring the first
16715 /// block, which has no neighbours to tell the modes apart with.
16716 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
16717 // A mode ablation measures the MODE search: the palette would code
16718 // these synthetic two-colour pictures losslessly under every arm and
16719 // leave nothing to compare (see [`force_screen`]).
16720 force_screen(Some(false));
16721 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
16722 let blocks = &encoded.modes[1..];
16723 let mut counts = [0usize; 13];
16724 for &mode in blocks {
16725 counts[usize::from(mode)] += 1;
16726 }
16727 let (mode, count) = counts
16728 .iter()
16729 .enumerate()
16730 .max_by_key(|&(_, count)| *count)
16731 .expect("thirteen modes");
16732 (mode as u8, *count, blocks.len())
16733 }
16734
16735 /// The search has to follow a diagonal the way it runs: stripes down and to
16736 /// the right are cheapest predicted at 135 degrees, stripes down and to the
16737 /// left at 45. A walk that stepped the wrong way along the edge, or read
16738 /// the above row where it should read the left column, would swap these.
16739 #[test]
16740 fn the_search_picks_the_diagonal_the_picture_runs() {
16741 let _knobs = crate::speed::knob_write();
16742 let fctx = &crate::decode::FrameCtx::for_encoder();
16743 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
16744 let picture = diagonal(160, 96, down_right);
16745 let (mode, count, blocks) = favourite_mode(&picture, fctx);
16746 assert_eq!(
16747 mode, want,
16748 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
16749 );
16750 }
16751 }
16752
16753 /// What the directional modes are for: a picture that runs along a diagonal
16754 /// costs far less to code with them than the seven that read only their own
16755 /// edges can manage, and a picture that runs no particular way costs no
16756 /// more. The second half is the one that bites: a mode set the search
16757 /// cannot price is a mode set that loses rate on content that does not want
16758 /// it, which is what costing the mode symbol is for.
16759 #[test]
16760 fn the_diagonals_beat_the_modes_that_read_no_further() {
16761 let _knobs = crate::speed::knob_read();
16762 let fctx = &crate::decode::FrameCtx::for_encoder();
16763 for (name, picture, want) in [
16764 ("down-right", diagonal(160, 96, true), -0.20),
16765 ("down-left", diagonal(160, 96, false), -0.20),
16766 ("test card", test_card(160, 96), 0.01),
16767 ] {
16768 let saved = bd_rate(
16769 &ladder(&picture, &NON_DIRECTIONAL, fctx),
16770 &ladder(&picture, &KEY_FRAME_MODES, fctx),
16771 );
16772 assert!(
16773 saved < want,
16774 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
16775 saved * 100.0,
16776 -want * 100.0
16777 );
16778 }
16779 }
16780
16781 /// A mode the encoder cannot predict must be refused rather than coded as
16782 /// something else, and a search with nothing to choose from likewise.
16783 #[test]
16784 fn a_mode_the_encoder_cannot_predict_is_refused() {
16785 let _knobs = crate::speed::knob_read();
16786 let fctx = &crate::decode::FrameCtx::for_encoder();
16787 let picture = test_card(64, 64);
16788 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
16789 .unwrap_err()
16790 .to_string();
16791 assert!(
16792 message.contains("intra mode 13"),
16793 "the refusal must name the mode, got {message}"
16794 );
16795 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
16796 }
16797
16798 /// The picture that comes back is the picture that went in, to within the
16799 /// quantizer. A prediction that read the wrong neighbours, or a block
16800 /// written into the wrong place, would still decode to what the encoder
16801 /// reconstructed — it is this gate that says the reconstruction is of the
16802 /// right picture.
16803 #[test]
16804 fn the_encoded_picture_is_the_one_that_went_in() {
16805 let _knobs = crate::speed::knob_read();
16806 let fctx = &crate::decode::FrameCtx::for_encoder();
16807 let picture = test_card(160, 96);
16808 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16809 let luma = psnr(&encoded.reconstruction.y, &picture.y);
16810 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
16811 for (plane, (got, want)) in [
16812 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
16813 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
16814 ]
16815 .iter()
16816 .enumerate()
16817 {
16818 let chroma = psnr(got, want);
16819 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
16820 }
16821 }
16822
16823 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
16824 /// does the opposite. Both are monotone, which is what a rate-distortion
16825 /// loop above this will assume.
16826 #[test]
16827 fn fidelity_and_rate_move_with_the_quantizer() {
16828 let _knobs = crate::speed::knob_read();
16829 let fctx = &crate::decode::FrameCtx::for_encoder();
16830 let picture = test_card(128, 128);
16831 let mut previous: Option<(usize, f64)> = None;
16832 for &q in &[70u8, 90, 110] {
16833 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
16834 let quality = psnr(&encoded.reconstruction.y, &picture.y);
16835 if let Some((bytes, better)) = previous {
16836 assert!(
16837 encoded.stream.len() < bytes,
16838 "q {q}: {} bytes",
16839 encoded.stream.len()
16840 );
16841 assert!(quality < better, "q {q}: PSNR {quality}");
16842 }
16843 previous = Some((encoded.stream.len(), quality));
16844 }
16845
16846 // The deadzone half of this claim lives in
16847 // `transform::tests::a_wider_deadzone_codes_fewer_coefficients` now:
16848 // with the rate-distortion pass ([`crate::tile::rdoq`]) deciding
16849 // every zeroing, the deadzone no longer moves a coded stream
16850 // monotonically (the i64 + rdoq merge read 318 bytes at 0.3 against
16851 // fewer at 0.5 on this 128x128 card), and that is the pass doing its
16852 // job, not a quantiser defect.
16853
16854 // Bytes must not jump up across a q-context boundary: a wrong CDF
16855 // table for the far side would show up as a rate discontinuity here,
16856 // even though a coarser quantizer always codes no more than a finer
16857 // one on the same picture.
16858 //
16859 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
16860 // chroma searches its own mode, a coarser quantizer can pick a
16861 // *different* uv_mode on a block whose modes now cost nearly the
16862 // same, and the search prices that symbol against the static default
16863 // CDF while the writer codes it against an adapted one -- 311 -> 319
16864 // bytes at q 120->121 on this picture. The table this gate is really
16865 // watching would move the rate by far more than the mode churn does.
16866 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
16867 // same block can also change transform DEPTH between two neighbouring
16868 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
16869 // symbol is priced off the static CDF row 0 for the same reason the
16870 // uv_mode one is.
16871 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
16872 // path is pricing through the adapting CDF state (what
16873 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
16874 // drift of), after which the exact bound comes back.
16875 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
16876 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
16877 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
16878 assert!(
16879 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
16880 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
16881 );
16882 }
16883 }
16884
16885 /// A flat picture is a flat stream: every block predicts its neighbours'
16886 /// average, which is the picture's own value, and codes nothing.
16887 #[test]
16888 fn a_flat_picture_costs_almost_nothing() {
16889 let _knobs = crate::speed::knob_read();
16890 let fctx = &crate::decode::FrameCtx::for_encoder();
16891 let mut picture = Picture::grey(128, 128);
16892 picture.y.fill(97);
16893 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
16894 // The first block has no neighbour and predicts 128, so it carries a
16895 // DC; every block after it predicts 97 and carries nothing.
16896 assert!(
16897 encoded.stream.len() < 100,
16898 "{} bytes for a flat picture",
16899 encoded.stream.len()
16900 );
16901 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
16902 assert_eq!(s, 97, "sample {i} of a flat picture");
16903 }
16904 }
16905
16906 /// The sizes the encoder refuses, refused for a reason rather than by
16907 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
16908 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
16909 /// lands past the halfway point of whichever block it falls in, so
16910 /// `PARTITION_NONE` or a single gathered split flag still says everything
16911 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
16912 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
16913 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
16914 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
16915 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
16916 /// refusal here claimed otherwise and was wrong; see
16917 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
16918 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
16919 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
16920 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
16921 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
16922 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
16923 /// still refused is a malformed picture.
16924 #[test]
16925 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
16926 let _knobs = crate::speed::knob_read();
16927 let fctx = &crate::decode::FrameCtx::for_encoder();
16928 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
16929 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
16930 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
16931 .expect("36 luma columns still round up to an even MiCols");
16932
16933 let mut short = Picture::grey(64, 64);
16934 short.u.truncate(10);
16935 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
16936 }
16937
16938 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
16939 /// column half only (`has_half` false on cols, true on rows) -- exactly
16940 /// the single-axis straddle lane-av1-rect r7 wires through
16941 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
16942 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
16943 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
16944 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
16945 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
16946 /// `partition_context_lookup` entry this writer ever produces (no 4x4
16947 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
16948 /// leaf regardless of neighbour state -- our writer already agreed with
16949 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
16950 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
16951 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
16952 /// it does not regress the gate. r11 tell-for-tell traced two further,
16953 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
16954 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
16955 /// leaves, when the second leaf's true above (or left) neighbour is the
16956 /// first leaf itself -- fixed by threading the first leaf's mode into the
16957 /// second leaf's context, mi-precise, like `record_mi` already does for
16958 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
16959 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
16960 /// `reduced_tx_set` is false), but this crate's key frames set
16961 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
16962 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
16963 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
16964 /// symbol bits to desync everything after it. Fixed with a new
16965 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
16966 /// eset/size slot). Both fixes are provably correct against libaom
16967 /// source and each closed part of the gap (leaf0's `eob` went from a
16968 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
16969 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
16970 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
16971 /// (do not reuse r11's committed logs, which predate its own fixes) and
16972 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
16973 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
16974 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
16975 /// every other `write_block` caller at 16x16 and up already passes
16976 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
16977 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
16978 /// different amount of arithmetic range and derailed everything after
16979 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
16980 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
16981 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
16982 /// never updating those coarse arrays itself -- so a *second* straddling
16983 /// 16x16 quadrant stacked above or left of the first (never covered by
16984 /// r11's same-call `prev_leaf` override, which only threads state
16985 /// between the two leaves of one shared quadrant) read whatever stale
16986 /// mode sat in that slot before either leaf ran. Fixed by writing the
16987 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
16988 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
16989 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
16990 /// offset of a single unit; fixing (3)+(4) together still leaves a
16991 /// residual divergence one leaf further in -- the decoder now reads
16992 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
16993 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
16994 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
16995 /// desyncs the stream by exactly the width of one earlier symbol -- not
16996 /// yet isolated to a single named symbol. r15 found the last bug: the
16997 /// header fix from r14 explained the rng skew fully, and the remaining
16998 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
16999 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
17000 /// loop, once per leaf, so the first leaf's write clobbered the true
17001 /// external neighbour mode the second leaf of the *same* straddling
17002 /// quadrant still needed for its non-adjacency axis (a column-straddle
17003 /// case: two leaves share one `outer_at` column index, so leaf 1's
17004 /// write to `left_mode[r]` overwrote the real western neighbour before
17005 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
17006 /// doing it once, after the whole leaf loop, from the last (bottom/
17007 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
17008 #[test]
17009 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
17010 let _knobs = crate::speed::knob_read();
17011 let fctx = &crate::decode::FrameCtx::for_encoder();
17012 if !have_ffmpeg() {
17013 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
17014 return;
17015 }
17016 let (width, height) = (40usize, 32usize);
17017 let picture = test_card(width, height);
17018 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17019 assert_eq!(
17020 (encoded.reconstruction.width, encoded.reconstruction.height),
17021 (width, height)
17022 );
17023 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
17024 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
17025 }
17026 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17027 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
17028 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
17029 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
17030 }
17031
17032 /// A frame of real video, rather than a picture built to be easy.
17033 ///
17034 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
17035 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
17036 /// encoder's reconstruction has to survive the same equality gate as the
17037 /// synthetic pictures — real video reaches contexts a test card does not.
17038 #[test]
17039 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
17040 let _knobs = crate::speed::knob_read();
17041 let fctx = &crate::decode::FrameCtx::for_encoder();
17042 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
17043 eprintln!(
17044 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
17045 set EC_AV1_CLIP to a clip"
17046 );
17047 return;
17048 };
17049 if !have_ffmpeg() {
17050 eprintln!(
17051 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
17052 );
17053 return;
17054 }
17055 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
17056 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
17057 // test quick while still spanning many superblocks.
17058 let (width, height) = (640usize, 352usize);
17059 let picture = clip_frame(&clip, &skip, width, height);
17060
17061 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
17062 let decoded = ffmpeg_decode(&encoded.stream, width, height);
17063 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
17064 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
17065 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
17066 eprintln!(
17067 "{} bytes, luma PSNR {:.2} dB",
17068 encoded.stream.len(),
17069 psnr(&decoded.y, &picture.y)
17070 );
17071 }
17072
17073 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
17074 /// sequence of these is a translation a motion search can actually find
17075 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
17076 /// inter frame's rate against the key frame's is measuring the same
17077 /// picture moving, not two different pictures.
17078 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
17079 let mut picture = Picture::grey(width, height);
17080 for y in 0..height {
17081 for x in 0..width {
17082 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
17083 let gradient = sx * 200.0 / width as f64;
17084 let ripple = 30.0
17085 * (sx * std::f64::consts::PI / 23.0).sin()
17086 * (y as f64 * std::f64::consts::PI / 37.0).cos();
17087 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
17088 40.0
17089 } else {
17090 0.0
17091 };
17092 picture.y[y * width + x] =
17093 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
17094 }
17095 }
17096 for y in 0..height / 2 {
17097 for x in 0..width / 2 {
17098 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
17099 let i = y * width / 2 + x;
17100 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
17101 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
17102 }
17103 }
17104 picture
17105 }
17106
17107 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
17108 fn ffmpeg_decode_sequence(
17109 stream: &[u8],
17110 width: usize,
17111 height: usize,
17112 frames: usize,
17113 ) -> Vec<Picture> {
17114 let mut child = Command::new("ffmpeg")
17115 .args([
17116 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
17117 ])
17118 .stdin(Stdio::piped())
17119 .stdout(Stdio::piped())
17120 .stderr(Stdio::piped())
17121 .spawn()
17122 .expect("ffmpeg failed to start");
17123 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
17124 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
17125 // fills before the last input byte is written -- which is exactly what
17126 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
17127 // (measured: 45 min, both processes at 0% CPU). A write error here is
17128 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
17129 // below, are the real diagnosis.
17130 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
17131 let payload = stream.to_vec();
17132 let writer = std::thread::spawn(move || {
17133 let _ = stdin.write_all(&payload);
17134 });
17135 let out = child.wait_with_output().expect("ffmpeg failed to run");
17136 writer.join().expect("ffmpeg stdin writer thread");
17137 assert!(
17138 out.status.success(),
17139 "ffmpeg refused the stream: {}",
17140 String::from_utf8_lossy(&out.stderr)
17141 );
17142 let (luma, chroma) = (width * height, width * height / 4);
17143 let frame_bytes = luma + 2 * chroma;
17144 assert_eq!(
17145 out.stdout.len(),
17146 frame_bytes * frames,
17147 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
17148 String::from_utf8_lossy(&out.stderr)
17149 );
17150 (0..frames)
17151 .map(|i| {
17152 let base = i * frame_bytes;
17153 Picture {
17154 width,
17155 height,
17156 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
17157 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
17158 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
17159 }
17160 })
17161 .collect()
17162 }
17163
17164 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
17165 /// makes for a key frame, extended down the reference chain: each inter
17166 /// frame's reconstruction predicts from the previous frame's own decoded
17167 /// reconstruction, so a single sample of drift anywhere would propagate
17168 /// into every frame after it -- which is why every frame is checked, not
17169 /// just the last one, and why this is an equality and not a tolerance.
17170 #[test]
17171 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
17172 let _knobs = crate::speed::knob_read();
17173 let fctx = &crate::decode::FrameCtx::for_encoder();
17174 if !have_ffmpeg() {
17175 eprintln!(
17176 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
17177 );
17178 return;
17179 }
17180 let (width, height) = (128usize, 64usize);
17181 let pictures: Vec<Picture> = (0..5)
17182 .map(|i| panned_test_card(width, height, i * 3))
17183 .collect();
17184 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
17185 assert_eq!(encoded.frames.len(), 5);
17186
17187 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
17188 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17189 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
17190 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
17191 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
17192 }
17193
17194 eprintln!("frame bytes luma PSNR (dB) inter share");
17195 for (i, frame) in encoded.frames.iter().enumerate() {
17196 eprintln!(
17197 "{i:5} {:5} {:14.2} {:11.2}",
17198 frame.stream.len(),
17199 psnr(&frame.reconstruction.y, &pictures[i].y),
17200 frame.inter_block_share
17201 );
17202 }
17203 }
17204
17205 /// The same sequence through OUR OWN decoder, sample-exact against the
17206 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
17207 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
17208 /// divergence point at all, while our decoder can be traced symbol by
17209 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
17210 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
17211 /// names the first differing frame, plane and position.
17212 /// lane-sb128b: the writer used to price a `NEWMV` residual against
17213 /// `stack.pred_mv` whenever the SEARCH chose a `ref_mv_idx` the
17214 /// write-time stack could not carry, while the drl symbols signalled the
17215 /// clamped index -- so the decoder derived a DIFFERENT motion vector with
17216 /// the entropy stream still in sync, and the drift only surfaced frames
17217 /// later as a drl desync (on film B, as the encoder's own trial decode
17218 /// refusing a reference slot).
17219 ///
17220 /// The clamp needs a stack that shrinks between search and write, which
17221 /// is what a 128x128 superblock's visit order does; the counter is the
17222 /// point (class `gate-blind-to-feature`): a green round trip on a clip
17223 /// that never clamps proves nothing.
17224 ///
17225 /// `#[ignore]`: [`force_sb128`] moves a process-global.
17226 ///
17227 /// cargo test -p ec-av1 --release --lib -- --ignored \
17228 /// a_128_superblock_clip_whose_drl_index_the_write_time_stack --nocapture
17229 /// lane-b128: the 128x128 `PARTITION_NONE` root -- one block, one mode
17230 /// and one motion vector where the four 64x64 roots below spend four of
17231 /// each (cen3's L1). The counter is the gate on the fixture (class
17232 /// `gate-blind-to-feature`): a green round trip on a clip that never
17233 /// codes a 128x128 block proves nothing. RED before the search existed
17234 /// (zero such blocks coded, `tile::write_sb128_root` wrote SPLIT at every
17235 /// root by construction).
17236 ///
17237 /// Both readers: our own decoder sample-exact against the encoder's
17238 /// reconstruction (a writer/reader desync surfaces as a pixel miss or a
17239 /// refusal here, not in the BD gate) AND ffmpeg as the bitstream oracle.
17240 ///
17241 /// `#[ignore]`: [`force_sb128`] moves a process-global.
17242 ///
17243 /// cargo test -p ec-av1 --release --lib -- --ignored \
17244 /// a_128_superblock_clip_whose_root_search --nocapture
17245 #[test]
17246 #[ignore = "sets the process-global superblock size: run it alone"]
17247 fn a_128_superblock_clip_whose_root_search_codes_128x128_blocks_decodes_exact() {
17248 let _knobs = crate::speed::knob_write();
17249 if !have_ffmpeg() {
17250 eprintln!("SKIP: no ffmpeg");
17251 return;
17252 }
17253 force_sb128(true);
17254 let dir = std::env::temp_dir().join(format!("ec-av1-b128-{}", std::process::id()));
17255 std::fs::create_dir_all(&dir).unwrap();
17256 let clip = dir.join("smpte-1280x768.y4m");
17257 // A slow horizontal pan over a still pattern: whole 128x128 regions
17258 // share one motion vector, which is exactly what a 128 root can code
17259 // as one block and four 64 roots cannot.
17260 let ok = Command::new("ffmpeg")
17261 .args(["-v", "error", "-y", "-f", "lavfi"])
17262 .args(["-i", "smptebars=size=1600x768:rate=24"])
17263 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17264 .args(["-pix_fmt", "yuv420p"])
17265 .arg(&clip)
17266 .status()
17267 .expect("ffmpeg failed to run")
17268 .success();
17269 assert!(ok, "ffmpeg could not write the synthetic clip");
17270 let (width, height) = (1280usize, 768usize);
17271 let pictures =
17272 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17273 let _ = take_b128_none_hits();
17274 let _ = crate::tile::take_sb128_none_hits();
17275 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17276 let (won, coded) = (take_b128_none_hits(), crate::tile::take_sb128_none_hits());
17277 eprintln!("128x128 PARTITION_NONE blocks: search won {won}, writer coded {coded}");
17278 assert!(
17279 coded > 0,
17280 "no 128x128 block was coded on this clip, so it cannot witness the root search",
17281 );
17282 assert_eq!(won, coded, "every 128x128 root the search took must be coded as one");
17283 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17284 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17285 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17286 let recon = &frame.reconstruction;
17287 for (plane, got, want) in [
17288 ("luma", &dec.y, &recon.y),
17289 ("U", &dec.u, &recon.u),
17290 ("V", &dec.v, &recon.v),
17291 ] {
17292 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17293 assert_eq!(
17294 differ, 0,
17295 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17296 own reconstruction",
17297 got.len()
17298 );
17299 }
17300 }
17301 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17302 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17303 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17304 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17305 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17306 }
17307 }
17308
17309 /// lane-b128r: the 128 root's own RESIDUAL arm -- four TX_64X64 luma
17310 /// units interleaved with a TX_32X32 chroma pair per 64x64 mu chunk. The
17311 /// same pan the skip-only witness above uses, with the arm FORCED
17312 /// ([`force_b128_residual`]): on synthetic bars the RD picks the residual
17313 /// about once per frame, which witnesses the shape but not every context
17314 /// it reads, and forcing codes all 420 roots of the clip through it. RED
17315 /// before this lane by construction (`write_inter_block_128` refused
17316 /// every non-skip 128 block, so no such block existed to decode), and RED
17317 /// again on the first draft of the writer, whose neighbour band recorded
17318 /// `skip = true` for a block that carries a residual -- the next root's
17319 /// `skip` symbol then took CDF row 1 where the reader takes row 0.
17320 ///
17321 /// lane-b128res: the fixture's q moved 150 -> 60. The forced arm replaces
17322 /// the skip arm's cost unconditionally (that is what makes the writer see
17323 /// the residual), and the cost model moved under it since lane-b128r --
17324 /// lane-rectdq made every non-skipped root pay its delta_q group and the
17325 /// pyramid re-prices the leaves -- so at q=150, then q=90, the NONE root
17326 /// lost its partition at ALL 420 roots and the writer coded none. q=60
17327 /// puts 52 written blocks back on this clip; the `coded > 0` assert below
17328 /// is the guard that catches the next such drift.
17329 ///
17330 /// cargo test -p ec-av1 --release --lib -- --ignored \
17331 /// a_128_root_block_with_a_real_residual --nocapture
17332 #[test]
17333 #[ignore = "sets the process-global superblock size: run it alone"]
17334 fn a_128_root_block_with_a_real_residual_decodes_exact_through_both_decoders() {
17335 let _knobs = crate::speed::knob_write();
17336 if !have_ffmpeg() {
17337 eprintln!("SKIP: no ffmpeg");
17338 return;
17339 }
17340 force_sb128(true);
17341 let dir = std::env::temp_dir().join(format!("ec-av1-b128r-{}", std::process::id()));
17342 std::fs::create_dir_all(&dir).unwrap();
17343 let clip = dir.join("smpte-pan-1280x768.y4m");
17344 let ok = Command::new("ffmpeg")
17345 .args(["-v", "error", "-y", "-f", "lavfi"])
17346 .args(["-i", "smptebars=size=1600x768:rate=24"])
17347 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17348 .args(["-pix_fmt", "yuv420p"])
17349 .arg(&clip)
17350 .status()
17351 .expect("ffmpeg failed to run")
17352 .success();
17353 assert!(ok, "ffmpeg could not write the synthetic clip");
17354 let (width, height) = (1280usize, 768usize);
17355 let pictures =
17356 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17357 let _ = take_b128_residual_hits();
17358 let _ = crate::tile::take_sb128_residual_hits();
17359 force_b128_residual(true);
17360 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17361 let (won, coded) =
17362 (take_b128_residual_hits(), crate::tile::take_sb128_residual_hits());
17363 eprintln!("128x128 blocks WITH a residual: search won {won}, writer coded {coded}");
17364 assert!(
17365 coded > 0,
17366 "no 128x128 block carried a residual on this clip, so it cannot witness the arm",
17367 );
17368 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17369 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17370 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17371 let recon = &frame.reconstruction;
17372 for (plane, got, want) in [
17373 ("luma", &dec.y, &recon.y),
17374 ("U", &dec.u, &recon.u),
17375 ("V", &dec.v, &recon.v),
17376 ] {
17377 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17378 assert_eq!(
17379 differ, 0,
17380 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17381 own reconstruction",
17382 got.len()
17383 );
17384 }
17385 }
17386 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17387 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17388 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17389 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17390 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17391 }
17392 }
17393
17394 /// lane-edge128: a 128x128 root block WITH a residual on a clip whose
17395 /// CDEF search codes a per-64x64 `cdef_idx` list. `read_cdef` (spec
17396 /// 5.11.56) codes ONE literal for the block that first reaches a unit and
17397 /// copies it over every unit the block SPANS, so the four units of a 128
17398 /// root share one index -- while the encoder's CDEF search prices a
17399 /// preset per unit and its filter replay applied all four. Only the first
17400 /// reached the stream, so every decoder filtered the other three with the
17401 /// origin's strengths and the encoder's reconstruction (the picture the
17402 /// next frame predicts from) was a filter apart from what a decoder
17403 /// produces. RED before this lane on the native BD gate's bars 2160p row
17404 /// (`EC_AV1_B128RES=1`, q=90, frame 11: 8 luma and 702 chroma samples,
17405 /// the rows above the 128 superblock's own edge); the stream itself was
17406 /// always right -- ffmpeg and our own decoder agreed with each other and
17407 /// disagreed with the encoder.
17408 ///
17409 /// `take_cdef_covered_units` is the gate on the fixture (class
17410 /// `gate-blind-to-feature`): a clip whose CDEF picks one strength pair
17411 /// for the whole frame codes no literal at all and witnesses nothing.
17412 ///
17413 /// cargo test -p ec-av1 --release --lib -- --ignored \
17414 /// a_128_root_residual_block_under_a_per_unit_cdef --nocapture
17415 #[test]
17416 #[ignore = "sets the process-global superblock size: run it alone"]
17417 fn a_128_root_residual_block_under_a_per_unit_cdef_list_decodes_exact() {
17418 let _knobs = crate::speed::knob_write();
17419 if !have_ffmpeg() {
17420 eprintln!("SKIP: no ffmpeg");
17421 return;
17422 }
17423 force_sb128(true);
17424 let dir = std::env::temp_dir().join(format!("ec-av1-edge128-{}", std::process::id()));
17425 std::fs::create_dir_all(&dir).unwrap();
17426 let clip = dir.join("testsrc2-1280x768.y4m");
17427 // Detailed synthetic content: its CDEF search spends more than one
17428 // strength pair, which is what puts a `cdef_idx` literal in the tile.
17429 let ok = Command::new("ffmpeg")
17430 .args(["-v", "error", "-y", "-f", "lavfi"])
17431 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17432 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17433 .arg(&clip)
17434 .status()
17435 .expect("ffmpeg failed to run")
17436 .success();
17437 assert!(ok, "ffmpeg could not write the synthetic clip");
17438 let (width, height) = (1280usize, 768usize);
17439 let pictures =
17440 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17441 force_b128_root(true);
17442 force_b128_residual(true);
17443 let _ = crate::tile::take_sb128_residual_hits();
17444 let _ = crate::filter_search::take_cdef_covered_units();
17445 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
17446 let coded = crate::tile::take_sb128_residual_hits();
17447 let covered = crate::filter_search::take_cdef_covered_units();
17448 eprintln!(
17449 "128x128 blocks WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
17450 another unit's literal: {covered}"
17451 );
17452 assert!(coded > 0, "no 128x128 block carried a residual on this clip");
17453 assert!(
17454 covered > 0,
17455 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
17456 cannot witness the rule",
17457 );
17458 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17459 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17460 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17461 for (plane, got, want) in [
17462 ("luma", &dec.y, &frame.reconstruction.y),
17463 ("U", &dec.u, &frame.reconstruction.u),
17464 ("V", &dec.v, &frame.reconstruction.v),
17465 ] {
17466 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17467 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17468 }
17469 }
17470 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17471 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17472 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17473 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17474 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17475 }
17476 }
17477
17478 /// lane-rectres: a `PARTITION_HORZ` 128 root whose two 128x64 halves
17479 /// CARRY A RESIDUAL -- the mu-chunk shape (one TX_64X64 luma unit plus a
17480 /// TX_32X32 chroma pair per chunk) `write_inter_block_128_rect` now
17481 /// codes under `EC_AV1_RECTRES`, at the footprint the decoder's own
17482 /// mu-chunk loop reads. The arm is FORCED ([`force_b128_rectres`], the
17483 /// rect partition with [`force_b128_rect`]) so every inter root of the
17484 /// clip goes through it; the `coded > 0` assert is the guard that catches
17485 /// the next fixture drift (the whole-128 twin of this witness went RED
17486 /// twice that way).
17487 ///
17488 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17489 /// encode::tests::a_rect128_half_with_a_real_residual --nocapture
17490 #[test]
17491 #[ignore = "sets the process-global superblock size: run it alone"]
17492 fn a_rect128_half_with_a_real_residual_decodes_exact_through_both_decoders() {
17493 let _knobs = crate::speed::knob_write();
17494 if !have_ffmpeg() {
17495 eprintln!("SKIP: no ffmpeg");
17496 return;
17497 }
17498 force_sb128(true);
17499 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-{}", std::process::id()));
17500 std::fs::create_dir_all(&dir).unwrap();
17501 let clip = dir.join("smpte-pan-1280x768.y4m");
17502 let ok = Command::new("ffmpeg")
17503 .args(["-v", "error", "-y", "-f", "lavfi"])
17504 .args(["-i", "smptebars=size=1600x768:rate=24"])
17505 .args(["-vf", "crop=1280:768:'min(n*2,300)':0", "-frames:v", "8"])
17506 .args(["-pix_fmt", "yuv420p"])
17507 .arg(&clip)
17508 .status()
17509 .expect("ffmpeg failed to run")
17510 .success();
17511 assert!(ok, "ffmpeg could not write the synthetic clip");
17512 let (width, height) = (1280usize, 768usize);
17513 let pictures =
17514 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 8);
17515 force_b128_rect(1);
17516 force_b128_rectres(true);
17517 let _ = take_b128_rectres_hits();
17518 let _ = crate::tile::take_sb128_rectres_hits();
17519 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17520 let (won, coded) =
17521 (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17522 eprintln!("rect halves WITH a residual: search won {won}, writer coded {coded}");
17523 assert!(
17524 coded > 0,
17525 "no 128x64 half carried a residual on this clip, so it cannot witness the arm",
17526 );
17527 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17528 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17529 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17530 let recon = &frame.reconstruction;
17531 for (plane, got, want) in [
17532 ("luma", &dec.y, &recon.y),
17533 ("U", &dec.u, &recon.u),
17534 ("V", &dec.v, &recon.v),
17535 ] {
17536 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17537 assert_eq!(
17538 differ, 0,
17539 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17540 own reconstruction",
17541 got.len()
17542 );
17543 }
17544 }
17545 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17546 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17547 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17548 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17549 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17550 }
17551 }
17552
17553 /// lane-rectres: an AB shape (`PARTITION_HORZ_A` forced) whose THREE
17554 /// pieces carry residuals -- the 128x64 half through the two-chunk arm,
17555 /// the two 64x64 squares through the one-chunk arm (the shape libaom's
17556 /// own AB partitions earn their keep with). testsrc2 at 12 frames, the
17557 /// shipped AB witness's own recipe: an 8-frame clip parks an ARF whose
17558 /// reference picture the GOP has not produced yet, which refuses before
17559 /// any AB root is coded.
17560 ///
17561 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17562 /// encode::tests::an_ab128_piece_with_a_real_residual --nocapture
17563 #[test]
17564 #[ignore = "sets the process-global superblock size: run it alone"]
17565 fn an_ab128_piece_with_a_real_residual_decodes_exact_through_both_decoders() {
17566 let _knobs = crate::speed::knob_write();
17567 if !have_ffmpeg() {
17568 eprintln!("SKIP: no ffmpeg");
17569 return;
17570 }
17571 force_sb128(true);
17572 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-ab-{}", std::process::id()));
17573 std::fs::create_dir_all(&dir).unwrap();
17574 let clip = dir.join("testsrc2-1280x768.y4m");
17575 let ok = Command::new("ffmpeg")
17576 .args(["-v", "error", "-y", "-f", "lavfi"])
17577 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17578 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17579 .arg(&clip)
17580 .status()
17581 .expect("ffmpeg failed to run")
17582 .success();
17583 assert!(ok, "ffmpeg could not write the synthetic clip");
17584 let (width, height) = (1280usize, 768usize);
17585 let pictures =
17586 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17587 force_b128_ab(4);
17588 force_b128_rectres(true);
17589 let _ = take_b128_rectres_hits();
17590 let _ = crate::tile::take_sb128_rectres_hits();
17591 let encoded = encode_sequence(&pictures, 60, 0.5).unwrap();
17592 let (won, coded) =
17593 (take_b128_rectres_hits(), crate::tile::take_sb128_rectres_hits());
17594 eprintln!("AB pieces WITH a residual: search won {won}, writer coded {coded}");
17595 assert!(
17596 coded > 0,
17597 "no AB piece carried a residual on this clip, so it cannot witness the arm",
17598 );
17599 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17600 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17601 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17602 let recon = &frame.reconstruction;
17603 for (plane, got, want) in [
17604 ("luma", &dec.y, &recon.y),
17605 ("U", &dec.u, &recon.u),
17606 ("V", &dec.v, &recon.v),
17607 ] {
17608 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17609 assert_eq!(
17610 differ, 0,
17611 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
17612 own reconstruction",
17613 got.len()
17614 );
17615 }
17616 }
17617 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17618 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17619 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17620 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17621 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17622 }
17623 }
17624
17625 /// lane-rectres, lane-edge128's interaction on the rect shapes: a HORZ
17626 /// half WITH a residual under a clip whose CDEF search codes a
17627 /// per-64x64 `cdef_idx` list. The half codes ONE literal at its origin
17628 /// and the decoder stamps BOTH units it spans with it, so the owner map
17629 /// ([`crate::tile::cdef_unit_owner`], now extended past Whole128) has to
17630 /// collapse the pair -- exactly the bug class that broke bars 2160p at
17631 /// the whole-128 root. RED before this lane by construction: no rect
17632 /// piece could carry a residual, so no such literal existed.
17633 ///
17634 /// cargo test -p ec-av1 --release --lib -- --ignored --exact \
17635 /// encode::tests::a_rect128_residual_half_under_a_per_unit_cdef --nocapture
17636 #[test]
17637 #[ignore = "sets the process-global superblock size: run it alone"]
17638 fn a_rect128_residual_half_under_a_per_unit_cdef_list_decodes_exact() {
17639 let _knobs = crate::speed::knob_write();
17640 if !have_ffmpeg() {
17641 eprintln!("SKIP: no ffmpeg");
17642 return;
17643 }
17644 force_sb128(true);
17645 let dir = std::env::temp_dir().join(format!("ec-av1-rectres-cdef-{}", std::process::id()));
17646 std::fs::create_dir_all(&dir).unwrap();
17647 let clip = dir.join("testsrc2-1280x768.y4m");
17648 // Detailed synthetic content: its CDEF search spends more than one
17649 // strength pair, which is what puts a `cdef_idx` literal in the tile.
17650 let ok = Command::new("ffmpeg")
17651 .args(["-v", "error", "-y", "-f", "lavfi"])
17652 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17653 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17654 .arg(&clip)
17655 .status()
17656 .expect("ffmpeg failed to run")
17657 .success();
17658 assert!(ok, "ffmpeg could not write the synthetic clip");
17659 let (width, height) = (1280usize, 768usize);
17660 let pictures =
17661 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17662 force_b128_rect(1);
17663 force_b128_rectres(true);
17664 let _ = crate::tile::take_sb128_rectres_hits();
17665 let _ = crate::filter_search::take_cdef_covered_units();
17666 let encoded = encode_sequence(&pictures, 90, 0.5).unwrap();
17667 let coded = crate::tile::take_sb128_rectres_hits();
17668 let covered = crate::filter_search::take_cdef_covered_units();
17669 eprintln!(
17670 "rect halves WITH a residual: writer coded {coded}; 64x64 CDEF units taking \
17671 another unit's literal: {covered}"
17672 );
17673 assert!(coded > 0, "no 128x64 half carried a residual on this clip");
17674 assert!(
17675 covered > 0,
17676 "no 64x64 unit took a non-zero preset from another unit's literal, so this clip \
17677 cannot witness the rule",
17678 );
17679 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17680 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17681 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17682 for (plane, got, want) in [
17683 ("luma", &dec.y, &frame.reconstruction.y),
17684 ("U", &dec.u, &frame.reconstruction.u),
17685 ("V", &dec.v, &frame.reconstruction.v),
17686 ] {
17687 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17688 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17689 }
17690 }
17691 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17692 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17693 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17694 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17695 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17696 }
17697 }
17698
17699 /// lane-b128r: the COMPOUND arm at the 128 root -- one 128x128 block
17700 /// naming `LAST` plus `GOLDEN`/`ALTREF`, through the same
17701 /// `write_compound_block` chain every smaller compound block takes, at a
17702 /// window it had never been exercised at. RED before this lane: the
17703 /// search passed an empty compound list at the 128 root, so the count was
17704 /// 0 and no such block existed to decode.
17705 ///
17706 /// cargo test -p ec-av1 --release --lib -- --ignored \
17707 /// a_128_root_compound_block --nocapture
17708 #[test]
17709 #[ignore = "sets the process-global superblock size: run it alone"]
17710 fn a_128_root_compound_block_decodes_exact_through_both_decoders() {
17711 let _knobs = crate::speed::knob_write();
17712 if !have_ffmpeg() {
17713 eprintln!("SKIP: no ffmpeg");
17714 return;
17715 }
17716 force_sb128(true);
17717 let dir = std::env::temp_dir().join(format!("ec-av1-b128c-{}", std::process::id()));
17718 std::fs::create_dir_all(&dir).unwrap();
17719 let clip = dir.join("testsrc2-1280x768.y4m");
17720 // Moving objects that occlude each other: a pan is coded by one
17721 // reference outright, and a compound pair only pays where the two
17722 // references disagree.
17723 let ok = Command::new("ffmpeg")
17724 .args(["-v", "error", "-y", "-f", "lavfi"])
17725 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17726 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17727 .arg(&clip)
17728 .status()
17729 .expect("ffmpeg failed to run")
17730 .success();
17731 assert!(ok, "ffmpeg could not write the synthetic clip");
17732 let (width, height) = (1280usize, 768usize);
17733 let pictures =
17734 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17735 // The compound candidate wins the 128 block's own search on this pan
17736 // but the root then loses to its four cells, so the root is forced
17737 // (the residual arm is left at its default, off).
17738 force_b128_root(true);
17739 let _ = take_b128_compound_hits();
17740 let _ = crate::tile::take_sb128_compound_hits();
17741 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17742 let (won, coded) =
17743 (take_b128_compound_hits(), crate::tile::take_sb128_compound_hits());
17744 eprintln!("COMPOUND 128x128 blocks: search won {won}, writer coded {coded}");
17745 assert!(coded > 0, "no compound 128x128 block was coded on this clip");
17746 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17747 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17748 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17749 for (plane, got, want) in [
17750 ("luma", &dec.y, &frame.reconstruction.y),
17751 ("U", &dec.u, &frame.reconstruction.u),
17752 ("V", &dec.v, &frame.reconstruction.v),
17753 ] {
17754 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17755 assert_eq!(differ, 0, "frame {i}: {plane} -- {differ} samples differ");
17756 }
17757 }
17758 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17759 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17760 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: ffmpeg luma");
17761 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: ffmpeg U");
17762 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: ffmpeg V");
17763 }
17764 }
17765
17766 /// lane-b128hv: the 128 root's `PARTITION_HORZ` and `PARTITION_VERT`
17767 /// arms -- two 128x64 / 64x128 inter blocks where the NONE arm codes one
17768 /// square. Three passes over one `testsrc2` clip:
17769 ///
17770 /// * HORZ forced at every root ([`force_b128_rect`]), so every context
17771 /// the 128x64 shape reads is exercised rather than the handful the RD
17772 /// would pick;
17773 /// * VERT forced the same way;
17774 /// * UNFORCED, which is the count the gate rows are read against -- the
17775 /// same clip with the RD free to choose among NONE / HORZ / VERT /
17776 /// four superblocks.
17777 ///
17778 /// Each pass is sample-exact against the encoder's own reconstruction
17779 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
17780 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
17781 /// before this lane by construction: `write_sb128_root` could only name
17782 /// `PARTITION_NONE` or `PARTITION_SPLIT`, so the count was 0 on all three.
17783 ///
17784 /// cargo test -p ec-av1 --release --lib -- --ignored \
17785 /// a_128_root_horz_and_vert --nocapture
17786 #[test]
17787 #[ignore = "sets the process-global superblock size: run it alone"]
17788 fn a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders() {
17789 let _knobs = crate::speed::knob_write();
17790 if !have_ffmpeg() {
17791 eprintln!("SKIP: no ffmpeg");
17792 return;
17793 }
17794 force_sb128(true);
17795 let dir = std::env::temp_dir().join(format!("ec-av1-b128hv-{}", std::process::id()));
17796 std::fs::create_dir_all(&dir).unwrap();
17797 let clip = dir.join("testsrc2-1280x768.y4m");
17798 let ok = Command::new("ffmpeg")
17799 .args(["-v", "error", "-y", "-f", "lavfi"])
17800 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17801 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17802 .arg(&clip)
17803 .status()
17804 .expect("ffmpeg failed to run")
17805 .success();
17806 assert!(ok, "ffmpeg could not write the synthetic clip");
17807 let (width, height) = (1280usize, 768usize);
17808 let pictures =
17809 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17810 let mut unforced = (0usize, 0usize);
17811 for (label, force) in [("HORZ", 1u8), ("VERT", 2), ("unforced", 0)] {
17812 force_b128_rect(force);
17813 let _ = take_b128_horz_hits();
17814 let _ = take_b128_vert_hits();
17815 let _ = crate::tile::take_sb128_horz_hits();
17816 let _ = crate::tile::take_sb128_vert_hits();
17817 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17818 let (won_h, won_v) = (take_b128_horz_hits(), take_b128_vert_hits());
17819 let (coded_h, coded_v) = (
17820 crate::tile::take_sb128_horz_hits(),
17821 crate::tile::take_sb128_vert_hits(),
17822 );
17823 eprintln!(
17824 "{label}: search won {won_h} HORZ + {won_v} VERT roots, writer coded \
17825 {coded_h} 128x64 + {coded_v} 64x128 halves"
17826 );
17827 match force {
17828 1 => assert!(coded_h > 0, "no 128x64 half was coded with HORZ forced"),
17829 2 => assert!(coded_v > 0, "no 64x128 half was coded with VERT forced"),
17830 // The unforced count is REPORTED, not asserted: it is the
17831 // number the gate is read against, and a zero here would be
17832 // an RD result, not a defect (the forced passes already prove
17833 // the writer and the reader agree on the shape).
17834 _ => unforced = (won_h, won_v),
17835 }
17836 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17837 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
17838 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17839 for (plane, got, want) in [
17840 ("luma", &dec.y, &frame.reconstruction.y),
17841 ("U", &dec.u, &frame.reconstruction.u),
17842 ("V", &dec.v, &frame.reconstruction.v),
17843 ] {
17844 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17845 assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ");
17846 }
17847 }
17848 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17849 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17850 assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma");
17851 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
17852 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
17853 }
17854 }
17855 force_b128_rect(0);
17856 eprintln!(
17857 "unforced on testsrc2: {} HORZ + {} VERT roots over 12 frames",
17858 unforced.0, unforced.1
17859 );
17860 }
17861
17862 /// lane-ab128: the 128 root's four AB shapes -- `PARTITION_HORZ_A` (two
17863 /// 64x64 on top, one 128x64 below), `_HORZ_B`, `_VERT_A`, `_VERT_B`.
17864 /// Five passes over the same `testsrc2` clip
17865 /// `a_128_root_horz_and_vert_halves_decode_exact_through_both_decoders`
17866 /// uses: each shape forced at every root ([`force_b128_ab`]), so every
17867 /// context and every visit order the shape reads is exercised rather than
17868 /// the handful the RD would pick, and then an UNFORCED pass whose
17869 /// per-shape count is REPORTED (it is the number the gate rows are read
17870 /// against).
17871 ///
17872 /// Each pass is sample-exact against the encoder's own reconstruction
17873 /// through `decode_stream` AND through ffmpeg; a writer/reader mismatch
17874 /// surfaces here as a refusal or a pixel miss, never in the BD gate. RED
17875 /// before this lane by construction: `write_sb128_root` could only name
17876 /// NONE / HORZ / VERT / SPLIT, so all four counts were 0.
17877 ///
17878 /// cargo test -p ec-av1 --release --lib -- --ignored \
17879 /// a_128_root_ab_shapes --nocapture
17880 #[test]
17881 #[ignore = "sets the process-global superblock size: run it alone"]
17882 fn a_128_root_ab_shapes_decode_exact_through_both_decoders() {
17883 let _knobs = crate::speed::knob_write();
17884 if !have_ffmpeg() {
17885 eprintln!("SKIP: no ffmpeg");
17886 return;
17887 }
17888 force_sb128(true);
17889 let dir = std::env::temp_dir().join(format!("ec-av1-ab128-{}", std::process::id()));
17890 std::fs::create_dir_all(&dir).unwrap();
17891 let clip = dir.join("testsrc2-1280x768.y4m");
17892 let ok = Command::new("ffmpeg")
17893 .args(["-v", "error", "-y", "-f", "lavfi"])
17894 .args(["-i", "testsrc2=size=1280x768:rate=24"])
17895 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17896 .arg(&clip)
17897 .status()
17898 .expect("ffmpeg failed to run")
17899 .success();
17900 assert!(ok, "ffmpeg could not write the synthetic clip");
17901 let (width, height) = (1280usize, 768usize);
17902 let pictures =
17903 crate::probe::source(clip.to_str().unwrap(), "0", "null", width, height, 12);
17904 let names = ["HORZ_A", "HORZ_B", "VERT_A", "VERT_B"];
17905 let mut unforced = [0usize; 4];
17906 for force in [4u8, 5, 6, 7, 0] {
17907 force_b128_ab(force);
17908 let label = if force == 0 { "unforced" } else { names[usize::from(force) - 4] };
17909 let _ = take_b128_ab_hits();
17910 let _ = crate::tile::take_sb128_ab_hits();
17911 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17912 let won = take_b128_ab_hits();
17913 let coded = crate::tile::take_sb128_ab_hits();
17914 eprintln!(
17915 "{label}: search won {won:?} AB roots, writer coded {coded:?} \
17916 (HORZ_A/HORZ_B/VERT_A/VERT_B)"
17917 );
17918 if force == 0 {
17919 // The unforced counts are REPORTED, not asserted: a zero here
17920 // would be an RD result, not a defect (the four forced passes
17921 // already prove the writer and the reader agree on the shape).
17922 unforced = won;
17923 } else {
17924 let i = usize::from(force) - 4;
17925 assert!(coded[i] > 0, "no {label} root was coded with {label} forced");
17926 }
17927 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17928 assert_eq!(decoded.len(), encoded.frames.len(), "{label}: frame count");
17929 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17930 for (plane, got, want) in [
17931 ("luma", &dec.y, &frame.reconstruction.y),
17932 ("U", &dec.u, &frame.reconstruction.u),
17933 ("V", &dec.v, &frame.reconstruction.v),
17934 ] {
17935 let differ = got.iter().zip(want.iter()).filter(|(a, b)| a != b).count();
17936 assert_eq!(differ, 0, "{label} frame {i}: {plane} -- {differ} samples differ");
17937 }
17938 }
17939 let ff = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
17940 for (i, (frame, dec)) in encoded.frames.iter().zip(&ff).enumerate() {
17941 assert_eq!(dec.y, frame.reconstruction.y, "{label} frame {i}: ffmpeg luma");
17942 assert_eq!(dec.u, frame.reconstruction.u, "{label} frame {i}: ffmpeg U");
17943 assert_eq!(dec.v, frame.reconstruction.v, "{label} frame {i}: ffmpeg V");
17944 }
17945 }
17946 force_b128_ab(0);
17947 eprintln!(
17948 "unforced on testsrc2 over 12 frames: {} HORZ_A + {} HORZ_B + {} VERT_A + {} VERT_B",
17949 unforced[0], unforced[1], unforced[2], unforced[3],
17950 );
17951 }
17952
17953 #[test]
17954 #[ignore = "sets the process-global superblock size: run it alone"]
17955 fn a_128_superblock_clip_whose_drl_index_the_write_time_stack_cannot_carry_decodes_exact() {
17956 let _knobs = crate::speed::knob_write();
17957 if !have_ffmpeg() {
17958 eprintln!("SKIP: no ffmpeg");
17959 return;
17960 }
17961 force_sb128(true);
17962 let dir = std::env::temp_dir().join(format!("ec-av1-sb128b-{}", std::process::id()));
17963 std::fs::create_dir_all(&dir).unwrap();
17964 let clip = dir.join("mandelbrot-1280x768.y4m");
17965 let ok = Command::new("ffmpeg")
17966 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "mandelbrot=size=1280x768:rate=24"])
17967 .args(["-frames:v", "12", "-pix_fmt", "yuv420p"])
17968 .arg(&clip)
17969 .status()
17970 .expect("ffmpeg failed to run")
17971 .success();
17972 assert!(ok, "ffmpeg could not write the synthetic clip");
17973 let path = clip.to_str().unwrap();
17974 let (width, height) = (1280usize, 768usize);
17975 let pictures = crate::probe::source(path, "0", "null", width, height, 12);
17976
17977 let _ = crate::tile::take_drl_clamp_hits();
17978 let encoded = encode_sequence(&pictures, 150, 0.5).unwrap();
17979 let clamps = crate::tile::take_drl_clamp_hits();
17980 assert!(
17981 clamps > 0,
17982 "this clip never asked for a drl index the write-time stack could not carry, \
17983 so it cannot witness the defect"
17984 );
17985 eprintln!("clamped drl indices: {clamps}");
17986
17987 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
17988 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
17989 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
17990 let recon = &frame.reconstruction;
17991 for (plane, got, want) in [
17992 ("luma", &dec.y, &recon.y),
17993 ("U", &dec.u, &recon.u),
17994 ("V", &dec.v, &recon.v),
17995 ] {
17996 let differ = got.iter().zip(want).filter(|(a, b)| a != b).count();
17997 assert_eq!(
17998 differ, 0,
17999 "frame {i}: {plane} -- {differ} of {} samples differ from the encoder's \
18000 own reconstruction",
18001 got.len()
18002 );
18003 }
18004 }
18005 }
18006
18007 #[test]
18008 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
18009 let _knobs = crate::speed::knob_read();
18010 let fctx = &crate::decode::FrameCtx::for_encoder();
18011 // 256x128, not the 128x64 this started at: once a leaf could search
18012 // its second reference (lane-av1comp4) the small card's every
18013 // eligible block went to a compound winner, which commits its flat
18014 // transform, and the split below stopped firing on content that
18015 // still splits at every larger size ([[gate-blind-to-feature]] --
18016 // the guard is right, the fixture had shrunk under it).
18017 let (width, height) = (256usize, 128usize);
18018 let pictures: Vec<Picture> =
18019 (0..5).map(|i| panned_test_card(width, height, i * 3)).collect();
18020 let _ = take_inter_tx_split_hits();
18021 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18022 let raw = take_inter_tx_split_hits();
18023 // Summed over the four block classes the census keys on (leaf/32x32 x
18024 // single/compound): this assert is about the split firing at all.
18025 let split = [
18026 raw.iter().step_by(2).sum::<usize>(),
18027 raw.iter().skip(1).step_by(2).sum::<usize>(),
18028 ];
18029 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
18030 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
18031 // content splits -- a green round trip in which the split never fires
18032 // would prove only the flat path.
18033 if tx_select() && tx_select_inter() {
18034 assert!(split[1] > 0, "the inter var-tx split never fired");
18035 }
18036 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
18037 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
18038 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
18039 let recon = &frame.reconstruction;
18040 for (plane, got, want, stride) in [
18041 ("luma", &dec.y, &recon.y, width),
18042 ("U", &dec.u, &recon.u, width / 2),
18043 ("V", &dec.v, &recon.v, width / 2),
18044 ] {
18045 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
18046 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
18047 panic!(
18048 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
18049 reconstruction {} ({} of {} samples differ)",
18050 at % stride,
18051 at / stride,
18052 got[at],
18053 want[at],
18054 got.iter().zip(want).filter(|(a, b)| a != b).count(),
18055 got.len(),
18056 );
18057 }
18058 }
18059 }
18060 }
18061
18062 /// The rate term the mode search ranks every decision by has to be the
18063 /// rate the writer then spends. The search prices a block's coefficients
18064 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
18065 /// against the default CDFs a tile starts from and the contexts of a
18066 /// block whose neighbours coded nothing -- while the tile writer codes
18067 /// them against a state that has been adapting all frame (the
18068 /// price-the-narrowing class). This measures that drift: the sum of what
18069 /// the search paid for the coefficients it kept, against the bytes the
18070 /// writer actually emitted for the whole tile (which also carries the
18071 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
18072 /// expected to be the larger of the two).
18073 #[test]
18074 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
18075 let _knobs = crate::speed::knob_read();
18076 let fctx = &crate::decode::FrameCtx::for_encoder();
18077 let (width, height) = (256usize, 128usize);
18078 let pictures: Vec<Picture> = (0..5)
18079 .map(|i| panned_test_card(width, height, i * 2))
18080 .collect();
18081 let _ = take_predicted_bits();
18082 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18083 let predicted = take_predicted_bits();
18084 assert_eq!(predicted.len(), encoded.frames.len());
18085
18086 eprintln!("frame predicted bits written bits drift");
18087 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
18088 // defect this gate exists to catch), a positive one is the written
18089 // side carrying syntax the coefficient sum leaves out -- and since
18090 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
18091 // on that side, so the two directions no longer share a bound.
18092 let mut worst_over: f64 = 0.0;
18093 let mut worst_under: f64 = 0.0;
18094 // The census is per CODED frame, so it is zipped in coding order --
18095 // which is not display order under a pyramid.
18096 let coded: Vec<&Encoded> =
18097 encoded.coding_order.iter().map(|&i| &encoded.frames[i]).collect();
18098 for (i, (frame, &bits)) in coded.into_iter().zip(&predicted).enumerate() {
18099 let written = frame.tile.len() as f64 * 8.0;
18100 let drift = (written - bits) / written;
18101 worst_over = worst_over.max(-drift);
18102 // lane-av1pyrdef: a pyramid LEAF codes almost no coefficients at
18103 // all (150-250 bits of tile, nearly all of it partition/mode/mv
18104 // syntax the coefficient sum never counts), so its ratio measures
18105 // that floor rather than any drift. Frames under 512 written bits
18106 // are left out of the under-price bound for that reason; the
18107 // over-price bound -- the defect direction, where the search pays
18108 // MORE than the writer -- still covers every frame.
18109 if written >= 512.0 {
18110 worst_under = worst_under.max(drift);
18111 }
18112 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
18113 }
18114 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
18115 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
18116 // over-prices every frame but the last (its sum EXCLUDES the
18117 // partition/mode/skip/mv syntax the written side carries, so the true
18118 // coefficient over-price is larger still): the writer's CDFs adapt to
18119 // the content while the search's stay at the defaults. The bound is
18120 // set just above the worst measured point -- a widening drift is the
18121 // thing this gate exists to catch.
18122 assert!(
18123 worst_over <= 0.16,
18124 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
18125 worst_over * 100.0
18126 );
18127 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
18128 // the worst inter frame, where nearly every block now codes an MV
18129 // residual and a reference the coefficient sum never counts. Re-measured
18130 // at +29.6% once the encoder's grid published compound blocks properly
18131 // (compound share 8.8% -> 11.5%): a compound block carries a second
18132 // reference tree, a compound mode symbol and -- for the half-new modes
18133 // -- an MV residual, none of which the coefficient sum counts.
18134 // lane-av1txbits: pricing against the tables the frame's writer really
18135 // starts from collapses the over-price above to nothing, so the whole
18136 // remaining gap is the syntax the coefficient sum leaves out. That is
18137 // the default on a non-screen frame since lane-av1price2 (this
18138 // fixture is one), and it reads +32.6% here.
18139 // lane-av1obmc: every eligible single-reference inter block now also
18140 // carries a `motion_mode` symbol the coefficient sum never counts,
18141 // and an OBMC block carries the more expensive of the two values --
18142 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
18143 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
18144 // decisions, so this bound and the byte pins above FAIL BY DESIGN
18145 // under it; the default path (no motion_mode syntax at all) is the
18146 // one they are measured on.
18147 // lane-av1pyrdef: `encode_sequence` codes this fixture under the
18148 // coding pyramid now, so the five frames are a key frame, a hidden
18149 // ALTREF at q-16 and three leaves at q+8: +2.6% / +6.9% (the two
18150 // frames over the 512-bit floor) and +44.7 / +74.4 / +74.4 on the
18151 // near-empty leaves below it. Both bounds stand where they were.
18152 // lane-av1rejudge: local warp is ON by default now, so every eligible
18153 // single-reference block carries that same `motion_mode` symbol (a
18154 // 3-value alphabet where a warp sample exists) on the DEFAULT path --
18155 // +34.9% here, one point past the OBMC reading above. The bound moves
18156 // with it; `EC_AV1_WARP=0` restores the +32.6% no-motion_mode number.
18157 // lane-av1cfl: a `UV_CFL_PRED` block carries a `cfl_alpha_signs`
18158 // symbol and one or two magnitude symbols, none of which the
18159 // coefficient sum counts either -- +36.9% here against the same
18160 // fixture's +34.9% with `EC_AV1_CFL=0`.
18161 // ... and a directional block whose `angle_delta_y` is no longer
18162 // always ZERO codes a costlier symbol off the same CDF -- +39.1%.
18163 assert!(
18164 worst_under <= 0.40,
18165 "the writer spent {:.2}% more than the search priced -- more than \
18166 the mode/mv syntax outside the coefficient sum explains",
18167 worst_under * 100.0
18168 );
18169 }
18170
18171 /// The census behind step (1) of the pricer lane: for every transform
18172 /// block the writer really codes, what the search priced those levels at
18173 /// against what the writer spent on them, split by table set and non-zero
18174 /// count. One average hides the interesting part -- the classes the
18175 /// estimate is systematically wrong about (all-zero blocks, the
18176 /// one-coefficient blocks the inter search lives on) -- so the split is
18177 /// printed and only the total is asserted on.
18178 #[test]
18179 fn pricer_error_census_by_block_class() {
18180 let _knobs = crate::speed::knob_read();
18181 let fctx = &crate::decode::FrameCtx::for_encoder();
18182 let (width, height) = (256usize, 128usize);
18183 let pictures: Vec<Picture> = (0..5)
18184 .map(|i| panned_test_card(width, height, i * 2))
18185 .collect();
18186 crate::tile::pricer_census_on();
18187 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18188 let rows = crate::tile::take_pricer_census();
18189 assert!(!rows.is_empty(), "the census saw no transform block");
18190
18191 println!("| set | nz | blocks | priced bits | written bits | error |");
18192 println!("|---|---|---|---|---|---|");
18193 let (mut priced_all, mut written_all) = (0.0, 0.0);
18194 for ((set, bucket), (blocks, priced, written)) in &rows {
18195 priced_all += priced;
18196 written_all += written;
18197 println!(
18198 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
18199 crate::tile::census_bucket_label(*bucket),
18200 if *written > 0.0 {
18201 (priced - written) / written * 100.0
18202 } else {
18203 0.0
18204 }
18205 );
18206 }
18207 println!(
18208 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
18209 rows.values().map(|r| r.0).sum::<u64>(),
18210 (priced_all - written_all) / written_all * 100.0
18211 );
18212 assert!(written_all > 0.0);
18213 }
18214
18215 /// Step (2) of the pricer lane: the same census, but on the REAL clips
18216 /// the BD gate scores -- one film clip and the screen capture -- so the
18217 /// question the film/screen split raises can be answered from data. Real
18218 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
18219 /// the screen capture larger, and the census says why: on a screen
18220 /// capture the frame's own starting tables are the tables of a frame that
18221 /// coded PALETTE and long runs of zero blocks, so they are far from the
18222 /// tables the writer ends the frame with; the pricer error does not fall
18223 /// the way it does on film.
18224 ///
18225 /// Not a gate -- it prints. Run it once per mode:
18226 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
18227 /// --ignored pricer_error_census_on_clips --nocapture
18228 #[test]
18229 #[ignore = "reads the real library, needs ffmpeg"]
18230 fn pricer_error_census_on_clips() {
18231 let _knobs = crate::speed::knob_write();
18232 if !have_ffmpeg() {
18233 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
18234 return;
18235 }
18236 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
18237 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
18238 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
18239 if film.exists() {
18240 clips.push(("film 1080p".to_string(), film));
18241 }
18242 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
18243 && let Some(p) = manifest
18244 .lines()
18245 .skip(1)
18246 .filter_map(|l| l.split('\t').next())
18247 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
18248 {
18249 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
18250 }
18251 assert!(!clips.is_empty(), "no source clip available");
18252 let (width, height, frames) = (640usize, 384usize, 6usize);
18253 for (name, path) in &clips {
18254 let fctx = &crate::decode::FrameCtx::for_encoder();
18255 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
18256 SCREEN_FRAMES.iter().for_each(|c| {
18257 c.store(0, std::sync::atomic::Ordering::Relaxed);
18258 });
18259 let _ = crate::tile::take_pricing_hits();
18260 crate::tile::pricer_census_on();
18261 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18262 let rows = crate::tile::take_pricer_census();
18263 let (price_default, price_real) = crate::tile::take_pricing_hits();
18264 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
18265 println!(
18266 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
18267 {screen_on}, pricer armings default={price_default} real={price_real}"
18268 );
18269 println!("| set | nz | blocks | priced bits | written bits | error |");
18270 println!("|---|---|---|---|---|---|");
18271 let (mut priced_all, mut written_all) = (0.0, 0.0);
18272 for ((set, bucket), (blocks, priced, written)) in &rows {
18273 priced_all += priced;
18274 written_all += written;
18275 println!(
18276 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
18277 crate::tile::census_bucket_label(*bucket),
18278 if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 }
18279 );
18280 }
18281 println!(
18282 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
18283 rows.values().map(|r| r.0).sum::<u64>(),
18284 (priced_all - written_all) / written_all * 100.0
18285 );
18286 assert!(written_all > 0.0, "{name}: the census saw no transform block");
18287 }
18288 }
18289
18290 /// Low motion has to actually buy something: at least one inter frame of
18291 /// a panning sequence has to cost fewer bytes than the key frame that
18292 /// starts it, and the inter-block share it prints has to be non-zero --
18293 /// a search that never picks an inter mode would still pass a rate gate
18294 /// on a picture with no motion in it (the class this repo calls
18295 /// gate-blind-to-feature), so the share is printed even though it is not
18296 /// asserted on beyond being reachable at all.
18297 #[test]
18298 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
18299 let _knobs = crate::speed::knob_read();
18300 let fctx = &crate::decode::FrameCtx::for_encoder();
18301 let (width, height) = (256usize, 128usize);
18302 let pictures: Vec<Picture> = (0..5)
18303 .map(|i| panned_test_card(width, height, i * 2))
18304 .collect();
18305 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18306
18307 let key_bytes = encoded.frames[0].stream.len();
18308 eprintln!("frame bytes inter share");
18309 for (i, frame) in encoded.frames.iter().enumerate() {
18310 eprintln!(
18311 "{i:5} {:5} {:11.2}",
18312 frame.stream.len(),
18313 frame.inter_block_share
18314 );
18315 }
18316 assert!(
18317 encoded.frames[1..]
18318 .iter()
18319 .any(|f| f.stream.len() < key_bytes),
18320 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
18321 );
18322 assert!(
18323 encoded.frames[1..]
18324 .iter()
18325 .any(|f| f.inter_block_share > 0.0),
18326 "no inter frame coded a single inter block -- the search never fired"
18327 );
18328 }
18329
18330 /// A manual perf probe, not a gate: prints where a key frame's and an
18331 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
18332 /// measures before it optimizes rather than guessing. Run with
18333 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
18334 #[test]
18335 #[ignore = "a perf probe, not a gate"]
18336 fn stage_timing_breakdown() {
18337 let _knobs = crate::speed::knob_read();
18338 let fctx = &crate::decode::FrameCtx::for_encoder();
18339 use std::time::Instant;
18340
18341 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
18342 let picture = test_card(width, height);
18343
18344 let t = Instant::now();
18345 let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
18346 let dc_only_t = t.elapsed();
18347
18348 let t = Instant::now();
18349 let non_directional =
18350 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
18351 let non_directional_t = t.elapsed();
18352
18353 let t = Instant::now();
18354 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18355 let all_modes_t = t.elapsed();
18356
18357 eprintln!(
18358 "\n=== key frame {width}x{height} ===\n\
18359 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
18360 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
18361 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
18362 dc_only.stream.len(),
18363 non_directional.stream.len(),
18364 all_modes.stream.len(),
18365 );
18366
18367 // One inter frame predicting off the key frame's own
18368 // reconstruction, the (256, 256)-padded surface encode_sequence
18369 // itself would hand encode_inter_frame.
18370 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
18371 let padded_pic = picture.padded_to(SUPERBLOCK);
18372 let t = Instant::now();
18373 let inter =
18374 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();
18375 let inter_t = t.elapsed();
18376 eprintln!(
18377 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
18378 {:.2})",
18379 inter.stream.len(),
18380 inter.inter_block_share
18381 );
18382 }
18383
18384 // Isolated per-call cost of the trial pipeline's own stages, at both
18385 // transform sizes the search runs, averaged over enough calls to
18386 // rise above `Instant::now`'s own noise.
18387 for side in [16usize, 32] {
18388 const N: u32 = 20_000;
18389 let residual: Vec<i32> = (0..side * side)
18390 .map(|i| ((i * 37 % 61) as i32) - 30)
18391 .collect();
18392
18393 let t = Instant::now();
18394 let mut levels = Vec::new();
18395 for _ in 0..N {
18396 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
18397 }
18398 let forward_t = t.elapsed() / N;
18399
18400 let t = Instant::now();
18401 for _ in 0..N {
18402 std::hint::black_box(crate::transform::dequant_and_inverse(&levels, side, 8, 100));
18403 }
18404 let inverse_t = t.elapsed() / N;
18405
18406 let set = if side == 32 {
18407 crate::cdf_state::TxbSet::Luma32
18408 } else {
18409 crate::cdf_state::TxbSet::Luma16
18410 };
18411 let t = Instant::now();
18412 for _ in 0..N {
18413 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
18414 }
18415 let entropy_t = t.elapsed() / N;
18416
18417 let above = vec![128u8; side * 2];
18418 let left = vec![128u8; side * 2];
18419 let mut prediction = vec![0u8; side * side];
18420 let t = Instant::now();
18421 for _ in 0..N {
18422 intra_predict_u8(
18423 D45_PRED,
18424 0,
18425 Some(&above),
18426 Some(&left),
18427 Some(128),
18428 side,
18429 side,
18430 false,
18431 false,
18432 &mut prediction, fctx,
18433 );
18434 }
18435 let predict_t = t.elapsed() / N;
18436
18437 eprintln!(
18438 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
18439 predict (1 directional mode): {predict_t:>9.2?}\n\
18440 forward_and_quantize: {forward_t:>9.2?}\n\
18441 dequant_and_inverse: {inverse_t:>9.2?}\n\
18442 coeff_bits: {entropy_t:>9.2?}"
18443 );
18444 }
18445 }
18446
18447 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
18448 /// (motion search, [`crate::mc::predict`], transform+quantize,
18449 /// `coeff_bits`), plus what is left over once those are subtracted --
18450 /// the thirteen-mode intra-candidate loop `search_inter_block` still
18451 /// runs on every inter block (its own transform/quant/entropy calls are
18452 /// already inside buckets 2/3, so "left over" here is everything NOT
18453 /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
18454 /// symbol-cost lookups outside `coeff_bits`).
18455 ///
18456 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
18457 #[test]
18458 #[ignore = "a perf probe, not a gate"]
18459 fn stage_timing_breakdown_inter() {
18460 let _knobs = crate::speed::knob_read();
18461 let fctx = &crate::decode::FrameCtx::for_encoder();
18462 use std::time::Instant;
18463
18464 let (width, height) = (1280usize, 720);
18465 let picture = test_card(width, height);
18466 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
18467 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
18468 let padded_pic = picture.padded_to(SUPERBLOCK);
18469
18470 stage_reset();
18471 let t = Instant::now();
18472 let inter =
18473 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();
18474 let total_t = t.elapsed();
18475 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
18476 let accounted = motion_search + transform_quant + entropy;
18477 // motion_search already contains interpolation's own time (every
18478 // candidate the search costs calls crate::mc::predict), so it is not
18479 // added again here -- interpolation is reported alongside as "of
18480 // which interpolation", not as a fifth additive bucket.
18481 let other = total_t.saturating_sub(accounted);
18482
18483 eprintln!(
18484 "\n=== inter frame {width}x{height}, one frame ===\n\
18485 total: {total_t:>9.2?} ({} bytes)\n\
18486 motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
18487 {interpolation:>9.2?})\n\
18488 transform + quantize: {transform_quant:>9.2?}\n\
18489 coeff_bits (entropy pricing): {entropy:>9.2?}\n\
18490 everything else (13-mode intra {other:>9.2?}\n\
18491 candidate loop's own predict/bookkeeping, NEARESTMV's own \
18492 predict, RD glue):",
18493 inter.stream.len(),
18494 );
18495 }
18496
18497 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
18498 /// frames (a dark/flat one, a detailed one, a normal film one) at two
18499 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
18500 /// None`, the baseline this same build produces without
18501 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
18502 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
18503 /// go in the lane report, which is where "ship as default" is decided --
18504 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
18505 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
18506 #[test]
18507 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
18508 fn prune_k_quality_sweep() {
18509 let _knobs = crate::speed::knob_read();
18510 let fctx = &crate::decode::FrameCtx::for_encoder();
18511 if !have_ffmpeg() {
18512 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
18513 return;
18514 }
18515 let (width, height) = (640usize, 352usize);
18516 let frames: &[(&str, &str, &str)] = &[
18517 // (label, clip, seek) -- a near-black scene, a busy one, and an
18518 // ordinary film frame, each from a different real file.
18519 (
18520 "dark/flat",
18521 "/home/user/Videos/reela.mp4",
18522 "3",
18523 ),
18524 (
18525 "detailed",
18526 "/home/user/Downloads/reelb.mkv",
18527 "1200",
18528 ),
18529 (
18530 "film",
18531 "/home/user/Videos/Films/reelc.mkv",
18532 "600",
18533 ),
18534 ];
18535 for &(label, clip, skip) in frames {
18536 if !std::path::Path::new(clip).exists() {
18537 eprintln!("SKIP {label}: {clip} not present on this machine");
18538 continue;
18539 }
18540 let picture = clip_frame(clip, skip, width, height);
18541 for &q in &[60u8, 150] {
18542 // SAFETY (not literally unsafe, just process-global): this is
18543 // a single-threaded #[ignore] probe, run by hand, never
18544 // alongside other tests that read Search::top_k.
18545 set_test_top_k_override(None);
18546 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
18547 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
18548 eprint!(
18549 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
18550 baseline.stream.len(),
18551 baseline_psnr
18552 );
18553 for &k in &[3usize, 4, 6] {
18554 set_test_top_k_override(Some(k));
18555 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
18556 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
18557 eprint!(
18558 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
18559 pruned.stream.len(),
18560 pruned_psnr,
18561 pruned_psnr - baseline_psnr
18562 );
18563 }
18564 eprintln!();
18565 }
18566 }
18567 set_test_top_k_override(None);
18568 }
18569
18570 /// Two consecutive decoded frames from one clip, for an inter-frame
18571 /// sweep -- [`clip_frame`] alone only ever gives one.
18572 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
18573 let out = Command::new("ffmpeg")
18574 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
18575 .args(["-vf", &format!("scale={width}:{height}")])
18576 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
18577 .output()
18578 .expect("ffmpeg failed to run");
18579 assert!(
18580 out.status.success(),
18581 "ffmpeg: {}",
18582 String::from_utf8_lossy(&out.stderr)
18583 );
18584 let (luma, chroma) = (width * height, width * height / 4);
18585 let frame_len = luma + 2 * chroma;
18586 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
18587 std::array::from_fn(|i| {
18588 let bytes = &out.stdout[i * frame_len..][..frame_len];
18589 Picture {
18590 width,
18591 height,
18592 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
18593 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
18594 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
18595 }
18596 })
18597 }
18598
18599 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
18600 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
18601 /// then one inter frame off it (`search_inter_block`'s own intra
18602 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
18603 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
18604 /// padding step complicates the comparison. Prints bytes and luma PSNR
18605 /// for the inter frame alone, unpruned vs each `K`.
18606 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
18607 #[test]
18608 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
18609 fn prune_k_quality_sweep_inter() {
18610 let _knobs = crate::speed::knob_read();
18611 let fctx = &crate::decode::FrameCtx::for_encoder();
18612 if !have_ffmpeg() {
18613 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
18614 return;
18615 }
18616 let (width, height) = (1280usize, 704usize);
18617 let frames: &[(&str, &str, &str)] = &[
18618 (
18619 "dark/flat",
18620 "/home/user/Videos/reela.mp4",
18621 "3",
18622 ),
18623 (
18624 "detailed",
18625 "/home/user/Downloads/reelb.mkv",
18626 "1200",
18627 ),
18628 (
18629 "film",
18630 "/home/user/Videos/Films/reelc.mkv",
18631 "600",
18632 ),
18633 ];
18634 for &(label, clip, skip) in frames {
18635 if !std::path::Path::new(clip).exists() {
18636 eprintln!("SKIP {label}: {clip} not present on this machine");
18637 continue;
18638 }
18639 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
18640 for &q in &[60u8, 150] {
18641 // SAFETY (not literally unsafe, just process-global): a
18642 // single-threaded #[ignore] probe, run by hand, never
18643 // alongside other tests that read Search::top_k.
18644 set_test_top_k_override_inter(None);
18645 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
18646 let baseline = encode_inter_frame(
18647 &inter_source,
18648 &key.reconstruction,
18649 q,
18650 0.5,
18651 1,
18652 flat_order_hints(1, 0, false),
18653 (width, height), None, None, None, None, fctx, None, &[],
18654 )
18655 .unwrap();
18656 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
18657 eprint!(
18658 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
18659 baseline.stream.len(),
18660 baseline_psnr
18661 );
18662 for &k in &[3usize, 4, 6] {
18663 set_test_top_k_override_inter(Some(k));
18664 let pruned = encode_inter_frame(
18665 &inter_source,
18666 &key.reconstruction,
18667 q,
18668 0.5,
18669 1,
18670 flat_order_hints(1, 0, false),
18671 (width, height), None, None, None, None, fctx, None, &[],
18672 )
18673 .unwrap();
18674 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
18675 eprint!(
18676 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
18677 pruned.stream.len(),
18678 pruned_psnr,
18679 pruned_psnr - baseline_psnr
18680 );
18681 }
18682 eprintln!();
18683 }
18684 }
18685 set_test_top_k_override_inter(None);
18686 }
18687
18688 /// `frames` consecutive pictures out of a real clip, scaled to a whole
18689 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
18690 /// to an arbitrary count for the fixture regression gate below.
18691 fn clip_frames(
18692 clip: &str,
18693 skip: &str,
18694 width: usize,
18695 height: usize,
18696 frames: usize,
18697 ) -> Vec<Picture> {
18698 clip_frames_vf(clip, skip, &format!("scale={width}:{height}"), width, height, frames)
18699 }
18700
18701 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
18702 /// for a native-resolution CROP instead of a downscale (the downscale is
18703 /// what destroys a screen capture's exact repeats -- class
18704 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
18705 fn clip_frames_vf(
18706 clip: &str,
18707 skip: &str,
18708 vf: &str,
18709 width: usize,
18710 height: usize,
18711 frames: usize,
18712 ) -> Vec<Picture> {
18713 // ONE definition of the gate's loader recipe, shared with
18714 // `examples/enc_probe` so the instrument cannot arm a different source
18715 // than the gate it reports on (class `instrument disagrees with the
18716 // gate`; lane-probe).
18717 crate::probe::source(clip, skip, vf, width, height, frames)
18718 }
18719
18720 /// The standing regression gate on real content: 12 frames of a real
18721 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
18722 /// this crate's own input regardless of its own source codec), encoded
18723 /// as an AV1 GOP and checked against three numeric floors so a
18724 /// compatibility or quality regression fails the suite instead of
18725 /// waiting for a downstream repo's gate to catch it (as happened for a
18726 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
18727 /// refusal, both caught only that way).
18728 ///
18729 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
18730 /// that geometry is already covered elsewhere), chosen only so encode
18731 /// time and gate numbers are not muddied by an edge-block class this
18732 /// test is not about.
18733 ///
18734 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
18735 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
18736 /// below carry a margin off those measured numbers (PSNR floor =
18737 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
18738 #[test]
18739 fn real_clip_encodes_within_its_quality_and_size_budget() {
18740 let _knobs = crate::speed::knob_read();
18741 let fctx = &crate::decode::FrameCtx::for_encoder();
18742 if !have_ffmpeg() {
18743 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
18744 return;
18745 }
18746 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18747 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
18748 if !clip.exists() {
18749 eprintln!(
18750 "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing",
18751 clip.display()
18752 );
18753 return;
18754 }
18755 let (width, height, frame_count) = (640usize, 384usize, 12usize);
18756 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
18757 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18758 assert_eq!(encoded.frames.len(), frame_count);
18759
18760 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
18761 // stream and hands back every frame -- a stream a downstream
18762 // decoder refuses is the exact class of regression this gate
18763 // exists for.
18764 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
18765 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
18766
18767 // Gate 2: quality vs the source did not silently collapse.
18768 let mean_psnr: f64 = decoded
18769 .iter()
18770 .zip(&source)
18771 .map(|(d, s)| psnr(&d.y, &s.y))
18772 .sum::<f64>()
18773 / frame_count as f64;
18774 assert!(
18775 mean_psnr >= 44.91,
18776 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
18777 );
18778
18779 // Gate 3: the stream did not silently bloat.
18780 assert!(
18781 encoded.stream.len() <= 80_340,
18782 "stream grew to {} bytes, over the 80340-byte ceiling",
18783 encoded.stream.len()
18784 );
18785 }
18786
18787 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
18788 /// straddle size: 640x384 is exact on both axes (32-aligned), so
18789 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
18790 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
18791 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
18792 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
18793 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
18794 /// card; this one is the real-clip gate, same three floors.
18795 ///
18796 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
18797 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
18798 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
18799 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
18800 #[test]
18801 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
18802 let _knobs = crate::speed::knob_read();
18803 let fctx = &crate::decode::FrameCtx::for_encoder();
18804 if !have_ffmpeg() {
18805 eprintln!(
18806 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
18807 no ffmpeg"
18808 );
18809 return;
18810 }
18811 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18812 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
18813 if !clip.exists() {
18814 eprintln!(
18815 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
18816 {} missing",
18817 clip.display()
18818 );
18819 return;
18820 }
18821 let (width, height, frame_count) = (704usize, 400usize, 8usize);
18822 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
18823 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
18824 assert_eq!(encoded.frames.len(), frame_count);
18825
18826 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
18827 // stream and hands back every frame.
18828 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
18829 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
18830
18831 // Gate 2: quality vs the source did not silently collapse.
18832 let mean_psnr: f64 = decoded
18833 .iter()
18834 .zip(&source)
18835 .map(|(d, s)| psnr(&d.y, &s.y))
18836 .sum::<f64>()
18837 / frame_count as f64;
18838 assert!(
18839 mean_psnr >= 44.98,
18840 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
18841 );
18842
18843 // Gate 3: the stream did not silently bloat.
18844 assert!(
18845 encoded.stream.len() <= 62_703,
18846 "stream grew to {} bytes, over the 62703-byte ceiling",
18847 encoded.stream.len()
18848 );
18849 }
18850
18851 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
18852 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
18853 /// facade -- timed end to end, so the edith export-time projection is a
18854 /// real number rather than a guess from the isolated key/inter numbers
18855 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
18856 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
18857 #[test]
18858 #[ignore = "a perf probe, not a gate"]
18859 fn sequence_bench_sanity() {
18860 let _knobs = crate::speed::knob_read();
18861 let fctx = &crate::decode::FrameCtx::for_encoder();
18862 use std::time::Instant;
18863 let (width, height) = (1280usize, 720usize);
18864 let pictures: Vec<Picture> = (0..24)
18865 .map(|i| panned_test_card(width, height, i * 3))
18866 .collect();
18867 let t = Instant::now();
18868 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
18869 let elapsed = t.elapsed();
18870 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
18871 eprintln!(
18872 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
18873 elapsed / 24
18874 );
18875 }
18876
18877 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
18878 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
18879 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
18880 /// -- --ignored --nocapture`.
18881 #[test]
18882 #[ignore = "a calibration probe, not a gate"]
18883 fn calibration_sweep_base_q_idx() {
18884 let _knobs = crate::speed::knob_read();
18885 let fctx = &crate::decode::FrameCtx::for_encoder();
18886 if !have_ffmpeg() {
18887 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
18888 return;
18889 }
18890 let (width, height, frames) = (640usize, 384usize, 12usize);
18891 for clip in [
18892 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
18893 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
18894 ] {
18895 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
18896 .join("../../fixtures/video")
18897 .join(clip);
18898 if !path.exists() {
18899 eprintln!("SKIP {clip}: fixture missing");
18900 continue;
18901 }
18902 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
18903 eprintln!("--- {clip} ---");
18904 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
18905 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
18906 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
18907 let mean_psnr: f64 = decoded
18908 .iter()
18909 .zip(&source)
18910 .map(|(d, s)| psnr(&d.y, &s.y))
18911 .sum::<f64>()
18912 / frames as f64;
18913 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
18914 eprintln!(
18915 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
18916 encoded.stream.len()
18917 );
18918 }
18919 }
18920 }
18921
18922 // -----------------------------------------------------------------------
18923 // The encoder's standing BD-rate baseline against libaom and rav1e.
18924 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
18925 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
18926 // agreeing with our encoder proves nothing about the bitstream.
18927 // -----------------------------------------------------------------------
18928
18929 /// All-plane PSNR of a decoded picture against its source, on the same
18930 /// 8-bit scale [`psnr`] uses.
18931 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
18932 let cat = |p: &Picture| {
18933 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
18934 v.extend_from_slice(&p.y);
18935 v.extend_from_slice(&p.u);
18936 v.extend_from_slice(&p.v);
18937 v
18938 };
18939 psnr(&cat(decoded), &cat(source))
18940 }
18941
18942 /// The pictures back as the planar 8-bit bytes an encoder reads.
18943 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
18944 let mut raw = Vec::new();
18945 for p in source {
18946 for plane in [&p.y, &p.u, &p.v] {
18947 raw.extend(plane.iter().map(|&s| s as u8));
18948 }
18949 }
18950 raw
18951 }
18952
18953 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
18954 /// through ffmpeg: one point per entry of `points`, each a quality flag
18955 /// set. Returns the ladder ordered by fidelity and the total encode wall
18956 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
18957 /// so both curves are measured by the same decoder.
18958 fn external_ladder(
18959 source: &[Picture],
18960 width: usize,
18961 height: usize,
18962 encoder: &str,
18963 points: &[Vec<String>],
18964 ) -> (Vec<(f64, f64)>, f64) {
18965 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
18966 let dir = std::env::temp_dir();
18967 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
18968 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
18969 let mut ladder = Vec::new();
18970 let mut wall = 0.0;
18971 for (i, params) in points.iter().enumerate() {
18972 let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id()));
18973 let start = std::time::Instant::now();
18974 let out = Command::new("ffmpeg")
18975 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
18976 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
18977 .arg(&raw_path)
18978 .args(["-an", "-threads", "1"])
18979 .args(["-g", &source.len().to_string(), "-c:v", encoder])
18980 .args(params)
18981 .args(["-f", "obu"])
18982 .arg(&obu)
18983 .output()
18984 .expect("ffmpeg failed to run");
18985 wall += start.elapsed().as_secs_f64();
18986 assert!(
18987 out.status.success(),
18988 "{encoder} {params:?}: {}",
18989 String::from_utf8_lossy(&out.stderr)
18990 );
18991 let stream = std::fs::read(&obu).expect("reference stream");
18992 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
18993 // lane-dkey: every reference point must also decode through OUR
18994 // decoder, sample-exact against ffmpeg's decode of the same bytes.
18995 // A BD table computed off streams we cannot read is a table about
18996 // an encoder we cannot check; this is the assertion that would
18997 // have caught the `force_integer_mv` defect (its stream decoded to
18998 // 25 dB garbage while this gate stayed green) and the crf-5 key
18999 // frame desync. A failure names the encoder, the point's flags and
19000 // the first differing frame/plane/sample.
19001 // lane-dpm1: a failing reference point is COLLECTED, not panicked
19002 // on, so one run still prints the whole BD table and names every
19003 // bad point instead of stopping at the first. The collection is
19004 // asserted empty by [`assert_ladder_decodes`] at the end of each
19005 // gate.
19006 match crate::stream::decode_stream(&stream) {
19007 Ok(ours) if ours.len() != decoded.len() => note_ladder_failure(format!(
19008 "{encoder} {params:?}: our decoder returned {} shown frames, ffmpeg {}",
19009 ours.len(),
19010 decoded.len(),
19011 )),
19012 Ok(ours) => {
19013 for (f, (o, d)) in ours.iter().zip(&decoded).enumerate() {
19014 if let Some((plane, s, got, want)) = first_plane_mismatch(o, d) {
19015 note_ladder_failure(format!(
19016 "{encoder} {params:?} frame {f} plane {plane} sample {s}: our \
19017 decoder decoded {got}, ffmpeg {want}"
19018 ));
19019 break;
19020 }
19021 }
19022 }
19023 Err(e) => note_ladder_failure(format!(
19024 "{encoder} {params:?}: our decoder refused the stream ({e})"
19025 )),
19026 }
19027 let mean: f64 = decoded
19028 .iter()
19029 .zip(source)
19030 .map(|(d, s)| psnr_all(d, s))
19031 .sum::<f64>()
19032 / source.len() as f64;
19033 ladder.push((mean, (stream.len() as f64).log10()));
19034 let _ = std::fs::remove_file(&obu);
19035 }
19036 let _ = std::fs::remove_file(&raw_path);
19037 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19038 (ladder, wall)
19039 }
19040
19041 /// Every reference ladder point that did not decode sample-exactly
19042 /// through our own decoder, collected across a whole gate run so the BD
19043 /// table still prints and EVERY bad point is named
19044 /// (`encoder params frame plane sample`) instead of only the first.
19045 static LADDER_FAILURES: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
19046
19047 fn note_ladder_failure(msg: String) {
19048 eprintln!("LADDER DECODE FAILURE: {msg}");
19049 LADDER_FAILURES.lock().expect("ladder failures").push(msg);
19050 }
19051
19052 /// Fail the gate at its END on everything [`external_ladder`] collected.
19053 fn assert_ladder_decodes() {
19054 let failures = std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
19055 assert!(
19056 failures.is_empty(),
19057 "{} reference ladder point(s) did not decode exactly through our decoder:\n{}",
19058 failures.len(),
19059 failures.join("\n"),
19060 );
19061 }
19062
19063 /// First differing sample between two pictures, as
19064 /// `(plane, index, left, right)` -- so a gate failure names the plane and
19065 /// the sample instead of just "differs". A length difference counts as a
19066 /// mismatch of that plane at the first index past the shorter one.
19067 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
19068 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
19069 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
19070 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
19071 }
19072 if l.len() != r.len() {
19073 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
19074 }
19075 }
19076 None
19077 }
19078
19079 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
19080 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
19081 /// stream is decoded twice -- by ffmpeg and by our own
19082 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
19083 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
19084 /// in Y, U and V over every shown frame in display order. That is itself
19085 /// a gate: it proves the bitstream says what the encoder thinks, in the
19086 /// only two decoders that read it.
19087 fn our_ladder(
19088 name: &str,
19089 source: &[Picture],
19090 width: usize,
19091 height: usize,
19092 fctx: &crate::decode::FrameCtx,
19093 ) -> (Vec<(f64, f64)>, f64) {
19094 let mut ladder = Vec::new();
19095 let mut wall = 0.0;
19096 for &q in &[150u8, 120, 90, 60] {
19097 let start = std::time::Instant::now();
19098 // lane-rdoq: the deadzone was fitted WITHOUT the RDOQ pass, so
19099 // the gate has to be able to re-sweep it. 0.5 is the shipped one
19100 // (`crate::encoder::DEADZONE`).
19101 let deadzone = std::env::var("EC_AV1_DEADZONE")
19102 .ok()
19103 .and_then(|v| v.parse().ok())
19104 .unwrap_or(0.5);
19105 let encoded = encode_sequence_with_ctx(source, q, deadzone, fctx).unwrap();
19106 wall += start.elapsed().as_secs_f64();
19107 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
19108 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
19109 assert_eq!(
19110 ours.len(),
19111 source.len(),
19112 "{name} q={q}: our decoder's display-order frame count"
19113 );
19114 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
19115 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
19116 panic!(
19117 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
19118 {got}, the encoder reconstructed {want}"
19119 );
19120 }
19121 }
19122 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
19123 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
19124 panic!(
19125 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
19126 {got}, the encoder reconstructed {want}"
19127 );
19128 }
19129 }
19130 let per_frame: Vec<f64> = decoded.iter().zip(source).map(|(d, s)| psnr_all(d, s)).collect();
19131 // lane-txrd: does a tool's loss start at the FIRST inter frame
19132 // (a local mispricing) or grow down the GOP (propagation into
19133 // the reference chain)? One line per q point answers it.
19134 if crate::envflags::env_flag!("EC_AV1_FRAME_PSNR") {
19135 let row: Vec<String> = per_frame.iter().map(|p| format!("{p:.2}")).collect();
19136 eprintln!("{name}: q={q} per-frame PSNR {}", row.join(" "));
19137 // lane-txrd: per PLANE, because an all-plane mean hides a
19138 // collapse in one of them (class `metric blind to a plane`).
19139 let plane = |pick: fn(&Picture) -> &Vec<u16>| -> String {
19140 let v: Vec<String> = decoded
19141 .iter()
19142 .zip(source)
19143 .map(|(d, s)| format!("{:.2}", psnr(pick(d), pick(s))))
19144 .collect();
19145 v.join(" ")
19146 };
19147 eprintln!("{name}: q={q} Y {}", plane(|p| &p.y));
19148 eprintln!("{name}: q={q} U {}", plane(|p| &p.u));
19149 eprintln!("{name}: q={q} V {}", plane(|p| &p.v));
19150 }
19151 let mean: f64 = per_frame.iter().sum::<f64>() / source.len() as f64;
19152 ladder.push((mean, (encoded.stream.len() as f64).log10()));
19153 }
19154 // What this clip asked for and what the content gate left it coding
19155 // under: a screen clip requests a pyramid and codes flat, and that
19156 // difference is what keeps its row identical to the flat baseline
19157 // (class `gate-blind-to-feature`).
19158 eprintln!(
19159 "{name}: sequence, pyramid requested {:?} effective {:?}",
19160 crate::encoder::Pyramid::from_env(),
19161 last_sequence_pyramid(),
19162 );
19163 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19164 (ladder, wall)
19165 }
19166
19167 /// [`our_ladder`] through the streaming facade — the surface the editor's
19168 /// export drives (`EC_AV1_GATE_FACADE=1`). With a [`crate::encoder::Pyramid`]
19169 /// each stream is also reordered (hidden `ALTREF` first,
19170 /// `show_existing_frame` last per group) and each level is coded at its
19171 /// own quantizer offset; without one it is the flat ladder, which
19172 /// `encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
19173 /// pins byte-identical to [`our_ladder`]'s, so this arm must print the
19174 /// same BD numbers. Returns the ladder, the wall, per pyramid level over
19175 /// the whole ladder how many frames and how many bytes it spent, and the
19176 /// pyramid the streams were EFFECTIVELY coded under — the content gate in
19177 /// `Av1Encoder::encode_frames` drops a screen-content clip back to the
19178 /// flat path, so a requested pyramid can come back `None` here.
19179 fn our_ladder_facade(
19180 name: &str,
19181 source: &[Picture],
19182 width: usize,
19183 height: usize,
19184 pyramid: Option<crate::encoder::Pyramid>,
19185 ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4], Option<crate::encoder::Pyramid>) {
19186 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
19187 let slot = |l: Level| match l {
19188 Level::Key => 0,
19189 Level::Arf => 1,
19190 Level::Leaf => 2,
19191 Level::ShowExisting => 3,
19192 };
19193 let mut ladder = Vec::new();
19194 let mut wall = 0.0;
19195 let mut effective = None;
19196 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
19197 for &q in &[150u8, 120, 90, 60] {
19198 let config = EncoderConfig {
19199 width,
19200 height,
19201 base_q_idx: q,
19202 gop: source.len(),
19203 colour: Colour::Unspecified,
19204 tile_cols_log2: 0,
19205 tile_rows_log2: 0,
19206 };
19207 let start = std::time::Instant::now();
19208 let mut enc = match pyramid {
19209 None => Av1Encoder::new(config).unwrap(),
19210 Some(p) => Av1Encoder::with_pyramid(config, p).unwrap(),
19211 };
19212 let mut packets = Vec::new();
19213 for picture in source {
19214 packets.extend(enc.encode_frames(picture).unwrap());
19215 }
19216 packets.extend(enc.flush().unwrap());
19217 wall += start.elapsed().as_secs_f64();
19218 effective = enc.pyramid();
19219 let mut stream = Vec::new();
19220 for p in &packets {
19221 counts[slot(p.level)] += 1;
19222 bytes[slot(p.level)] += p.data.len();
19223 stream.extend_from_slice(&p.data);
19224 }
19225 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
19226 // correct if the DISPLAY-order output still has one frame per
19227 // source picture, in the right order -- checked against our own
19228 // decoder as well as ffmpeg's, both below.
19229 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
19230 assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count");
19231 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
19232 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
19233 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
19234 panic!(
19235 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
19236 decoded {got}, our decoder decoded {want}"
19237 );
19238 }
19239 }
19240 let mean: f64 = decoded
19241 .iter()
19242 .zip(source)
19243 .map(|(d, s)| psnr_all(d, s))
19244 .sum::<f64>()
19245 / source.len() as f64;
19246 ladder.push((mean, (stream.len() as f64).log10()));
19247 }
19248 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
19249 (ladder, wall, counts, bytes, effective)
19250 }
19251
19252 /// Byte-exactness gate for encoder work that is meant to change only
19253 /// how long the encoder takes.
19254 ///
19255 /// The BD gate above measures quality, which a speed lane can move by a
19256 /// hair without failing anything; this pins the streams themselves.
19257 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
19258 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
19259 /// in the tile) and again on lane-av1mv's merge of it: an extra
19260 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
19261 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
19262 /// prices coefficients against the tables the frame's writer really
19263 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
19264 /// decision change the BD gate judges. Re-pinned again on
19265 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
19266 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
19267 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
19268 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
19269 /// search moved with it. Re-pinned on lane-av1rejudge: local warp is on
19270 /// by default ([`warp_on`], a sequence/frame header bit and a new
19271 /// motion_mode symbol on eligible blocks) and
19272 /// [`LEAF_SECOND_NEW_MARGIN`] moved 0.8 -> 1.2. Re-pinned on lane-av1tpl:
19273 /// every inter frame's superblocks now code at their own lambda
19274 /// ([`TPL_STRENGTH`]), so every RD decision in an inter frame moved.
19275 /// Re-pinned on lane-av1resweep: [`LAMBDA_SCALE`] moved 0.05 -> 0.0275
19276 /// and the two var-tx depth searches ([`tx32_depth_search`],
19277 /// [`compound_var_tx`]) are on by default, all three re-judged on the
19278 /// native gate's real film rows.
19279 /// Re-pinned on lane-av1cfl: the chroma search offers `UV_CFL_PRED`, so
19280 /// every block whose chroma takes it codes a different mode symbol, two
19281 /// alpha symbols and different chroma coefficients. `EC_AV1_CFL=0`
19282 /// restores the previous streams. Re-pinned again in the same lane once
19283 /// directional luma winners searched their `angle_delta_y`
19284 /// (`EC_AV1_ANGLE=0` restores that half).
19285 #[test]
19286 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
19287 // These are DEFAULT-PRESET pins: a speed preset switches search levers
19288 // off, so it legitimately moves every byte. Encode at speed 0 whatever
19289 // `EC_AV1_SPEED` says (write guard: the preset is process-global).
19290 let _knobs = crate::speed::knob_write();
19291 let was = crate::speed::speed();
19292 crate::speed::set_speed(0);
19293 if !have_ffmpeg() {
19294 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
19295 return;
19296 }
19297 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
19298 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
19299 if !clip.exists() {
19300 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip");
19301 return;
19302 }
19303 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
19304 // FNV-1a over the stream: a witness that every coded bit is where it
19305 // was, which a byte count alone is not.
19306 let fnv = |b: &[u8]| {
19307 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
19308 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
19309 })
19310 };
19311 // Re-taken on lane-av1pyrdef: `encode_sequence` codes this (non-screen)
19312 // clip under the coding pyramid now -- one hidden ALTREF per mini-GOP
19313 // of 4, its leaves at q+8 and a `show_existing_frame` header per
19314 // group. 7299 -> 8194 bytes at q=150 and 26804 -> 28285 at q=60 over
19315 // four frames; four pictures is one short mini-GOP, which is the
19316 // shape that pays least (the ARF's own quality has no later group to
19317 // carry it), so this is not the BD gate's number.
19318 // Re-taken again on lane-av1cfl: the chroma search offers
19319 // `UV_CFL_PRED` and directional luma winners search `angle_delta_y`,
19320 // so every block taking either codes different syntax and different
19321 // coefficients -- 8194 -> 7321 at q=150 and 28285 -> 27285 at q=60.
19322 // `EC_AV1_CFL=0` / `EC_AV1_ANGLE=0` restore each half.
19323 // Re-taken on lane-pyr3: the mini-GOP of the default pyramid is 16
19324 // pictures at `q-24` / `q+16` now (the sweep in [`Pyramid::default`]),
19325 // so these four pictures code as one truncated group -- a hidden
19326 // ALTREF at `q-24` and three leaves at `q+16` -- instead of one
19327 // mini-GOP of 4 at `q-16` / `q+8`: 7373 -> 8076 at q=150 and
19328 // 27074 -> 27585 at q=60. `EC_AV1_PYRAMID=4:-16:8` restores these.
19329 // Re-taken on lane-fintra: the sequence header sets
19330 // `enable_filter_intra`, so every DC_PRED intra block of at most
19331 // 32x32 without a luma palette carries a `use_filter_intra` flag and
19332 // the blocks that take one code a filter-intra mode, a different
19333 // prediction and different coefficients -- 7321 -> 7373 at q=150 and
19334 // 27285 -> 27074 at q=60. `EC_AV1_FILTER_INTRA=0` restores these.
19335 // Re-taken on lane-b64 (64x64 skip root), at the lane-pyr4 merge
19336 // (default pyramid `8:-32:16`, one truncated group of 8 with its
19337 // hidden ALTREF at `q-32`), and at the lane-tx64 merge: the 64x64
19338 // root can code a REAL residual now (one TX_64X64 luma transform and
19339 // two TX_32X32 chroma ones). `EC_AV1_B64RES=0` restores 8446 / 28548;
19340 // `EC_AV1_B64=0` gives the pre-root bytes under this pyramid.
19341 // Re-taken on lane-keyq: the pyramid codes its KEY FRAME at
19342 // `base_q - 48` now ([`crate::encoder::Pyramid::key_q_offset`]), and
19343 // one of these four pictures is the key -- 8590 -> 9778 at q=150 and
19344 // 28535 -> 35450 at q=60. `EC_AV1_PYRAMID=8:-32:16:-8:0` restores these.
19345 // Re-taken on lane-arfq: the leaves are coded 12 quantizer steps above
19346 // base now, not 16 ([`crate::encoder::Pyramid::leaf_q_offset`]) -- 9778
19347 // -> 9835 at q=150 and 35450 -> 35798 at q=60.
19348 // `EC_AV1_PYRAMID=8:-32:16:-8:-48` restores these.
19349 // Re-taken at the lane-b64b merge, the lane-rdoq merge (`EC_AV1_RDOQ=0`
19350 // gave 9808 / 35791) and the lane-i64 merge: the KEY frame -- one of
19351 // these four pictures -- offers every superblock a 64x64 intra root
19352 // now. `EC_AV1_I64=0` restores 8557 / 33345.
19353 // Re-taken on lane-pricer: the inter RD search prices a single
19354 // reference through the tree and the neighbour contexts the writer
19355 // really codes it with, so every inter picture's reference decisions
19356 // move -- 8562 -> 8535 at q=150 and 33357 -> 33221 at q=60.
19357 // Re-taken on lane-ctx: the RD pricer reads the writer's own contexts
19358 // for `skip`/`is_inter` and for the whole compound reference tree, so
19359 // every inter block's cost -- and with it the skip and reference
19360 // decisions -- moved: 8535 -> 8311 bytes at q=150 and 33221 -> 33087
19361 // at q=60. Re-taken on lane-ctx2: a single-reference candidate now
19362 // pays the `comp_mode = 0` symbol the writer codes ahead of it, so
19363 // single and compound are priced against the same syntax -- 8311 ->
19364 // 8325 bytes at q=150 and 33087 -> 33014 at q=60.
19365 // Re-taken on lane-newmv: the motion search charges its own rate term
19366 // at half the block RD lambda ([`crate::motion::MV_SEARCH_LAMBDA`])
19367 // and each subpel stage re-runs from its own winner
19368 // ([`crate::motion::MV_SUBPEL_ITERS`]), so every inter block's vector
19369 // -- and with it its residual -- moved: 8325 -> 8288 bytes at q=150
19370 // and 33014 -> 33090 at q=60.
19371 // Re-taken on lane-dq: preset 0 codes a per-superblock `delta_qindex`
19372 // from libaom's objective tpl mapping, so every inter picture's
19373 // quantizer grid -- and every decision priced against it -- moved
19374 // (8325 -> 8419 / 33014 -> 33029 on its own base); re-taken once more
19375 // at the merge of both lanes.
19376 // Re-taken on lane-arfq: the top ARF of a mini-GOP codes its
19377 // per-superblock `delta_qindex` at 1.5x the preset's strength
19378 // ([`crate::speed::DQ_LEVEL_K`]), so the hidden frames' quantizer
19379 // grids -- and every decision priced against them -- moved:
19380 // 8252 -> 8269 bytes at q=150 and 33053 -> 33044 at q=60.
19381 // Re-taken on lane-arfpred: the top ARF is coded from a temporally
19382 // FILTERED source ([`crate::speed::ARF_TF`]), so every hidden frame's
19383 // pixels -- and the leaves that predict from them -- moved:
19384 // 8269 -> 8218 bytes at q=150 and 33044 -> 33017 at q=60.
19385 // NOT re-taken on lane-b128: [`SB128_DEFAULT`] stayed off there, so
19386 // the shipped stream did not move.
19387 // Re-taken on lane-b128m, which flips [`SB128_DEFAULT`] on: every
19388 // picture is coded in 128x128 superblocks now, the inter ones
19389 // offering the 128 root's own `PARTITION_NONE` block -- 8327 bytes at
19390 // q=150 and 33194 at q=60. `EC_AV1_SB128=0` restores 8252 / 33053.
19391 // Re-taken at the merge of lane-b128m onto main (128 superblocks on
19392 // by default, on top of the ARF temporal filter).
19393 // Re-taken on lane-b128r: the 128 root now offers the COMPOUND
19394 // candidates the 64 root already did ([`b128_compound`]), so every
19395 // inter frame that carries `reference_select` codes different blocks
19396 // -- 8354 -> 8364 bytes at q=150 and 33222 -> 33257 at q=60.
19397 // `EC_AV1_B128COMP=0` restores 8354 / 33222 exactly.
19398 // Re-taken on lane-arftf: that filter's strength swept on the deciding
19399 // gate lands at 2, not 3 ([`crate::speed::ARF_TF`]), so the filtered
19400 // anchors' pixels moved once more: 8218 -> 8307 bytes at q=150 and
19401 // 33017 at q=60 (the same LENGTH, different bytes).
19402 // Re-taken at the merge of lane-arftf (ARF filter strength 2) and
19403 // lane-rlclamp onto the 128 compound default.
19404 // Re-taken on lane-b128hv: the 128 root now also offers PARTITION_HORZ
19405 // and PARTITION_VERT ([`b128_rect`]), two 128x64 / 64x128 skip blocks,
19406 // so every inter frame whose RD takes one codes a different partition
19407 // -- 8290 -> 8291 bytes at q=150. The q=60 pin does NOT move: at that
19408 // quantizer the rect cut never wins its own comparison on this clip.
19409 // `EC_AV1_B128HV=0` restores 8290 exactly.
19410 let pins: [(u8, usize, u64); 2] = [(150, 8291, 0x1f00bb0eb099a27f), (60, 33227, 0x57ee6b1f8eacd881)];
19411 let coded: Vec<(u8, usize, u64)> = pins
19412 .iter()
19413 .map(|&(q, _, _)| {
19414 let e = encode_sequence(&source, q, 0.5).unwrap();
19415 (q, e.stream.len(), fnv(&e.stream))
19416 })
19417 .collect();
19418 crate::speed::set_speed(was);
19419 for (&(q, bytes, hash), &got) in pins.iter().zip(&coded) {
19420 assert_eq!(got, (q, bytes, hash), "q={q}: the encoder's stream moved");
19421 }
19422 }
19423
19424 /// A ladder is only a ladder if both axes rise together.
19425 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
19426 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
19427 for w in ladder.windows(2) {
19428 assert!(
19429 w[1].0 > w[0].0 && w[1].1 > w[0].1,
19430 "{name}: not monotone, {ladder:?}"
19431 );
19432 }
19433 }
19434
19435 /// The sweep behind [`screen_content`]'s constants
19436 /// (`unswept-decision-constants`), on the SAME five clips
19437 /// [`bd_rate_screen_native`] keeps off (`native_gate_clips`) and at the
19438 /// same native crop: for each colour bound N the share of 16x16 luma
19439 /// blocks with 2..=N distinct colours, and the share of those whose
19440 /// per-pixel variance also clears a floor V -- libaom's
19441 /// `av1_set_screen_content_options` counts the variance-cleared blocks
19442 /// too (its `counts_2`, which gates intrabc), and without that term a
19443 /// smooth dark film frame reads as screen content.
19444 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
19445 #[test]
19446 #[ignore = "reads the real library"]
19447 fn probe_screen_detect() {
19448 let _knobs = crate::speed::knob_read();
19449 if !have_ffmpeg() {
19450 eprintln!("SKIP probe_screen_detect: no ffmpeg");
19451 return;
19452 }
19453 let limits = [4usize, 8, 16, 32, 64, 128];
19454 let floors = [0u64, 4, 16, 64, 256];
19455 // The census of one clip at one size: mean share, over the frames, of
19456 // 16x16 blocks with 2..=N colours whose per-pixel variance is > V.
19457 let census = |label: &str, frames: &[Picture], cw: usize, ch: usize| {
19458 let mut acc = [[0f64; 5]; 6];
19459 for picture in frames {
19460 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
19461 let mut hit = [[0usize; 5]; 6];
19462 let mut blocks = 0usize;
19463 for by in (0..ch).step_by(16) {
19464 for bx in (0..cw).step_by(16) {
19465 let mut seen = [false; 256];
19466 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
19467 for row in 0..16 {
19468 for col in 0..16 {
19469 let v = y[(by + row) * cw + bx + col];
19470 sum += u64::from(v);
19471 sq += u64::from(v) * u64::from(v);
19472 if !seen[usize::from(v)] {
19473 seen[usize::from(v)] = true;
19474 colors += 1;
19475 }
19476 }
19477 }
19478 let var = (sq - sum * sum / 256) / 256;
19479 blocks += 1;
19480 for (li, &limit) in limits.iter().enumerate() {
19481 if colors > 1 && colors <= limit {
19482 for (fi, &floor) in floors.iter().enumerate() {
19483 hit[li][fi] += usize::from(var > floor);
19484 }
19485 }
19486 }
19487 }
19488 }
19489 for li in 0..6 {
19490 for fi in 0..5 {
19491 acc[li][fi] += 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
19492 }
19493 }
19494 }
19495 let n = frames.len().max(1) as f64;
19496 eprintln!("{label} {cw}x{ch}, {} frames -- share of 16x16 blocks with 2..=N colours and per-pixel var > V:", frames.len());
19497 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{f:>8}")).collect::<String>());
19498 for (li, &limit) in limits.iter().enumerate() {
19499 eprintln!(
19500 " {limit:>5} |{}",
19501 (0..5).map(|fi| format!("{:>7.1}%", acc[li][fi] / n)).collect::<String>()
19502 );
19503 }
19504 };
19505 for (name, path, seek) in native_gate_clips() {
19506 let Some((nw, nh)) = probe_dims(&path) else {
19507 eprintln!("SKIP {name}: ffprobe gave no size");
19508 continue;
19509 };
19510 let cw = nw.min(1920) / 128 * 128;
19511 let ch = nh.min(1024) / 128 * 128;
19512 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
19513 let frames = clip_frames_vf(&path, &seek, &format!("crop={cw}:{ch}:{x}:{y0}"), cw, ch, 12);
19514 census(&name, &frames, cw, ch);
19515 // The 640x384 gate scales instead of cropping, and the scaling
19516 // changes the census (bars smooth out): the constants have to
19517 // separate at BOTH sizes.
19518 let small = clip_frames(&path, &seek, 640, 384, 12);
19519 census(&name, &small, 640, 384);
19520 }
19521 }
19522
19523 /// The detector against the WHOLE real library (class
19524 /// `unswept-decision-constants`, user rule "his data is the gate"):
19525 /// every VIDEO row of `fixtures/real-library-manifest.tsv` -- plus the
19526 /// two colour-bar fixtures as anchors -- decoded at 10/50/90% of its
19527 /// duration, four frames each, 8-bit 4:2:0, at native size or a
19528 /// 1920x1080 centred crop when larger (the crop keeps a capture's exact
19529 /// repeats, which a downscale destroys -- class `gate-recipe-confound`).
19530 /// Prints per file and offset the share of qualifying 16x16 blocks, the
19531 /// [`screen_content`] verdict and a content hint (mean luma, luma
19532 /// standard deviation, inter MAD), then sweeps the colour bound against
19533 /// the variance floor over the whole library: for each (N, V) the worst
19534 /// (highest) share among the camera/film rows against the best (lowest)
19535 /// among the screen-recording rows, so the rule with the widest gap can
19536 /// be read off. Rows carry the manifest index, codec and size only --
19537 /// no titles, no home paths.
19538 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_library --nocapture`
19539 #[test]
19540 #[ignore = "reads the real library"]
19541 fn probe_screen_library() {
19542 let _knobs = crate::speed::knob_read();
19543 if !have_ffmpeg() {
19544 eprintln!("SKIP probe_screen_library: no ffmpeg");
19545 return;
19546 }
19547 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
19548 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
19549 eprintln!("SKIP probe_screen_library: no real-library manifest");
19550 return;
19551 };
19552 let limits = [4usize, 8, 16, 32, 64];
19553 let floors = [0u64, 4, 8, 16, 32, 64, 128];
19554 // Whatever ffmpeg gave us, without the exact-count assertion the
19555 // gate loaders make: a seek near the end of a clip returns fewer
19556 // frames, and that is a row to print, not a panic.
19557 let decode = |clip: &str, seek: &str, vf: &str, w: usize, h: usize, n: usize| -> Vec<Picture> {
19558 let out = Command::new("ffmpeg")
19559 .args(["-v", "error", "-ss", seek, "-i", clip])
19560 .args(["-frames:v", &n.to_string()])
19561 .args(["-vf", vf])
19562 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
19563 .output();
19564 let Ok(out) = out else { return Vec::new() };
19565 if !out.status.success() {
19566 return Vec::new();
19567 }
19568 let (luma, chroma) = (w * h, w * h / 4);
19569 let frame_len = luma + 2 * chroma;
19570 (0..out.stdout.len() / frame_len)
19571 .map(|i| {
19572 let b = &out.stdout[i * frame_len..][..frame_len];
19573 Picture {
19574 width: w,
19575 height: h,
19576 y: b[..luma].iter().map(|&v| u16::from(v)).collect(),
19577 u: b[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
19578 v: b[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
19579 }
19580 })
19581 .collect()
19582 };
19583 // Share (%) of 16x16 blocks with 2..=N colours and per-pixel
19584 // variance > V, for every (N, V) of the sweep grid, over one frame.
19585 let census = |y: &[u8], w: usize, h: usize| -> [[f64; 7]; 5] {
19586 let mut hit = [[0usize; 7]; 5];
19587 let mut blocks = 0usize;
19588 for by in (0..h).step_by(16) {
19589 for bx in (0..w).step_by(16) {
19590 let (bh, bw) = ((h - by).min(16), (w - bx).min(16));
19591 let mut seen = [false; 256];
19592 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
19593 for row in 0..bh {
19594 for col in 0..bw {
19595 let v = y[(by + row) * w + bx + col];
19596 sum += u64::from(v);
19597 sq += u64::from(v) * u64::from(v);
19598 if !seen[usize::from(v)] {
19599 seen[usize::from(v)] = true;
19600 colors += 1;
19601 }
19602 }
19603 }
19604 let n = (bh * bw) as u64;
19605 let var = (sq - sum * sum / n) / n;
19606 blocks += 1;
19607 for (li, &limit) in limits.iter().enumerate() {
19608 if colors > 1 && colors <= limit {
19609 for (fi, &floor) in floors.iter().enumerate() {
19610 hit[li][fi] += usize::from(var > floor);
19611 }
19612 }
19613 }
19614 }
19615 }
19616 let mut out = [[0f64; 7]; 5];
19617 for li in 0..5 {
19618 for fi in 0..7 {
19619 out[li][fi] = 100.0 * hit[li][fi] as f64 / blocks.max(1) as f64;
19620 }
19621 }
19622 out
19623 };
19624 // (index, label, path, duration, screen-by-its-own-content). The
19625 // OBS directory and the OBS file-name shape ("YYYY-MM-DD HH-MM-SS")
19626 // are desktop recordings; everything else in this library is camera
19627 // or film material.
19628 let mut rows: Vec<(String, String, String, f64, bool)> = Vec::new();
19629 for (label, file) in [("bars 1080p", "h264-1080p-23.976-8bit.mp4"), ("bars 2160p", "h264-2160p-23.976-8bit.mp4")] {
19630 let path = fixtures.join("video").join(file);
19631 if path.exists() {
19632 rows.push(("fx".into(), label.into(), path.to_str().unwrap().into(), 10.0, false));
19633 }
19634 }
19635 for (i, line) in manifest.lines().skip(1).enumerate() {
19636 let f: Vec<&str> = line.split('\t').collect();
19637 if f.len() < 10 {
19638 continue;
19639 }
19640 let (path, codec) = (f[0], f[2]);
19641 if codec == "-" || codec.is_empty() {
19642 continue;
19643 }
19644 let (Ok(w), Ok(h)) = (f[3].parse::<usize>(), f[4].parse::<usize>()) else {
19645 eprintln!("SKIP {}: manifest carries no coded size", i + 1);
19646 continue;
19647 };
19648 if !std::path::Path::new(path).exists() {
19649 eprintln!("SKIP {}: file is gone", i + 1);
19650 continue;
19651 }
19652 let name = path.rsplit('/').next().unwrap_or(path);
19653 let is_capture = path.contains("/OBS/")
19654 || (name.len() > 19
19655 && name.as_bytes()[4] == b'-'
19656 && name.as_bytes()[7] == b'-'
19657 && name.as_bytes()[10] == b' '
19658 && name.as_bytes()[13] == b'-');
19659 rows.push((
19660 format!("{}", i + 1),
19661 format!("{codec} {w}x{h}"),
19662 path.to_string(),
19663 f[8].parse::<f64>().unwrap_or(0.0),
19664 is_capture,
19665 ));
19666 }
19667 // Per (N, V): the worst camera/film row and the best screen row, so
19668 // the separation of the whole library is one subtraction.
19669 let (mut cam_max, mut scr_min) = ([[0f64; 7]; 5], [[100f64; 7]; 5]);
19670 eprintln!("| idx | codec size | class | offset | qualifying blocks | verdict | mean/sd/MAD |");
19671 for (idx, label, path, dur, is_capture) in &rows {
19672 let Some((nw, nh)) = probe_dims(path) else {
19673 eprintln!("SKIP {idx}: ffprobe gave no size");
19674 continue;
19675 };
19676 let (cw, ch) = (nw.min(1920) & !1, nh.min(1080) & !1);
19677 let (x, y0) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
19678 let vf = format!("crop={cw}:{ch}:{x}:{y0}");
19679 let mut file_grid = [[0f64; 7]; 5];
19680 let mut file_frames = 0usize;
19681 for pct in [10u32, 50, 90] {
19682 let seek = format!("{:.3}", dur * f64::from(pct) / 100.0);
19683 let frames = decode(path, &seek, &vf, cw, ch, 4);
19684 if frames.is_empty() {
19685 eprintln!("| {idx} | {label} | {} | {pct}% | SKIP: ffmpeg decoded no frame here |", if *is_capture { "screen" } else { "camera" });
19686 continue;
19687 }
19688 let (mut share, mut yes, mut mean, mut sd, mut mad) = (0f64, 0usize, 0f64, 0f64, 0f64);
19689 let mut prev: Option<Vec<u8>> = None;
19690 for picture in &frames {
19691 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
19692 let grid = census(&y, cw, ch);
19693 for li in 0..5 {
19694 for fi in 0..7 {
19695 file_grid[li][fi] += grid[li][fi];
19696 }
19697 }
19698 file_frames += 1;
19699 // The shipped rule is (16 colours, var > 16): grid row 2,
19700 // floor 16 is column 3.
19701 share += grid[2][3];
19702 yes += usize::from(screen_content(&y, cw, cw, ch));
19703 let n = y.len() as f64;
19704 let sum: f64 = y.iter().map(|&v| f64::from(v)).sum();
19705 let sq: f64 = y.iter().map(|&v| f64::from(v) * f64::from(v)).sum();
19706 mean += sum / n;
19707 sd += (sq / n - (sum / n) * (sum / n)).max(0.0).sqrt();
19708 if let Some(p) = &prev {
19709 mad += p.iter().zip(&y).map(|(&a, &b)| f64::from(a.abs_diff(b))).sum::<f64>() / n;
19710 }
19711 prev = Some(y);
19712 }
19713 let f = frames.len() as f64;
19714 eprintln!(
19715 "| {idx} | {label} | {} | {pct}% | {:.1}% | {} ({yes}/{} frames) | {:.0}/{:.1}/{:.2} |",
19716 if *is_capture { "screen" } else { "camera" },
19717 share / f,
19718 if yes * 2 > frames.len() { "SCREEN" } else { "camera" },
19719 frames.len(),
19720 mean / f,
19721 sd / f,
19722 mad / (f - 1.0).max(1.0),
19723 );
19724 }
19725 if file_frames == 0 {
19726 continue;
19727 }
19728 for li in 0..5 {
19729 for fi in 0..7 {
19730 let s = file_grid[li][fi] / file_frames as f64;
19731 match is_capture {
19732 true => scr_min[li][fi] = scr_min[li][fi].min(s),
19733 false => cam_max[li][fi] = cam_max[li][fi].max(s),
19734 }
19735 }
19736 }
19737 }
19738 eprintln!("sweep over the whole library -- worst camera/film share vs best screen share, per (N colours, var > V):");
19739 eprintln!(" N \\ V |{}", floors.iter().map(|f| format!("{:>18}", format!("V>{f}"))).collect::<String>());
19740 let (mut best, mut best_rule) = (f64::MIN, (16usize, 16u64));
19741 for (li, &limit) in limits.iter().enumerate() {
19742 let mut row = String::new();
19743 for fi in 0..7 {
19744 let (c, s) = (cam_max[li][fi], scr_min[li][fi]);
19745 row.push_str(&format!("{:>18}", format!("{c:.1}/{s:.1} {:+.1}", s - c)));
19746 if s - c > best {
19747 best = s - c;
19748 best_rule = (limit, floors[fi]);
19749 }
19750 }
19751 eprintln!(" {limit:>5} |{row}");
19752 }
19753 // The threshold sits at the midpoint of the widest gap; the shipped
19754 // constant is its reciprocal in whole parts of the frame.
19755 let (li, fi) = (
19756 limits.iter().position(|&l| l == best_rule.0).unwrap(),
19757 floors.iter().position(|&f| f == best_rule.1).unwrap(),
19758 );
19759 let mid = (cam_max[li][fi] + scr_min[li][fi]) / 2.0;
19760 eprintln!(
19761 "widest split: {} colours, var > {}, gap {:+.1} points (camera <= {:.1}%, screen >= {:.1}%); threshold {:.1}% = EC_AV1_SCREEN_PCT {}",
19762 best_rule.0,
19763 best_rule.1,
19764 best,
19765 cam_max[li][fi],
19766 scr_min[li][fi],
19767 mid,
19768 (100.0 / mid.max(0.1)).round() as usize,
19769 );
19770 }
19771
19772 /// The missing instrument: what this encoder costs against libaom and
19773 /// rav1e at matched fidelity, and how long it takes to get there.
19774 ///
19775 /// Recipe, identical on all three sides: 12 consecutive frames of each
19776 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
19777 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
19778 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
19779 /// it by default), 4:2:0 8-bit in and out. Reference points:
19780 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
19781 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
19782 /// tile_cols=1:tile_rows=1:threads=1`
19783 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
19784 /// ffmpeg-decoded frames of each encoder's own stream.
19785 ///
19786 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
19787 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
19788 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
19789 /// four encodes of that ladder together):
19790 ///
19791 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
19792 /// |---|---|---|---|---|
19793 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
19794 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
19795 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
19796 ///
19797 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
19798 /// the encoder takes -- every stream it writes is byte-identical, so the
19799 /// BD columns are this box's own re-run of the same recipe rather than a
19800 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
19801 /// rav1e). What moved is the wall of the four encodes:
19802 ///
19803 /// | clip | wall ours before | after | instructions:u before -> after |
19804 /// |---|---|---|---|
19805 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
19806 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
19807 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
19808 ///
19809 /// Three exact steps, none of which touches a coded bit: the coefficient
19810 /// rate pricer stopped rebuilding every CDF table per candidate
19811 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
19812 /// tile once per candidate (`decode::FilterReplay`), and the forward
19813 /// transform stopped transforming the all-zero residual that 70% of its
19814 /// calls carry.
19815 ///
19816 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
19817 ///
19818 /// | step | 1080p | 2160p | screen |
19819 /// |---|---|---|---|
19820 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
19821 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
19822 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
19823 ///
19824 /// Re-measured for the record 2026-09-07 (lane-av1resweep), after
19825 /// [`LAMBDA_SCALE`] moved 0.05 -> 0.0275 and the two var-tx depth
19826 /// searches ([`tx32_depth_search`], [`compound_var_tx`]) became defaults
19827 /// -- all three decided on the REAL film rows of
19828 /// [`bd_rate_screen_native`], which this downscaled recipe does not
19829 /// carry:
19830 ///
19831 /// | clip | BD vs libaom | BD vs rav1e | wall ours:libaom:rav1e |
19832 /// |---|---|---|---|
19833 /// | bars 1080p | +68.8% | +26.2% | 5.8s:1.2s:2.7s |
19834 /// | bars 2160p | +81.6% | +41.5% | 4.8s:1.0s:2.2s |
19835 /// | screen capture | +49.1% | -4.3% | 5.5s:1.0s:2.1s |
19836 ///
19837 /// RE-RECORDED 2026-09-07 (lane-av1pyrdef), with the coding pyramid the
19838 /// DEFAULT of the sequence path this gate codes through -- the bars are
19839 /// non-screen so they take it, the capture is gated flat:
19840 ///
19841 /// | clip | effective pyramid | BD vs libaom | BD vs rav1e | wall |
19842 /// |---|---|---|---|---|
19843 /// | bars 1080p | 4:-16:8 | +84.7% | +39.9% | 5.1s:1.1s:2.6s |
19844 /// | bars 2160p | 4:-16:8 | +124.4% | +75.2% | 4.4s:1.0s:2.8s |
19845 /// | screen capture | none (gated) | +49.1% | -4.3% | 6.5s:1.2s:2.3s |
19846 ///
19847 /// Those are, to the byte, the numbers lane-av1pyrgate recorded for the
19848 /// same clips under `EC_AV1_PYRAMID=4:-16:8 EC_AV1_GATE_FACADE=1` -- the
19849 /// facade arm -- which is what "one mini-GOP driver, two entry points"
19850 /// means here. This downscaled recipe HATES the pyramid (as it hates
19851 /// every knob the real film rows of `bd_rate_screen_native` keep, which
19852 /// is why it decides nothing); `EC_AV1_PYRAMID=0` restores the flat rows
19853 /// above. The capture's row is the flat row to the byte in both runs --
19854 /// that equality IS the content gate.
19855 ///
19856 /// Loop restoration is NOT in yet: it is the one filter whose parameters
19857 /// are per restoration UNIT inside the tile payload, so it needs both
19858 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
19859 /// buffer to solve against -- neither of which this frame-header-level
19860 /// search reaches.
19861 ///
19862 /// The baseline it replaced, before an inter frame's blocks chose their
19863 /// own partition, was +501.4/+504.4/+440.9 against libaom and
19864 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
19865 ///
19866 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
19867 /// fidelity, while spending far more time than either (the partition
19868 /// search's own cost, uncut: see the two intra-pruning variants measured
19869 /// and rejected in the lane report). No
19870 /// threshold is asserted yet -- this run sets the baseline; the gate
19871 /// asserts four monotone points per ladder, and at EVERY ladder point of
19872 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
19873 /// `crate::stream::decode_stream` -- and asserts the encoder's
19874 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
19875 /// and V over every shown frame in display order. A failure names the
19876 /// clip, the q, the frame, the plane and the first differing sample.
19877 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
19878 /// which exposes no per-packet reconstruction, so that path asserts the
19879 /// two decoders against each other on all three planes.)
19880 ///
19881 /// Run:
19882 /// cargo test -p ec-av1 --release --lib -- --ignored \
19883 /// bd_rate_vs_libaom_and_rav1e --nocapture
19884 #[test]
19885 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
19886 fn bd_rate_vs_libaom_and_rav1e() {
19887 let _knobs = crate::speed::knob_write();
19888 if !have_ffmpeg() {
19889 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
19890 return;
19891 }
19892 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
19893 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
19894 // testsrc2 COLOUR BARS, not film -- labelled so no reader takes these
19895 // rows for real content (the real rows live in the native gate).
19896 for (label, name) in [
19897 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
19898 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
19899 ] {
19900 let path = fixtures.join("video").join(name);
19901 if path.exists() {
19902 clips.push((label.to_string(), path));
19903 } else {
19904 eprintln!("SKIP clip {name}: missing");
19905 }
19906 }
19907 // Screen capture: the repo carries no screen-capture fixture, so take
19908 // the first OBS recording the real-library manifest names.
19909 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
19910 Ok(manifest) => {
19911 let screen = manifest
19912 .lines()
19913 .skip(1)
19914 .filter_map(|l| l.split('\t').next())
19915 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists());
19916 match screen {
19917 Some(p) => clips.push((
19918 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
19919 std::path::PathBuf::from(p),
19920 )),
19921 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
19922 }
19923 }
19924 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
19925 }
19926 assert!(!clips.is_empty(), "no source clip available");
19927
19928 let (width, height, frames) = (640usize, 384usize, 12usize);
19929 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
19930 .iter()
19931 .map(|q| {
19932 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
19933 .map(String::from)
19934 .to_vec()
19935 })
19936 .collect();
19937 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
19938 .iter()
19939 .map(|q| {
19940 vec![
19941 "-rav1e-params".to_string(),
19942 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
19943 ]
19944 })
19945 .collect();
19946 println!(
19947 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
19948 );
19949 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |");
19950 println!("|---|---|---|---|---|");
19951 for (name, path) in &clips {
19952 let fctx = &crate::decode::FrameCtx::for_encoder();
19953 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
19954 let _ = take_partition_hits();
19955 let _ = crate::tile::take_palette_hits();
19956 SCREEN_FRAMES.iter().for_each(|c| {
19957 c.store(0, std::sync::atomic::Ordering::Relaxed);
19958 });
19959 let _ = take_uv_mode_hits();
19960 let _ = crate::tile::take_inter_mode_hits();
19961 let _ = crate::tile::take_drl_hits();
19962 let _ = crate::tile::take_ref_hits();
19963 let _ = crate::tile::take_compound_mode_hits();
19964 let _ = crate::tile::take_compound_pair_hits();
19965 let _ = crate::tile::take_compound_size_hits();
19966 let _ = crate::tile::take_compound_leaf_mode_hits();
19967 let _ = take_b64_root_hits();
19968 let _ = take_b64_residual_hits();
19969 let _ = take_b64_compound_hits();
19970 let _ = crate::motion::take_census();
19971 // The entry-surface arm: run the SAME ladder through the
19972 // streaming facade the editor's export calls, which must print
19973 // the same BD numbers as the sequence path -- byte for byte the
19974 // same stream now that both drive one mini-GOP driver
19975 // (lane-av1pyrdef).
19976 let facade = std::env::var_os("EC_AV1_GATE_FACADE").is_some();
19977 let (ours, ours_wall) = match facade {
19978 false => our_ladder(name, &source, width, height, fctx),
19979 true => {
19980 let pyramid = crate::encoder::Pyramid::from_env();
19981 let (ladder, wall, counts, bytes, effective) =
19982 our_ladder_facade(name, &source, width, height, pyramid);
19983 eprintln!(
19984 "{name}: facade, pyramid requested {pyramid:?} effective \
19985 {effective:?} -- frames key {} arf {} leaf {} \
19986 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
19987 counts[0], counts[1], counts[2], counts[3],
19988 bytes[0], bytes[1], bytes[2], bytes[3],
19989 );
19990 (ladder, wall)
19991 }
19992 };
19993 // How often the inter split actually fired over this clip's four
19994 // encodes, against the whole 32x32 that was the only outcome
19995 // before (gate-blind-to-feature).
19996 let [whole32, split32, whole16, split16] = take_partition_hits();
19997 // Which inter modes actually fired over this clip's four encodes,
19998 // and at which DRL index -- a mode nobody picks is a mode the BD
19999 // number cannot be crediting (gate-blind-to-feature).
20000 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
20001 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
20002 let refs = crate::tile::take_ref_hits();
20003 let modes_total = (nearest + near + global + new).max(1);
20004 eprintln!(
20005 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
20006 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
20007 {drl0}/{drl1}/{drl2}/{drl3}",
20008 100.0 * nearest as f64 / modes_total as f64,
20009 100.0 * near as f64 / modes_total as f64,
20010 100.0 * global as f64 / modes_total as f64,
20011 100.0 * new as f64 / modes_total as f64,
20012 );
20013 // The compound census: what share of the coded inter blocks took
20014 // a compound reference at all, which compound mode they took, and
20015 // which pair (gate-blind-to-feature -- a compound mode nobody
20016 // picks cannot be what a BD number credits).
20017 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
20018 // superblocks were left whole at all, and how many of those coded
20019 // a residual or took a compound reference.
20020 let (roots, root_res, root_comp) = (
20021 take_b64_root_hits(),
20022 take_b64_residual_hits(),
20023 take_b64_compound_hits(),
20024 );
20025 eprintln!(
20026 "{name}: 64x64 roots {roots} (with a residual {root_res}, compound {root_comp})"
20027 );
20028 let comp_modes = crate::tile::take_compound_mode_hits();
20029 let comp_pairs = crate::tile::take_compound_pair_hits();
20030 let comp_sizes = crate::tile::take_compound_size_hits();
20031 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
20032 let comp_total: usize = comp_modes.iter().sum();
20033 eprintln!(
20034 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
20035 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
20036 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
20037 modes_total + comp_total,
20038 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
20039 comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3],
20040 comp_modes[6], comp_modes[7],
20041 comp_pairs[3], comp_pairs[6],
20042 );
20043 eprintln!(
20044 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
20045 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
20046 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6],
20047 comp_leaf[7],
20048 );
20049 eprintln!(
20050 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
20051 comp_sizes[1], comp_sizes[2], comp_sizes[3],
20052 );
20053 // Where the wall-owning stage actually goes: how many candidate
20054 // evaluations (one `mc::predict` + SAD each) a search spends, how
20055 // many of them are subpel, and how often the winner is the seed
20056 // it started from -- the census the seeded search is judged by.
20057 let [calls, evals, subpel, rounds, near_pred, unmoved, widest, widest_moves] =
20058 crate::motion::take_census();
20059 let per = |n: u64| n as f64 / calls.max(1) as f64;
20060 eprintln!(
20061 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
20062 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
20063 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
20064 per(evals),
20065 100.0 * subpel as f64 / evals.max(1) as f64,
20066 per(rounds),
20067 100.0 * near_pred as f64 / calls.max(1) as f64,
20068 100.0 * unmoved as f64 / calls.max(1) as f64,
20069 );
20070 // lane-newmv, class `instrument at bound`: how often the winner
20071 // was walked to at the log stage's own WIDEST step -- a high
20072 // share means the search stops where its step lets it, not where
20073 // the content is.
20074 eprintln!(
20075 "{name}: motion search moved at the widest step in {:.1}% of calls ({:.2} such moves/call)",
20076 100.0 * widest as f64 / calls.max(1) as f64,
20077 per(widest_moves),
20078 );
20079 eprintln!(
20080 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
20081 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
20082 );
20083 eprintln!(
20084 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
20085 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
20086 whole32 + split32,
20087 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
20088 whole16 + split16,
20089 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
20090 );
20091 // The deblocking level each of this clip's frames chose
20092 // (lane-av1filt): 0 everywhere would mean the filter never fires.
20093 let levels = crate::filter_search::take_chosen_levels();
20094 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
20095 let mean = |f: fn(&Chosen) -> u8| {
20096 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
20097 };
20098 eprintln!(
20099 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
20100 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
20101 levels.len(),
20102 mean(|l| l.0.0),
20103 mean(|l| l.0.1),
20104 mean(|l| l.1.0),
20105 mean(|l| l.1.1),
20106 mean(|l| l.2.0),
20107 mean(|l| l.2.1),
20108 );
20109 // How many strength presets each frame's CDEF list carried and
20110 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
20111 // everywhere would mean the per-unit choice never fires.
20112 let presets = crate::filter_search::take_cdef_presets();
20113 let mut by_bits = [0usize; 4];
20114 for (b, _) in &presets {
20115 by_bits[usize::from(*b)] += 1;
20116 }
20117 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
20118 let on_extra: usize = presets
20119 .iter()
20120 .flat_map(|(_, c)| c.iter().skip(1))
20121 .sum();
20122 eprintln!(
20123 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
20124 on a non-default preset ({:.1}%)",
20125 by_bits[0],
20126 by_bits[1],
20127 by_bits[2],
20128 by_bits[3],
20129 on_extra,
20130 units,
20131 100.0 * on_extra as f64 / units.max(1) as f64
20132 );
20133 // How the 64x64 luma restoration units split between
20134 // RESTORE_NONE and Wiener (lane-av1lr).
20135 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
20136 eprintln!(
20137 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
20138 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
20139 );
20140 // Which chroma modes the search actually wins with, against the
20141 // unconditional DC_PRED that was the only outcome before
20142 // (gate-blind-to-feature).
20143 // Screen-content detection and the palette it turns on
20144 // (gate-blind-to-feature): how many frames set
20145 // `allow_screen_content_tools`, how many blocks took a palette,
20146 // and of what size. A film clip must print `screen frames on=0`.
20147 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
20148 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
20149 // Which tables the SEARCH priced against, per frame arming
20150 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
20151 // real starting ones. A film clip must show every inter arming on
20152 // the real side, a screen clip none of them.
20153 let (price_default, price_real) = crate::tile::take_pricing_hits();
20154 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
20155 let palette = crate::tile::take_palette_hits();
20156 eprintln!(
20157 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
20158 palette[0],
20159 (2..=8)
20160 .filter(|&n| palette[n] > 0)
20161 .map(|n| format!("{n}={}", palette[n]))
20162 .collect::<Vec<_>>()
20163 .join(" ")
20164 );
20165 // The CfL alpha histogram (lane-av1cfl): one entry per chroma
20166 // plane of every `UV_CFL_PRED` block, by |alpha_q3|. A tool that
20167 // only ever fires at one magnitude is a search that never left
20168 // its first candidate (gate-blind-to-feature).
20169 // The luma angle-delta histogram (lane-av1cfl): how many
20170 // directional blocks won at each delta. All-zero would mean the
20171 // refinement never beat the base angle.
20172 let deltas = take_angle_delta_hits();
20173 if deltas.iter().sum::<usize>() > 0 {
20174 eprintln!(
20175 "{name}: angle_delta_y {}",
20176 deltas
20177 .iter()
20178 .enumerate()
20179 .map(|(d, &n)| format!("{:+}={n}", d as i32 - 3))
20180 .collect::<Vec<_>>()
20181 .join(" ")
20182 );
20183 }
20184 let alphas = take_cfl_alpha_hits();
20185 if alphas.iter().sum::<usize>() > 0 {
20186 eprintln!(
20187 "{name}: cfl |alpha| {}",
20188 alphas
20189 .iter()
20190 .enumerate()
20191 .filter(|&(_, &n)| n > 0)
20192 .map(|(a, &n)| format!("{a}={n}"))
20193 .collect::<Vec<_>>()
20194 .join(" ")
20195 );
20196 }
20197 let palette_uv = crate::tile::take_palette_uv_hits();
20198 eprintln!(
20199 "{name}: chroma palette blocks {} sizes {}",
20200 palette_uv[0],
20201 (2..=8)
20202 .filter(|&n| palette_uv[n] > 0)
20203 .map(|n| format!("{n}={}", palette_uv[n]))
20204 .collect::<Vec<_>>()
20205 .join(" ")
20206 );
20207 let uv = take_uv_mode_hits();
20208 let uv_total: usize = uv.iter().sum();
20209 eprintln!(
20210 "{name}: uv modes {}",
20211 uv.iter()
20212 .enumerate()
20213 .filter(|&(_, &n)| n > 0)
20214 .map(|(m, &n)| format!(
20215 "{}={n} ({:.1}%)",
20216 UV_MODE_NAMES[m],
20217 100.0 * n as f64 / uv_total.max(1) as f64
20218 ))
20219 .collect::<Vec<_>>()
20220 .join(" ")
20221 );
20222 // Which transform depth the intra blocks of this clip's key
20223 // frames resolved to (lane-av1tx): depth 0 is one transform over
20224 // the whole block, 1 and 2 its halvings.
20225 let depths = take_tx_depth_hits();
20226 let depth_total: usize = depths.iter().sum();
20227 eprintln!(
20228 "{name}: intra tx depths {}",
20229 depths
20230 .iter()
20231 .enumerate()
20232 .map(|(d, &n)| format!(
20233 "{d}={n} ({:.1}%)",
20234 100.0 * n as f64 / depth_total.max(1) as f64
20235 ))
20236 .collect::<Vec<_>>()
20237 .join(" ")
20238 );
20239 print_inter_tx_census(name);
20240 // lane-av1obmc: how many blocks actually CODED a motion_mode
20241 // symbol and which value they took, by footprint -- "OBMC is on"
20242 // as a measurement rather than a claim (class
20243 // `gate-blind-to-feature`).
20244 let mm = crate::tile::take_motion_mode_hits();
20245 eprintln!(
20246 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
20247 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
20248 eligible)",
20249 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
20250 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20251 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20252 mm.iter().sum::<usize>(),
20253 );
20254 let (aom, aom_wall) =
20255 external_ladder(&source, width, height, "libaom-av1", &aom_points);
20256 let (rav1e, rav1e_wall) =
20257 external_ladder(&source, width, height, "librav1e", &rav1e_points);
20258 assert_monotone(&format!("{name}: ours"), &ours);
20259 assert_monotone(&format!("{name}: libaom"), &aom);
20260 assert_monotone(&format!("{name}: rav1e"), &rav1e);
20261 let points = ours
20262 .iter()
20263 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20264 .collect::<Vec<_>>()
20265 .join(", ");
20266 println!(
20267 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
20268 bd_rate(&aom, &ours) * 100.0,
20269 bd_rate(&rav1e, &ours) * 100.0,
20270 );
20271 println!(
20272 "| references | libaom {} | rav1e {} | | |",
20273 aom.iter()
20274 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20275 .collect::<Vec<_>>()
20276 .join(", "),
20277 rav1e
20278 .iter()
20279 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20280 .collect::<Vec<_>>()
20281 .join(", "),
20282 );
20283 }
20284 assert_ladder_decodes();
20285 }
20286 /// Which var-tx depth this clip's INTER blocks resolved to (lane-av1tx2,
20287 /// split by block class in lane-av1txdepth): depth 0 is one transform over
20288 /// the whole block, 1 its four halves; the classes are the 16x16/8x8
20289 /// leaves and the 32x32 root, each single-reference or compound. A class
20290 /// with no counts at all never reached `commit_inter_luma` -- which is
20291 /// what its knob being off looks like (class `gate-blind-to-feature`).
20292 fn print_inter_tx_census(name: &str) {
20293 let splits = take_inter_tx_split_hits();
20294 let total: usize = splits.iter().sum();
20295 let row = |label: &str, base: usize| {
20296 let (n0, n1) = (splits[base], splits[base + 1]);
20297 format!(
20298 "{label} 0={n0} 1={n1} ({:.1}% split)",
20299 100.0 * n1 as f64 / (n0 + n1).max(1) as f64
20300 )
20301 };
20302 eprintln!(
20303 "{name}: inter var-tx depths of {total} blocks -- {} | {} | {} | {}",
20304 row("leaf single", 0),
20305 row("leaf compound", 2),
20306 row("32x32 single", 4),
20307 row("32x32 compound", 6),
20308 );
20309 // lane-txrd: which types the two searches actually COMMITTED over
20310 // this row's four encodes -- the gate could not say whether a type
20311 // search fired at all (class `gate-blind-to-feature`).
20312 const NAMES: [&str; 16] = [
20313 "IDTX", "DCT_DCT", "ADST_ADST", "ADST_DCT", "DCT_ADST", "V_DCT", "H_DCT",
20314 "FLIPADST_DCT", "DCT_FLIPADST", "FLIPADST_FLIPADST", "ADST_FLIPADST",
20315 "FLIPADST_ADST", "V_ADST", "H_ADST", "V_FLIPADST", "H_FLIPADST",
20316 ];
20317 let name_of = |t: usize| NAMES[t];
20318 for (label, hits) in [("inter", take_inter_tx_type_hits()), ("intra", take_tx_type_hits())] {
20319 let total: usize = hits.iter().sum();
20320 let live: Vec<String> = hits
20321 .iter()
20322 .enumerate()
20323 .filter(|&(_, &n)| n > 0)
20324 .map(|(t, &n)| format!("{}={n} ({:.1}%)", name_of(t), 100.0 * n as f64 / total.max(1) as f64))
20325 .collect();
20326 eprintln!("{name}: {label} tx_type of {total} units -- {}", live.join(" "));
20327 }
20328 let t = take_txrd_stats();
20329 if t[0] > 0 {
20330 eprintln!(
20331 "{name}: txrd flat decisions={} chosen sse={} bits={:.0} | DCT_DCT sse={} \
20332 bits={:.0} (dsse {:+.2}%, dbits {:+.2}%)",
20333 t[0], t[1], t[3] as f64 / 64.0, t[2], t[4] as f64 / 64.0,
20334 100.0 * (t[1] as f64 - t[2] as f64) / t[2].max(1) as f64,
20335 100.0 * (t[3] as f64 - t[4] as f64) / t[4].max(1) as f64,
20336 );
20337 eprintln!(
20338 "{name}: txrd DCT_DCT re-predicted HERE sse={} bits={:.0} (vs the passed-in \
20339 flat: dsse {:+.2}%, dbits {:+.2}%)",
20340 t[5], t[6] as f64 / 64.0,
20341 100.0 * (t[5] as f64 - t[2] as f64) / t[2].max(1) as f64,
20342 100.0 * (t[6] as f64 - t[4] as f64) / t[4].max(1) as f64,
20343 );
20344 }
20345 }
20346
20347 /// The video stream's coded size, from ffprobe.
20348 fn probe_dims(clip: &str) -> Option<(usize, usize)> {
20349 crate::probe::dims(clip)
20350 }
20351
20352 /// `EC_AV1_NATIVE_CROP=<width>x<height>`: the native gate's window at a
20353 /// size of the reader's choosing instead of [`crate::probe::gate_crop`]'s
20354 /// superblock-aligned one, still centred and still even for 4:2:0.
20355 ///
20356 /// WHY IT EXISTS (lane-sse): `gate_crop` rounds DOWN to whole 128-wide
20357 /// superblocks by design, so no default gate row has a block the frame
20358 /// edge cuts through -- while every arbitrary export size does (3840x1608
20359 /// is 25.1 superblock rows, 1920x1080 is 8.4). `EC_AV1_NATIVE_CROP=
20360 /// 1920x1080` is the straddling arm the edge-clipped distortion score is
20361 /// read on.
20362 fn native_crop_override(clip: &str) -> Option<(String, usize, usize)> {
20363 let spec = std::env::var("EC_AV1_NATIVE_CROP").ok()?;
20364 let (w, h) = spec.split_once('x').expect("EC_AV1_NATIVE_CROP is <width>x<height>");
20365 let (cw, ch): (usize, usize) =
20366 (w.parse().expect("crop width"), h.parse().expect("crop height"));
20367 let (nw, nh) = crate::probe::dims(clip)?;
20368 assert!(cw <= nw && ch <= nh, "{cw}x{ch} does not fit in {nw}x{nh}");
20369 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
20370 Some((format!("crop={cw}:{ch}:{x}:{y}"), cw, ch))
20371 }
20372
20373 /// The rows of [`bd_rate_screen_native`] -- (label, path, seek) -- shared
20374 /// with `probe_screen_detect` so the detector sweep measures exactly the
20375 /// clips the keep table is read off. Selector env vars as documented on
20376 /// the gate; a missing clip prints a SKIP and drops its row.
20377 fn native_gate_clips() -> Vec<(String, String, String)> {
20378 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
20379 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
20380 let (film, film4k, screen) = (
20381 on("EC_AV1_NATIVE_FILM"),
20382 on("EC_AV1_NATIVE_FILM4K"),
20383 on("EC_AV1_NATIVE_SCREEN"),
20384 );
20385 // No selector at all means every clip; any selector means that subset.
20386 let all = !(film || film4k || screen);
20387 // (label, path, seek). The two `testsrc2` fixtures are COLOUR BARS,
20388 // not film -- they print as "bars" so no reader takes them for real
20389 // content -- and the two rows below them are the real AV1 films.
20390 let mut clips: Vec<(String, String, String)> = Vec::new();
20391 for (want, label, file) in [
20392 (all || film, "bars 1080p", "h264-1080p-23.976-8bit.mp4"),
20393 (all || film4k, "bars 2160p", "h264-2160p-23.976-8bit.mp4"),
20394 ] {
20395 if !want {
20396 continue;
20397 }
20398 let path = fixtures.join("video").join(file);
20399 match path.exists() {
20400 true => {
20401 clips.push((label.to_string(), path.to_str().unwrap().to_string(), "0".into()))
20402 }
20403 false => eprintln!("SKIP {label}: {file} missing"),
20404 }
20405 }
20406 let manifest = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"));
20407 // The real films, taken out of the real-library manifest by codec and
20408 // coded width so no title and no home path lives in this file. Each
20409 // seek is PINNED (class `seeded fixture not reproducible`) at a
20410 // moving, non-black window -- a black leader would make every arm
20411 // read +0.000 (class `flat sample window`). Both sources are 10-bit
20412 // (one HDR10/PQ); the loader's plain `-pix_fmt yuv420p` conversion is
20413 // what all three encoders see, so the comparison stays
20414 // encoder-vs-encoder.
20415 let pick = |width: &str| -> Option<String> {
20416 let m = manifest.as_ref().ok()?;
20417 m.lines()
20418 .skip(1)
20419 .map(|l| l.split('\t').collect::<Vec<_>>())
20420 .find(|f| {
20421 f.len() > 4
20422 && f[2] == "av1"
20423 && f[3] == width
20424 && std::path::Path::new(f[0]).exists()
20425 })
20426 .map(|f| f[0].to_string())
20427 };
20428 for (want, label, width, seek) in [
20429 (all || film, "film A (1080p source)", "1920", "00:35:00"),
20430 (all || film4k, "film B (2160p HDR source)", "3840", "00:40:00"),
20431 ] {
20432 if !want {
20433 continue;
20434 }
20435 match pick(width) {
20436 Some(path) => clips.push((label.to_string(), path, seek.to_string())),
20437 None => eprintln!("SKIP {label}: no {width}-wide AV1 source in the manifest"),
20438 }
20439 }
20440 if all || screen {
20441 match &manifest {
20442 Ok(manifest) => match manifest
20443 .lines()
20444 .skip(1)
20445 .filter_map(|l| l.split('\t').next())
20446 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
20447 {
20448 Some(p) => clips.push((
20449 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
20450 p.to_string(),
20451 "0".into(),
20452 )),
20453 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
20454 },
20455 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
20456 }
20457 }
20458 clips
20459 }
20460
20461 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
20462 /// downscales the OBS capture to 640x384, which destroys exactly the
20463 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
20464 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
20465 /// on that recipe is taken on content the tool cannot serve. This arm
20466 /// crops -- never scales -- a superblock-aligned window out of the middle
20467 /// of the capture at its own resolution (at most 1920x1024, so the wall
20468 /// stays in the minutes) and runs the same 12-frame, four-quantizer
20469 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
20470 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
20471 /// sample-exactness assertion `our_ladder` makes.
20472 ///
20473 /// It is its own `--ignored` test so the default gate's wall does not
20474 /// grow. Every variant is an environment knob, and each of those is a
20475 /// `OnceLock` read once per process, so a variant is a separate run:
20476 ///
20477 /// cargo test -p ec-av1 --release --lib -- --ignored \
20478 /// bd_rate_screen_native --nocapture # baseline
20479 /// EC_AV1_INTRABC=1 ... same command # intra block copy
20480 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
20481 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
20482 /// EC_AV1_PYRAMID=0 ... same command # no coding pyramid
20483 /// EC_AV1_GOP_LAYOUT=fixed ... same command # no tail absorbing
20484 /// EC_AV1_GATE_FACADE=1 ... same command # the facade arm
20485 ///
20486 /// The coding pyramid is the DEFAULT of the sequence path this arm codes
20487 /// through (lane-av1pyrdef); the run prints the requested and the
20488 /// effective pyramid per clip, and a screen clip's effective one is
20489 /// `None`. `EC_AV1_GATE_FACADE=1` runs the same ladder through the
20490 /// streaming facade instead, which prints the per-level frame and byte
20491 /// census and asserts ffmpeg's decode against our own decoder on all
20492 /// three planes in display order; both arms code the same bytes
20493 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`).
20494 ///
20495 /// WHICH ROWS ARE REAL CONTENT: the `bars 1080p` / `bars 2160p` rows are
20496 /// the repo fixtures `scripts/gen-fixtures.sh` builds with ffmpeg
20497 /// `testsrc2` -- COLOUR BARS, ~90% of whose 16x16 cells have no intra
20498 /// cost -- so every "film" column in the historical tables of this file
20499 /// is that generator, not film. The real content is `film A`, `film B`
20500 /// (native crops out of the two AV1 films the real-library manifest
20501 /// names, at a pinned seek; added 2026-09-07) and the screen capture. A
20502 /// decision only the bars rows support is not supported.
20503 ///
20504 /// Measured 2026-09-07, the five rows before and after the screen
20505 /// detector grew libaom's variance term ([`screen_var`]) -- before it,
20506 /// BOTH real films were classified as screen content on 48/48 frames, so
20507 /// their coefficients were priced against the DEFAULT CDFs and the
20508 /// palette search ran over film; after, both are non-screen (0/48) and
20509 /// the capture is unchanged at 48/48:
20510 ///
20511 /// | clip | vs libaom before -> after | vs rav1e before -> after | wall ours |
20512 /// |---|---|---|---|
20513 /// | bars 1080p | +15.6% -> +15.6% | -1.7% -> -1.7% | 37.9s |
20514 /// | bars 2160p | +46.5% -> +46.5% | +18.8% -> +18.8% | 33.9s |
20515 /// | film A | +69.5% -> +69.0% | +37.7% -> +37.5% | 72s -> 64.4s |
20516 /// | film B | +102.4% -> +100.0% | +63.4% -> +61.5% | 72s -> 67.9s |
20517 /// | screen capture | +51.0% -> +51.0% | -14.5% -> -14.5% | 27.5s |
20518 ///
20519 /// Both bars rows and the capture are byte-identical across that change
20520 /// (their classification never moved); the palette search over film was
20521 /// costing roughly a tenth of the film rows' wall.
20522 ///
20523 /// CONFIRM RUN 2026-09-07 (lane-av1pyrdef), with the pyramid now the
20524 /// sequence path's default -- the four non-screen rows take `4:-16:8`,
20525 /// the capture is gated flat and does not move a byte:
20526 ///
20527 /// | clip | effective | flat -> default | vs rav1e | wall ours:libaom:rav1e |
20528 /// |---|---|---|---|---|
20529 /// | bars 1080p | 4:-16:8 | +16.4% -> +21.5% | -1.1% -> +3.7% | 37.8s:8.4s:16.4s |
20530 /// | bars 2160p | 4:-16:8 | +48.2% -> +48.3% | +20.4% -> +20.4% | 32.2s:5.6s:16.2s |
20531 /// | film A | 4:-16:8 | +62.8% -> +54.1% | +32.5% -> +24.2% | 58.9s:9.5s:13.6s |
20532 /// | film B | 4:-16:8 | +86.3% -> +82.6% | +50.5% -> +47.4% | 63.2s:18.7s:16.4s |
20533 /// | screen capture | none (gated) | +50.1% -> +50.1% | -15.4% -> -15.4% | 31.1s:8.4s:11.3s |
20534 ///
20535 /// Every row lands on lane-av1pyrgate's facade-arm number to the digit,
20536 /// which is the point of the shared driver: the two entry points code one
20537 /// stream. The bars rows are fixtures (recorded, never a decision); the
20538 /// two real films are what the pyramid ships for.
20539 ///
20540 /// All five gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
20541 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
20542 /// setting any one of them keeps only the selected rows (the two 1080p
20543 /// rows, the two 2160p rows, the capture row respectively). A missing
20544 /// real film SKIPs its row; it never fails the gate.
20545 #[test]
20546 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
20547 fn bd_rate_screen_native() {
20548 let _knobs = crate::speed::knob_read();
20549 native_bd_arm("bd_rate_screen_native", 12, false);
20550 }
20551
20552 /// The LONG-GOP arm of the native BD gate: the same recipe as
20553 /// [`bd_rate_screen_native`] over the two real film rows only, but 48
20554 /// pictures with `gop = 48` (`encode_sequence` sets `gop =
20555 /// pictures.len()`, and `external_ladder` passes ffmpeg `-g 48`, which
20556 /// reaches libaom as `--kf-max-dist=48` and rav1e as
20557 /// `key_frame_interval=48`), so every encoder sees one key frame and 47
20558 /// inter pictures.
20559 ///
20560 /// WHY IT EXISTS: `bd_rate_screen_native` codes 12 frames with `gop =
20561 /// 12`, and `Av1Encoder::encode_frames` cuts a mini-GOP at every key
20562 /// frame (`encoder.rs`), so ANY [`crate::encoder::Pyramid::mini_gop`]
20563 /// above 12 codes the same stream there -- the shipped `16` was measured
20564 /// as "one hidden ARF per 12-picture GOP", never as a real 16-picture
20565 /// group (class `instrument at bound` / `gate blind to feature`). The
20566 /// user's exports are long GOPs, so the pyramid shape is decided here.
20567 ///
20568 /// cargo test -p ec-av1 --release --lib -- --ignored \
20569 /// bd_rate_film_long_gop --nocapture
20570 ///
20571 /// `EC_AV1_NATIVE_FILM=1` keeps only film A, `EC_AV1_NATIVE_FILM4K=1`
20572 /// only film B; `EC_AV1_PYRAMID=<mini_gop>:<arf>:<leaf>` picks the shape.
20573 /// Read every row off the log's own "pyramid requested/effective" print,
20574 /// never off the argument order of the runs (lane-pyr3 misattributed
20575 /// three rows that way).
20576 ///
20577 /// Table: `lanes/pyr4.sweep.txt`.
20578 #[test]
20579 #[ignore = "the long-GOP native BD arm: ~7 minutes per film row, needs ffmpeg"]
20580 fn bd_rate_film_long_gop() {
20581 let _knobs = crate::speed::knob_write();
20582 native_bd_arm("bd_rate_film_long_gop", 48, true);
20583 }
20584
20585 /// The shared driver of the two native BD arms above: `frames` pictures
20586 /// per row (the sequence's `gop` is the same number, so one key frame),
20587 /// four quantizers, `films_only` dropping every row but the two real
20588 /// films.
20589 fn native_bd_arm(label: &str, frames: usize, films_only: bool) {
20590 if !have_ffmpeg() {
20591 eprintln!("SKIP {label}: no ffmpeg");
20592 return;
20593 }
20594 let mut clips = native_gate_clips();
20595 if films_only {
20596 clips.retain(|(name, _, _)| name.starts_with("film "));
20597 }
20598 if clips.is_empty() {
20599 eprintln!("SKIP {label}: no clip");
20600 return;
20601 }
20602
20603 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
20604 .iter()
20605 .map(|q| {
20606 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
20607 .map(String::from)
20608 .to_vec()
20609 })
20610 .collect();
20611 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
20612 .iter()
20613 .map(|q| {
20614 vec![
20615 "-rav1e-params".to_string(),
20616 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
20617 ]
20618 })
20619 .collect();
20620 println!(
20621 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
20622 intrabc {}, palette maxcolors {}",
20623 armed_tiles(),
20624 crate::par::tile_threads(),
20625 intrabc_enabled(),
20626 palette_max_colors(),
20627 );
20628 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |");
20629 println!("|---|---|---|---|---|");
20630 for (name, path, seek) in &clips {
20631 let fctx = &crate::decode::FrameCtx::for_encoder();
20632 if probe_dims(path).is_none() {
20633 eprintln!("SKIP {name}: ffprobe gave no size");
20634 continue;
20635 }
20636 // A whole number of 128-wide superblocks, at most 1920x1024, out
20637 // of the middle of the frame; the offsets stay even for 4:2:0.
20638 // ONE definition, shared with `examples/enc_probe` so the probe
20639 // cannot measure a different window than this gate (lane-probe).
20640 let (vf, cw, ch) = match native_crop_override(path) {
20641 Some(over) => over,
20642 None => crate::probe::gate_crop(path),
20643 };
20644 let source = clip_frames_vf(path, seek, &vf, cw, ch, frames);
20645 SCREEN_FRAMES.iter().for_each(|c| {
20646 c.store(0, std::sync::atomic::Ordering::Relaxed);
20647 });
20648 let _ = crate::tile::take_palette_hits();
20649 let _ = crate::tile::take_palette_uv_hits();
20650 let _ = crate::tile::take_intrabc_hits();
20651 let _ = take_intrabc_search();
20652 let _ = crate::tile::take_filter_intra_hits();
20653 let _ = take_edge_census();
20654 // The sequence path itself codes the pyramid now
20655 // (lane-av1pyrdef), and prints what it requested and what the
20656 // content gate left effective.
20657 let (ours, ours_wall) = our_ladder(name, &source, cw, ch, fctx);
20658 // lane-sse: the blocks the true frame edge cuts through, and how
20659 // much of their RAW squared error sat in the padding the encoder
20660 // invented past it -- what the inside-only score stopped ranking
20661 // on. Empty on a superblock-aligned crop, which is every default
20662 // gate row (class `gate-blind-to-feature`).
20663 if edge_census() {
20664 for (side, n, inside, padding) in take_edge_census() {
20665 eprintln!(
20666 "{name}: edge {side}x{side} scores={n} inside_sse={inside} \
20667 padding_sse={padding} ({:.1}% of raw)",
20668 100.0 * padding as f64 / (inside + padding).max(1) as f64,
20669 );
20670 }
20671 }
20672 // gate-blind-to-feature: what the screen tools actually did at
20673 // native resolution, over this clip's four encodes.
20674 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
20675 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
20676 // Which tables the SEARCH priced against, per frame arming
20677 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
20678 // real starting ones. A film clip must show every inter arming on
20679 // the real side, a screen clip none of them.
20680 let (price_default, price_real) = crate::tile::take_pricing_hits();
20681 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
20682 // The 64x64 root's own fire shares (lane-b64/tx64/b64b): how many
20683 // superblocks stayed whole, and how many of those coded a
20684 // residual, split that residual's luma, or took a compound
20685 // reference (class `gate-blind-to-feature`).
20686 // lane-i64: the KEY frame's own 64x64 intra root -- how many of
20687 // the superblocks offered the trial were coded whole.
20688 let [i64_whole, i64_offered, i64_edge] = take_i64_root_hits();
20689 eprintln!(
20690 "{name}: key 64x64 intra roots {i64_whole} of {i64_offered} offered ({:.1}%), \
20691 {i64_edge} on a superblock the frame edge cuts",
20692 100.0 * i64_whole as f64 / i64_offered.max(1) as f64,
20693 );
20694 eprintln!(
20695 "{name}: 128x128 roots {} (search) / {} (writer), with a residual \
20696 {} (search) / {} (writer); rect/AB pieces with a residual \
20697 {} (search) / {} (writer)",
20698 take_b128_none_hits(),
20699 crate::tile::take_sb128_none_hits(),
20700 take_b128_residual_hits(),
20701 crate::tile::take_sb128_residual_hits(),
20702 take_b128_rectres_hits(),
20703 crate::tile::take_sb128_rectres_hits(),
20704 );
20705 eprintln!(
20706 "{name}: 64x64 roots {} (with a residual {}, split luma {}, compound {})",
20707 take_b64_root_hits(),
20708 take_b64_residual_hits(),
20709 take_b64_var_tx_hits(),
20710 take_b64_compound_hits(),
20711 );
20712 // lane-rdoq, under `EC_AV1_RDOQ_CENSUS=1` only (it costs a scan
20713 // of every priced block): what the deadzone quantiser handed the
20714 // RDOQ pass and what the pass changed, over every TRIAL block of
20715 // this row's four encodes -- not over the coded stream, so it is
20716 // the bits AT STAKE in the search, not in the bitstream.
20717 let rq = crate::tile::take_rdoq_stats();
20718 if rq[0] > 0 {
20719 eprintln!(
20720 "{name}: rdoq blocks={} coeffs={} (+-1 {:.1}%, trailing +-1 {:.1}%) \
20721 zeroed={} lowered={} trial bits {:.0} -> {:.0} ({:+.2}%)",
20722 rq[0],
20723 rq[1],
20724 100.0 * rq[2] as f64 / rq[1].max(1) as f64,
20725 100.0 * rq[3] as f64 / rq[1].max(1) as f64,
20726 rq[4],
20727 rq[5],
20728 rq[7] as f64 / 64.0,
20729 rq[6] as f64 / 64.0,
20730 100.0 * (rq[6] as f64 - rq[7] as f64) / rq[7].max(1) as f64,
20731 );
20732 }
20733 // lane-av1obmc2: the same motion_mode census the 640x384 gate
20734 // prints (class `gate-blind-to-feature`) -- how many blocks coded
20735 // the symbol at each footprint and how many took OBMC. Without it
20736 // the native table, which is the standing keep table, could not
20737 // say whether the tool fired at all.
20738 let mm = crate::tile::take_motion_mode_hits();
20739 eprintln!(
20740 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
20741 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
20742 eligible)",
20743 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
20744 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20745 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
20746 mm.iter().sum::<usize>(),
20747 );
20748 print_inter_tx_census(name);
20749 // lane-last2 (class `gate-blind-to-feature`): which reference the
20750 // 32x32-and-below inter blocks of this clip's four encodes chose.
20751 // The native table is the standing keep table, so a second past
20752 // reference that never won a block has to be visible HERE and not
20753 // only in a synthetic witness.
20754 let rh = crate::encode::take_ref_frame_hits();
20755 let rtot: usize = rh.iter().sum();
20756 eprintln!(
20757 "{name}: references LAST {} LAST2 {} GOLDEN {} ALTREF {} of {} inter blocks \
20758 (LAST2 {:.1}%)",
20759 rh[1], rh[2], rh[4], rh[7], rtot,
20760 100.0 * rh[2] as f64 / rtot.max(1) as f64,
20761 );
20762 let palette = crate::tile::take_palette_hits();
20763 let palette_uv = crate::tile::take_palette_uv_hits();
20764 let ibc = crate::tile::take_intrabc_hits();
20765 let search = take_intrabc_search();
20766 eprintln!(
20767 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
20768 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
20769 won {})",
20770 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
20771 palette[0],
20772 palette_uv[0],
20773 ibc[0],
20774 search[0],
20775 search[1],
20776 search[2],
20777 );
20778 // gate-blind-to-feature: how often the five recursive filter-intra
20779 // modes actually won a block over this clip's four encodes -- a
20780 // tool that never fires is not measured by the row above it.
20781 let fi = crate::tile::take_filter_intra_hits();
20782 eprintln!(
20783 "{name}: filter intra on={} blocks {} (modes DC={} V={} H={} D157={} PAETH={})",
20784 filter_intra_on(),
20785 fi[0],
20786 fi[1],
20787 fi[2],
20788 fi[3],
20789 fi[4],
20790 fi[5],
20791 );
20792 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
20793 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
20794 assert_monotone(&format!("{name}: ours"), &ours);
20795 assert_monotone(&format!("{name}: libaom"), &aom);
20796 assert_monotone(&format!("{name}: rav1e"), &rav1e);
20797 let points = ours
20798 .iter()
20799 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
20800 .collect::<Vec<_>>()
20801 .join(", ");
20802 println!(
20803 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
20804 bd_rate(&aom, &ours) * 100.0,
20805 bd_rate(&rav1e, &ours) * 100.0,
20806 );
20807 // lane-pareto2: the two references at THEIR fast presets, plus
20808 // SVT-AV1, measured in the SAME arm as the row above -- the only
20809 // way the wall column of a Pareto table means anything (class:
20810 // wall tables are comparable only inside one interleaved batch).
20811 // `EC_AV1_PARETO_REFS=1` only: it roughly doubles the arm.
20812 if std::env::var("EC_AV1_PARETO_REFS").ok().as_deref() == Some("1") {
20813 let rav1e_at = |sp: u32| -> Vec<Vec<String>> {
20814 [50, 100, 150, 200]
20815 .iter()
20816 .map(|q| {
20817 vec![
20818 "-rav1e-params".to_string(),
20819 format!(
20820 "speed={sp}:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"
20821 ),
20822 ]
20823 })
20824 .collect()
20825 };
20826 let aom_at = |cu: u32| -> Vec<Vec<String>> {
20827 [5, 20, 35, 45]
20828 .iter()
20829 .map(|q| {
20830 vec![
20831 "-cpu-used".to_string(),
20832 cu.to_string(),
20833 "-b:v".to_string(),
20834 "0".to_string(),
20835 "-crf".to_string(),
20836 q.to_string(),
20837 ]
20838 })
20839 .collect()
20840 };
20841 let svt_at = |pr: u32| -> Vec<Vec<String>> {
20842 [20, 35, 45, 55]
20843 .iter()
20844 .map(|q| {
20845 vec![
20846 "-preset".to_string(),
20847 pr.to_string(),
20848 "-crf".to_string(),
20849 q.to_string(),
20850 "-svtav1-params".to_string(),
20851 "lp=1".to_string(),
20852 ]
20853 })
20854 .collect()
20855 };
20856 let mut arms: Vec<(String, &str, Vec<Vec<String>>)> = vec![
20857 ("rav1e speed 8".into(), "librav1e", rav1e_at(8)),
20858 ("rav1e speed 10".into(), "librav1e", rav1e_at(10)),
20859 ("libaom cpu-used 8".into(), "libaom-av1", aom_at(8)),
20860 ];
20861 if have_encoder("libsvtav1") {
20862 arms.push(("svt-av1 preset 8".into(), "libsvtav1", svt_at(8)));
20863 arms.push(("svt-av1 preset 10".into(), "libsvtav1", svt_at(10)));
20864 } else {
20865 eprintln!("SKIP the SVT-AV1 rows: this ffmpeg has no libsvtav1");
20866 }
20867 for (label, encoder, points) in arms {
20868 let (lad, wall) = external_ladder(&source, cw, ch, encoder, &points);
20869 // A REFERENCE stream our decoder cannot read is a note in
20870 // this table, not a gate failure: these rows exist to
20871 // price the references, and `assert_ladder_decodes` keeps
20872 // its teeth for the two ladders the keep table is read off.
20873 let notes =
20874 std::mem::take(&mut *LADDER_FAILURES.lock().expect("ladder failures"));
20875 if !notes.is_empty() {
20876 eprintln!("{name} {label}: {} point(s) our decoder could not read (reference row, not a gate failure)", notes.len());
20877 }
20878 assert_monotone(&format!("{name}: {label}"), &lad);
20879 println!(
20880 "| {name} {cw}x{ch} / {label} | -- | {:+.1}% | {:+.1}% | {wall:.1}s (ours {ours_wall:.1}s, rav1e s6 {rav1e_wall:.1}s) |",
20881 bd_rate(&aom, &lad) * 100.0,
20882 bd_rate(&rav1e, &lad) * 100.0,
20883 );
20884 }
20885 }
20886 }
20887 assert_ladder_decodes();
20888 }
20889
20890 /// lane-av1tpl3 step 1: the SHAPE of the propagating map's denominator
20891 /// ([`super::tpl_intra_costs`], the per-16x16 MAD from the cell's own DC)
20892 /// on the two film clips at their native gate crop. The 2160p clip loses
20893 /// at every arm of the propagating map and the named suspect was that its
20894 /// heavily filtered flat cells give a tiny denominator, so the dependence
20895 /// ratio explodes exactly where coding is cheap; this prints the numbers
20896 /// that confirm or refute it.
20897 #[test]
20898 #[ignore = "needs ffmpeg and the film fixtures"]
20899 fn tpl_intra_denominator_histogram() {
20900 let _knobs = crate::speed::knob_read();
20901 if !have_ffmpeg() {
20902 eprintln!("SKIP tpl_intra_denominator_histogram: no ffmpeg");
20903 return;
20904 }
20905 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
20906 for (label, file) in [
20907 ("bars 1080p", "h264-1080p-23.976-8bit.mp4"),
20908 ("bars 2160p", "h264-2160p-23.976-8bit.mp4"),
20909 ] {
20910 let path = fixtures.join("video").join(file);
20911 if !path.exists() {
20912 eprintln!("SKIP {label}: {file} missing");
20913 continue;
20914 }
20915 let path = path.to_str().unwrap();
20916 let Some((nw, nh)) = probe_dims(path) else {
20917 eprintln!("SKIP {label}: ffprobe gave no size");
20918 continue;
20919 };
20920 let (cw, ch) = (nw.min(1920) / 128 * 128, nh.min(1024) / 128 * 128);
20921 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
20922 let source =
20923 clip_frames_vf(path, "0", &format!("crop={cw}:{ch}:{x}:{y}"), cw, ch, 8);
20924 let mut costs: Vec<f64> = Vec::new();
20925 for pic in &source {
20926 let y8: Vec<u8> = pic.y.iter().map(|&v| v as u8).collect();
20927 costs.extend(
20928 super::tpl_intra_costs(&y8, cw, ch).iter().map(|&c| f64::from(c)),
20929 );
20930 }
20931 let mean = costs.iter().sum::<f64>() / costs.len() as f64;
20932 let mut sorted = costs.clone();
20933 sorted.sort_by(f64::total_cmp);
20934 let q = |f: f64| sorted[((sorted.len() - 1) as f64 * f) as usize] / mean;
20935 let below = |f: f64| costs.iter().filter(|&&c| c < f * mean).count();
20936 eprintln!(
20937 "{label} {cw}x{ch}: {} cells over 8 frames, mean intra MAD {mean:.0}; \
20938 as a fraction of the mean p0={:.3} p1={:.3} p5={:.3} p25={:.3} p50={:.3} \
20939 p75={:.3} p99={:.3} max={:.3}; below 0.25x {} ({:.1}%), below 0.5x {} ({:.1}%), \
20940 below 1.0x {} ({:.1}%)",
20941 costs.len(),
20942 q(0.0),
20943 q(0.01),
20944 q(0.05),
20945 q(0.25),
20946 q(0.50),
20947 q(0.75),
20948 q(0.99),
20949 q(1.0),
20950 below(0.25),
20951 100.0 * below(0.25) as f64 / costs.len() as f64,
20952 below(0.5),
20953 100.0 * below(0.5) as f64 / costs.len() as f64,
20954 below(1.0),
20955 100.0 * below(1.0) as f64 / costs.len() as f64,
20956 );
20957 }
20958 }
20959
20960 /// The probe arms the gate's source (lane-probe, class `instrument
20961 /// disagrees with the gate`). `examples/enc_probe` built its own ffmpeg
20962 /// command line and had no `-ss`, so it read film B from frame 0 -- a
20963 /// black leader -- and coded 59 kB where the gate's own ladder point
20964 /// coded 89 kB of the same title; every census taken through it was
20965 /// probe-relative. Both now call [`crate::probe::source`]; this pins that
20966 /// the shared loader honours the seek (arming the probe's way and the
20967 /// gate's way gives byte-identical streams, and dropping the seek does
20968 /// not), on a synthetic clip whose content moves over time.
20969 #[test]
20970 fn the_probe_arms_the_gates_source() {
20971 let _knobs = crate::speed::knob_write();
20972 if !have_ffmpeg() {
20973 eprintln!("SKIP the_probe_arms_the_gates_source: no ffmpeg");
20974 return;
20975 }
20976 let dir = std::env::temp_dir().join(format!("ec-av1-probe-{}", std::process::id()));
20977 std::fs::create_dir_all(&dir).unwrap();
20978 let clip = dir.join("testsrc2.y4m");
20979 // 384x202: neither side is a multiple of 128, so the gate's centre
20980 // window is a real derivation and not the frame itself -- exactly the
20981 // shape film B has (3840x1608, never 3840x2160).
20982 let ok = Command::new("ffmpeg")
20983 .args(["-v", "error", "-y", "-f", "lavfi", "-i", "testsrc2=size=384x202:rate=10"])
20984 .args(["-frames:v", "20", "-pix_fmt", "yuv420p"])
20985 .arg(&clip)
20986 .status()
20987 .expect("ffmpeg failed to run")
20988 .success();
20989 assert!(ok, "ffmpeg could not write the synthetic clip");
20990 let path = clip.to_str().unwrap();
20991
20992 // The window: superblock-aligned, centred, even offsets.
20993 let (vf, w, h) = crate::probe::gate_crop(path);
20994 assert_eq!((vf.as_str(), w, h), ("crop=384:128:0:36", 384, 128));
20995
20996 let (seek, q) = ("00:00:01", 150u8);
20997 let gate = clip_frames_vf(path, seek, &vf, w, h, 6);
20998 let probe = crate::probe::source(path, seek, &vf, w, h, 6);
20999 assert!(
21000 gate.iter().zip(&probe).all(|(a, b)| a.y == b.y && a.u == b.u && a.v == b.v),
21001 "the probe's source differs from the gate's at the same window"
21002 );
21003 let bytes = |src: &[Picture]| {
21004 encode_sequence_with_ctx(src, q, 0.5, &crate::decode::FrameCtx::for_encoder())
21005 .unwrap()
21006 .stream
21007 };
21008 assert_eq!(bytes(&gate), bytes(&probe), "probe and gate code different bytes");
21009 // The two witnesses that both halves of the arming reach ffmpeg: the
21010 // seek, and the crop's own offset (the film-B defect in miniature --
21011 // the probe was reading `crop=..:568` of a 1608-high frame).
21012 let unseeked = crate::probe::source(path, "0", &vf, w, h, 6);
21013 assert_ne!(
21014 bytes(&gate),
21015 bytes(&unseeked),
21016 "seeked and unseeked arming coded the same bytes -- the seek is inert"
21017 );
21018 let offset = crate::probe::source(path, seek, "crop=384:128:0:0", w, h, 6);
21019 assert_ne!(
21020 bytes(&gate),
21021 bytes(&offset),
21022 "centred and top-aligned windows coded the same bytes -- the crop is inert"
21023 );
21024 std::fs::remove_dir_all(&dir).ok();
21025 }
21026
21027 /// lane-probe diagnostic: the gate's own loader + ladder call for ONE
21028 /// point inside the test binary, to compare against `examples/enc_probe`.
21029 #[test]
21030 #[ignore = "diagnostic: needs ffmpeg and a clip"]
21031 fn probe_parity_point() {
21032 let _knobs = crate::speed::knob_write();
21033 let g = |k: &str| std::env::var(k).unwrap();
21034 let (w, h) = g("EC_PARITY_DIMS").split_once(':').map(|(a, b)| (a.parse::<usize>().unwrap(), b.parse::<usize>().unwrap())).unwrap();
21035 let frames: usize = g("EC_PARITY_FRAMES").parse().unwrap();
21036 let q: u8 = g("EC_PARITY_Q").parse().unwrap();
21037 let source = clip_frames_vf(&g("EC_PARITY_CLIP"), &g("EC_PARITY_SS"), &g("EC_PARITY_VF"), w, h, frames);
21038 let fctx = &crate::decode::FrameCtx::for_encoder();
21039 let e = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
21040 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
21041 for &b in &e.stream {
21042 hash = (hash ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3);
21043 }
21044 eprintln!("PARITY q={q} bytes={} fnv1a={hash:016x} speed={} pyramid {:?} effective {:?}",
21045 e.stream.len(), crate::speed::speed(), crate::encoder::Pyramid::from_env(), last_sequence_pyramid());
21046 }
21047 /// lane-refs/lane-last2: IS A SECOND PAST REFERENCE WORTH RETAINING? The
21048 /// lever this census priced SHIPS since lane-last2 (merge `321b2dc1`):
21049 /// `EC_AV1_LAST2` (default OFF) retains a second past leaf picture in
21050 /// `LEAF_SLOTS`, names it `ref_frame_idx[1]`, and offers it to the 32x32
21051 /// search with its own `NEWMV` (`EC_AV1_LAST2_NEW`); the ARF-level lags
21052 /// the census's far row measures were already banked by `arf_altref`.
21053 /// This census stays the PRICING arm (class `gate-blind-to-feature`): its
21054 /// best-of-two SAD shares are read against the fire share the gate census
21055 /// prints (`references ... LAST2 n (n%)`) and the refutation in
21056 /// `lanes/last2.report.md` §4 -- a pure-SAD best-of-two over-counts the
21057 /// lever by more than an order of magnitude once NEAR/NEAREST/DRL off
21058 /// `LAST`, the backward `ALTREF`, and the rate term price in.
21059 ///
21060 /// The measurement is on the gate's own window and loader (`gate_crop`,
21061 /// 12 pictures) of the two real films: every 16x16 luma block of every
21062 /// picture gets one full-pel diamond search against the NEAR reference
21063 /// and the same search against the FAR one, at the two lags the pyramid
21064 /// actually offers -- (1, 2) for the leaf chain and (4, 8) for the ARF
21065 /// level, rav1e's own pair. Reported per lag: the share of blocks the far
21066 /// reference wins at all and by more than 10%, and -- the number the
21067 /// decision is taken on -- the total SAD of best-of-{near, far} against
21068 /// the total SAD of near alone, which is the prediction energy a second
21069 /// reference could remove before any rate is paid for naming it.
21070 ///
21071 /// cargo test -p ec-av1 --release --lib -- --ignored last2_census --nocapture
21072 #[test]
21073 #[ignore = "reads the real films"]
21074 fn last2_census() {
21075 if !have_ffmpeg() {
21076 eprintln!("SKIP last2_census: no ffmpeg");
21077 return;
21078 }
21079 const SIDE: usize = 16;
21080 // SAD of one 16x16 block against `r` at full-pel `(dy, dx)`, or
21081 // `None` when the displaced block leaves the picture.
21082 let sad = |cur: &Picture, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
21083 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
21084 if sy < 0 || sx < 0 {
21085 return None;
21086 }
21087 let (sy, sx) = (sy as usize, sx as usize);
21088 if sy + SIDE > r.height || sx + SIDE > r.width {
21089 return None;
21090 }
21091 let mut acc = 0u64;
21092 for row in 0..SIDE {
21093 let c = &cur.y[(by + row) * cur.width + bx..][..SIDE];
21094 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
21095 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
21096 }
21097 Some(acc)
21098 };
21099 // A log-step diamond from the zero motion vector: the cheapest search
21100 // that still finds real pans. Both references get exactly this one,
21101 // so the comparison is search-fair.
21102 let search = |cur: &Picture, r: &Picture, bx: usize, by: usize| -> u64 {
21103 let mut best = (sad(cur, r, bx, by, (0, 0)).unwrap_or(u64::MAX), (0isize, 0isize));
21104 let mut step = 16isize;
21105 while step >= 1 {
21106 let centre = best.1;
21107 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
21108 let mv = (centre.0 + dy * step, centre.1 + dx * step);
21109 if let Some(s) = sad(cur, r, bx, by, mv) {
21110 if s < best.0 {
21111 best = (s, mv);
21112 }
21113 }
21114 }
21115 step /= 2;
21116 }
21117 best.0
21118 };
21119 println!("| clip | level (near/far lag) | blocks | far wins | far wins >10% | SAD near | SAD best-of | energy removed |");
21120 println!("|---|---|---|---|---|---|---|---|");
21121 for (name, path, seek) in native_gate_clips() {
21122 if !name.starts_with("film ") {
21123 continue;
21124 }
21125 let (vf, cw, ch) = crate::probe::gate_crop(&path);
21126 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 12);
21127 for (near, far, level) in [(1usize, 2usize, "leaf"), (4usize, 8usize, "ARF")] {
21128 let (mut blocks, mut wins, mut big) = (0u64, 0u64, 0u64);
21129 let (mut near_sad, mut best_sad) = (0u64, 0u64);
21130 for i in far..pictures.len() {
21131 let cur = &pictures[i];
21132 let (rn, rf) = (&pictures[i - near], &pictures[i - far]);
21133 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
21134 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
21135 let (n, f) = (search(cur, rn, bx, by), search(cur, rf, bx, by));
21136 blocks += 1;
21137 wins += u64::from(f < n);
21138 big += u64::from(f as f64 * 1.1 < n as f64);
21139 near_sad += n;
21140 best_sad += n.min(f);
21141 }
21142 }
21143 }
21144 let pct = |a: u64| 100.0 * a as f64 / blocks.max(1) as f64;
21145 println!(
21146 "| {name} | {level} ({near}/{far}) | {blocks} | {:.1}% | {:.1}% | {near_sad} | {best_sad} | {:.2}% |",
21147 pct(wins),
21148 pct(big),
21149 100.0 * (near_sad - best_sad) as f64 / near_sad.max(1) as f64,
21150 );
21151 }
21152 }
21153 }
21154
21155 /// lane-arfpred: WHAT THE TOP ARF'S PREDICTION IS WORTH, and what a
21156 /// temporal filter of its SOURCE would take off it, priced before any
21157 /// encoder change (class `gate-blind-to-feature`).
21158 ///
21159 /// The stream census says our top ARF costs 6992 B a frame against
21160 /// rav1e's 3872 at a COARSER quantizer (118 vs 104) for the same picture
21161 /// quality, and that 61% of the gap is residual, not syntax. Two
21162 /// explanations are separable here without an encoder: our anchor
21163 /// predicts across 8 pictures where rav1e's predicts across 4 (lag), and
21164 /// the residual it codes at that lag is dominated by film grain, which no
21165 /// motion search can predict (source noise). So, per ARF position of the
21166 /// gate's own 48-picture window:
21167 ///
21168 /// * mean full-pel SAD per pixel at lag 8 (ours) and lag 4 (rav1e's),
21169 /// * the same at lag 8 with the CURRENT picture temporally filtered --
21170 /// a libaom-shaped motion-compensated average of the +-2 display
21171 /// neighbours, weights `exp(-mse / strength)` -- which is the residual
21172 /// energy an ARF temporal filter would remove, and
21173 /// * PSNR of that filtered picture against the unfiltered one, the
21174 /// CEILING the filtered ARF's own PSNR is then measured under (the
21175 /// BD gate scores against the unfiltered source).
21176 ///
21177 /// EC_ARF_TF_S=<strength> cargo test -p ec-av1 --release --lib -- \
21178 /// --ignored arf_pred_census --nocapture
21179 #[test]
21180 #[ignore = "reads the real films"]
21181 fn arf_pred_census() {
21182 if !have_ffmpeg() {
21183 eprintln!("SKIP arf_pred_census: no ffmpeg");
21184 return;
21185 }
21186 const SIDE: usize = 16;
21187 let strength: f64 = std::env::var("EC_ARF_TF_S")
21188 .ok()
21189 .and_then(|v| v.parse().ok())
21190 .unwrap_or(30.0);
21191 let past = std::env::var("EC_ARF_TF_PAST").as_deref() == Ok("1");
21192 // SAD and the matching block of `r` at full-pel `(dy, dx)`, or `None`
21193 // when the displaced block leaves the picture.
21194 let at = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize, mv: (isize, isize)| {
21195 let (sy, sx) = (by as isize + mv.0, bx as isize + mv.1);
21196 if sy < 0 || sx < 0 {
21197 return None;
21198 }
21199 let (sy, sx) = (sy as usize, sx as usize);
21200 if sy + SIDE > r.height || sx + SIDE > r.width {
21201 return None;
21202 }
21203 let mut acc = 0u64;
21204 for row in 0..SIDE {
21205 let c = &cur[row * cw..][..SIDE];
21206 let p = &r.y[(sy + row) * r.width + sx..][..SIDE];
21207 acc += c.iter().zip(p).map(|(&a, &b)| u64::from(a.abs_diff(b))).sum::<u64>();
21208 }
21209 Some((acc, (sy, sx)))
21210 };
21211 // The same log-step diamond `last2_census` uses, so the two censuses'
21212 // SADs are comparable.
21213 let search = |cur: &[u16], cw: usize, r: &Picture, bx: usize, by: usize| {
21214 let mut best = match at(cur, cw, r, bx, by, (0, 0)) {
21215 Some(v) => v,
21216 None => return (u64::MAX, (by, bx)),
21217 };
21218 let mut centre = (0isize, 0isize);
21219 let mut step = 16isize;
21220 while step >= 1 {
21221 let from = centre;
21222 for (dy, dx) in [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)] {
21223 let mv = (from.0 + dy * step, from.1 + dx * step);
21224 if let Some(s) = at(cur, cw, r, bx, by, mv) {
21225 if s.0 < best.0 {
21226 best = s;
21227 centre = mv;
21228 }
21229 }
21230 }
21231 step /= 2;
21232 }
21233 best
21234 };
21235 println!(
21236 "| clip | ARFs | strength {strength} past {past} | lag8 SAD/px | lag4 SAD/px | tf lag8 SAD/px | tf removes | tf PSNR ceiling |"
21237 );
21238 println!("|---|---|---|---|---|---|---|");
21239 for (name, path, seek) in native_gate_clips() {
21240 if !name.starts_with("film ") {
21241 continue;
21242 }
21243 let (vf, cw, ch) = crate::probe::gate_crop(&path);
21244 let pictures = clip_frames_vf(&path, &seek, &vf, cw, ch, 48);
21245 let (mut n8, mut n4, mut ntf, mut px, mut arfs) = (0u64, 0u64, 0u64, 0u64, 0usize);
21246 let (mut tf_sse, mut tf_px) = (0f64, 0u64);
21247 for i in (8..pictures.len()).step_by(8) {
21248 arfs += 1;
21249 let cur = &pictures[i];
21250 for by in (0..ch.saturating_sub(SIDE - 1)).step_by(SIDE) {
21251 for bx in (0..cw.saturating_sub(SIDE - 1)).step_by(SIDE) {
21252 let block: Vec<u16> = (0..SIDE)
21253 .flat_map(|row| cur.y[(by + row) * cur.width + bx..][..SIDE].to_vec())
21254 .collect();
21255 n8 += search(&block, SIDE, &pictures[i - 8], bx, by).0;
21256 n4 += search(&block, SIDE, &pictures[i - 4], bx, by).0;
21257 // The temporal filter: each +-2 display neighbour is
21258 // motion-compensated onto this block and averaged in
21259 // with libaom's shape, a weight that falls with the
21260 // match's own mean squared error.
21261 let mut acc: Vec<f64> = block.iter().map(|&v| f64::from(v)).collect();
21262 let mut wsum = 1.0f64;
21263 // `EC_ARF_TF_PAST=1` restricts the filter to the
21264 // DISPLAY-PAST neighbours -- the only ones the
21265 // encoder's own group buffer holds when it codes its
21266 // top ARF (the group's future is not buffered yet).
21267 let offs: &[isize] = match past {
21268 true => &[-2, -1],
21269 false => &[-2, -1, 1, 2],
21270 };
21271 for &d in offs {
21272 let j = i as isize + d;
21273 let Some(nb) = usize::try_from(j).ok().and_then(|j| pictures.get(j))
21274 else {
21275 continue;
21276 };
21277 let (_, (sy, sx)) = search(&block, SIDE, nb, bx, by);
21278 let mut sse = 0f64;
21279 for row in 0..SIDE {
21280 for col in 0..SIDE {
21281 let d = f64::from(block[row * SIDE + col])
21282 - f64::from(nb.y[(sy + row) * nb.width + sx + col]);
21283 sse += d * d;
21284 }
21285 }
21286 let w = (-sse / ((SIDE * SIDE) as f64) / strength).exp();
21287 for row in 0..SIDE {
21288 for col in 0..SIDE {
21289 acc[row * SIDE + col] +=
21290 w * f64::from(nb.y[(sy + row) * nb.width + sx + col]);
21291 }
21292 }
21293 wsum += w;
21294 }
21295 let filtered: Vec<u16> = acc
21296 .iter()
21297 .map(|v| (v / wsum).round().clamp(0.0, 1023.0) as u16)
21298 .collect();
21299 for (a, b) in filtered.iter().zip(&block) {
21300 let d = f64::from(*a) - f64::from(*b);
21301 tf_sse += d * d;
21302 }
21303 tf_px += (SIDE * SIDE) as u64;
21304 ntf += search(&filtered, SIDE, &pictures[i - 8], bx, by).0;
21305 px += (SIDE * SIDE) as u64;
21306 }
21307 }
21308 }
21309 let per = |v: u64| v as f64 / px.max(1) as f64;
21310 let mse = tf_sse / tf_px.max(1) as f64;
21311 println!(
21312 "| {name} | {arfs} | s{strength} p{past} | {:.3} | {:.3} | {:.3} | {:.1}% | {:.2} dB |",
21313 per(n8),
21314 per(n4),
21315 per(ntf),
21316 100.0 * (n8 - ntf) as f64 / n8.max(1) as f64,
21317 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(),
21318 );
21319 }
21320 }
21321
21322 /// lane-refs: THE FRAME FILTER REACHES THE PIXELS. `mc::predict` used to
21323 /// hardwire the REGULAR kernel, so the encoder could not have coded a
21324 /// SMOOTH or SHARP frame even if the header had said so -- the search,
21325 /// the trials, the recon and the frame header now all read
21326 /// `FrameCtx::interp_filter`. Each of the three kernels codes its own
21327 /// distinct stream (a filter that never reached the prediction would code
21328 /// the same bytes as REGULAR, class `symbol consumption gap`), and ffmpeg
21329 /// reconstructs every frame of each of them exactly, which is what proves
21330 /// the header and the prediction agree.
21331 #[test]
21332 fn each_frame_interpolation_filter_codes_its_own_stream_ffmpeg_decodes_exactly() {
21333 let _knobs = crate::speed::knob_write();
21334 if !have_ffmpeg() {
21335 eprintln!("SKIP each_frame_interpolation_filter_codes_its_own_stream: no ffmpeg");
21336 return;
21337 }
21338 let (width, height) = (256usize, 128usize);
21339 // A HALF-PEL pan: an integer-pel one reads no filter tap at all, so
21340 // all three kernels would code the same bytes and the test would pass
21341 // on a wiring that does nothing (class `fixture proves the symbol, not
21342 // the signal`). `panned_test_card` shifts by whole pixels, so the
21343 // search finds the sub-pel positions off the reconstruction instead:
21344 // three frames of a slow diagonal pan.
21345 let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect();
21346 let mut streams = Vec::new();
21347 for filter in [
21348 ec_av1_syntax::InterpolationFilter::Eighttap,
21349 ec_av1_syntax::InterpolationFilter::EighttapSmooth,
21350 ec_av1_syntax::InterpolationFilter::EighttapSharp,
21351 ] {
21352 set_frame_interp(Some(filter));
21353 let fctx = &crate::decode::FrameCtx::for_encoder();
21354 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
21355 .unwrap_or_else(|e| panic!("{filter:?}: {e}"));
21356 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
21357 assert_eq!(decoded.len(), 3, "{filter:?}: decoded frame count");
21358 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
21359 assert_eq!(decoded.y, frame.reconstruction.y, "{filter:?} frame {i}: luma");
21360 assert_eq!(decoded.u, frame.reconstruction.u, "{filter:?} frame {i}: U");
21361 assert_eq!(decoded.v, frame.reconstruction.v, "{filter:?} frame {i}: V");
21362 }
21363 streams.push((filter, encoded.stream));
21364 }
21365 set_frame_interp(None);
21366 for (i, (fa, a)) in streams.iter().enumerate() {
21367 for (fb, b) in &streams[i + 1..] {
21368 assert_ne!(a, b, "{fa:?} and {fb:?} coded the same bytes");
21369 }
21370 }
21371 }
21372
21373
21374 /// lane-hpmv: THE EIGHTH-PEL VECTOR REACHES THE STREAM. With
21375 /// `allow_high_precision_mv` off the writer refuses an odd eighth-pel
21376 /// residual outright (`round_to_valid_mv` rounds it away first), so the
21377 /// finest vector the encoder could commit to was a quarter pel. With the
21378 /// header bit on, the writer codes an `mv_hp`/`mv_class0_hp` symbol per
21379 /// non-zero component and the search's fourth stage refines to the
21380 /// eighth: this asserts ZERO hp symbols in the off arm, non-zero in the
21381 /// on arm, and -- the part that makes it a signal rather than a symbol
21382 /// count (class `fixture proves the symbol, not the signal`) -- that some
21383 /// of them come out ZERO, i.e. name a vector the off arm cannot code at
21384 /// all. Both streams are decoded by ffmpeg AND by this crate's own
21385 /// decoder and asserted sample-exact against the encoder's own
21386 /// reconstruction, which is what proves the header bit and the symbols
21387 /// agree.
21388 #[test]
21389 fn a_high_precision_frame_codes_eighth_pel_motion_vectors_both_decoders_read() {
21390 let _knobs = crate::speed::knob_write();
21391 if !have_ffmpeg() {
21392 eprintln!("SKIP a_high_precision_frame_codes_eighth_pel_motion_vectors: no ffmpeg");
21393 return;
21394 }
21395 let (width, height) = (256usize, 128usize);
21396 let pictures: Vec<Picture> = (0..3).map(|i| panned_test_card(width, height, i * 3)).collect();
21397 let mut arms = Vec::new();
21398 for hp in [false, true] {
21399 set_high_precision_mv(Some(hp));
21400 let _ = crate::tile::take_hp_symbols();
21401 let fctx = &crate::decode::FrameCtx::for_encoder();
21402 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
21403 .unwrap_or_else(|e| panic!("hp={hp}: {e}"));
21404 let (symbols, eighth) = crate::tile::take_hp_symbols();
21405 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, pictures.len());
21406 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
21407 assert_eq!(decoded.len(), pictures.len(), "hp={hp}: ffmpeg frame count");
21408 assert_eq!(ours.len(), pictures.len(), "hp={hp}: our decoder frame count");
21409 for (i, e) in encoded.frames.iter().enumerate() {
21410 for (who, got) in [("ffmpeg", &decoded[i]), ("our decoder", &ours[i])] {
21411 if let Some((plane, s, got, want)) = first_plane_mismatch(got, &e.reconstruction)
21412 {
21413 panic!(
21414 "hp={hp} frame {i} plane {plane} sample {s}: {who} decoded {got}, \
21415 the encoder reconstructed {want}"
21416 );
21417 }
21418 }
21419 }
21420 arms.push((symbols, eighth, encoded.stream));
21421 }
21422 set_high_precision_mv(None);
21423 let (off, on) = (&arms[0], &arms[1]);
21424 assert_eq!(off.0, 0, "a frame without the header bit codes no hp symbol");
21425 assert!(on.0 > 0, "a high-precision frame codes hp symbols (got {})", on.0);
21426 assert!(
21427 on.1 > 0,
21428 "a high-precision frame codes eighth-pel vectors ({} hp symbols, none of them zero)",
21429 on.0
21430 );
21431 assert_ne!(off.2, on.2, "the two arms coded the same bytes");
21432 println!(
21433 "hp witness: off {} hp symbols / {} B, on {} hp symbols ({} eighth-pel) / {} B",
21434 off.0,
21435 off.2.len(),
21436 on.0,
21437 on.1,
21438 on.2.len()
21439 );
21440 }
21441}