forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mod.rs2572 lines, 115.0 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};
43#[cfg(test)]
44use crate::transform::forward_and_quantize;
45use crate::transform::{
46 TxType, dequant_and_inverse_typed_wh, forward_and_quantize_typed,
47 forward_and_quantize_typed_scaled,
48};
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/// [`reach_sb_px`] in 4x4 mode-info units -- libaom's `sb_mi_size` in
78/// `has_top_right`/`has_bottom_left` (`mi_size_high[sb_size]`), which is what
79/// [`Reach::of_tu_chroma`] masks the block's mi position with.
80pub(crate) fn reach_sb_mi(fctx: &crate::decode::FrameCtx) -> usize {
81 reach_sb_px(fctx) / 4
82}
83
84/// `scale_chroma_bsize(bsize, ss_x, ss_y)` (libaom `reconintra.c:1649`,
85/// called from `av1_predict_intra_block` at `:1823`) in 4x4 mode-info units:
86/// the block shape a CHROMA plane's reach is answered against. Only the
87/// BLOCK_4X4 / BLOCK_4X8 / BLOCK_8X4 / BLOCK_4X16 / BLOCK_16X4 family is
88/// remapped -- every other block size passes through, so at `ss (0,0)` and
89/// for any block of 8 or more this is the block's own `(bw/4, bh/4)`.
90pub(crate) fn chroma_mi_shape(bw: usize, bh: usize, ss_x: usize, ss_y: usize) -> (usize, usize) {
91 match (bw, bh, ss_x, ss_y) {
92 // BLOCK_4X4 -> BLOCK_8X8 / BLOCK_8X4 / BLOCK_4X8 / itself.
93 (4, 4, 1, 1) => (2, 2),
94 (4, 4, 1, 0) => (2, 1),
95 (4, 4, 0, 1) => (1, 2),
96 // BLOCK_4X8 -> BLOCK_8X8 / BLOCK_8X8 / BLOCK_4X8 / itself.
97 (4, 8, 1, _) => (2, 2),
98 (4, 8, 0, 1) => (1, 2),
99 // BLOCK_8X4 -> BLOCK_8X8 / BLOCK_8X4 / BLOCK_8X8 / itself.
100 (8, 4, 1, 0) => (2, 1),
101 (8, 4, 1, 1) | (8, 4, 0, 1) => (2, 2),
102 // BLOCK_4X16 -> BLOCK_8X16 / BLOCK_8X16 / BLOCK_4X16 / itself.
103 (4, 16, 1, _) => (2, 4),
104 (4, 16, 0, 1) => (1, 4),
105 // BLOCK_16X4 -> BLOCK_16X8 / BLOCK_16X4 / BLOCK_16X8 / itself.
106 (16, 4, 1, 0) => (4, 1),
107 (16, 4, 1, 1) | (16, 4, 0, 1) => (4, 2),
108 _ => (bw / 4, bh / 4),
109 }
110}
111
112/// How heavily the mode search weighs rate against squared error, in units of
113/// the quantizer's reconstruction step squared per bit.
114///
115/// Swept three times over his clips and three synthetic pictures
116/// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in
117/// the three lane reports). The first sweep, before the mode symbol was
118/// costed, put the best point at 0.05; costing it moved the point to 0.1. The
119/// third sweep, after the levels were costed through the writer's own CDFs
120/// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98%
121/// on film and -0.20% against -0.14% on screen capture.
122///
123/// The fourth sweep (lane-av1lambda) ran the BD gates themselves rather than
124/// those ladders, and 0.1 was far off the point: the rate term was carrying
125/// roughly twice the weight it is worth. 640x384 gate, BD-rate vs libaom /
126/// vs rav1e for 1080p film, 2160p film, screen capture:
127///
128/// | lambda | 1080p | 2160p | screen |
129/// |--------|-------|-------|--------|
130/// | 0.0125 | +78.0 / +31.3 | +90.8 / +46.5 | +57.2 / -0.3 |
131/// | 0.025 | +71.5 / +28.4 | +87.0 / +46.5 | +50.4 / -3.8 |
132/// | 0.0375 | +71.2 / +28.5 | +84.3 / +45.4 | +48.7 / -4.4 |
133/// | 0.05 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
134/// | 0.075 | +74.8 / +32.7 | +91.3 / +52.8 | +51.4 / -1.3 |
135/// | 0.1 | +79.2 / +36.9 | +97.7 / +58.8 | +53.1 / -0.4 |
136/// | 0.125 | +84.0 / +41.1 | +100.7 / +61.5 | +56.8 / +2.3 |
137/// | 0.15 | +86.0 / +42.9 | +104.4 / +65.2 | +59.5 / +4.2 |
138/// | 0.2 | +89.6 / +45.5 | +109.9 / +69.8 | +62.3 / +7.3 |
139///
140/// and on the native 1920x1024 crops, which is the table that decides:
141///
142/// | lambda | film 1080p | film 2160p | screen |
143/// |--------|------------|------------|--------|
144/// | 0.025 | +17.1 / -0.5 | +49.0 / +21.1 | +51.5 / -15.1 |
145/// | 0.0375 | +16.3 / -1.0 | +47.5 / +19.7 | +50.7 / -15.1 |
146/// | 0.05 | +17.0 / -0.3 | +47.0 / +19.2 | +51.6 / -14.2 |
147/// | 0.1 | +18.1 / +0.9 | +47.1 / +19.0 | +58.3 / -9.8 |
148///
149/// 0.0375 was the best point on two clips of three there and cost the "2160p
150/// film" row +0.4/+0.7, outside the +-0.3 band every other lever here is kept
151/// inside, so 0.05 shipped. BOTH of those tables' "film" rows are the
152/// `testsrc2` COLOUR BARS fixtures (see [`bd_rate_screen_native`]), ~90% of
153/// whose cells have no intra cost -- no real film supported the point.
154///
155/// FIFTH SWEEP (lane-av1resweep, 2026-09-07), on the native gate's two REAL
156/// film crops (film A 1080p, film B 2160p HDR) plus the capture, BD-rate vs
157/// libaom / vs rav1e, everything else at the shipped defaults:
158///
159/// | lambda | bars 1080p | bars 2160p | film A | film B | screen |
160/// |--------|------------|------------|--------|--------|--------|
161/// | 0.02 | +17.5 / -0.2 | +49.7 / +21.7 | +65.8 / +35.0 | +91.2 / +55.4 | +53.4 / -14.1 |
162/// | 0.0275 | +16.6 / -0.9 | +48.3 / +20.5 | +65.5 / +34.7 | +91.6 / +55.1 | +51.3 / -15.0 |
163/// | 0.035 | +16.1 / -1.3 | +47.5 / +19.7 | +66.4 / +35.2 | +94.2 / +56.9 | +50.8 / -15.1 |
164/// | 0.05 | +15.6 / -1.7 | +46.5 / +18.8 | +69.0 / +37.5 | +100.0 / +61.5 | +51.0 / -14.5 |
165/// | 0.07 | +16.6 / -0.5 | +46.8 / +18.8 | +72.3 / +40.4 | +108.5 / +68.8 | +54.4 / -12.4 |
166/// | 0.1 | +16.5 / -0.7 | +46.6 / +18.7 | +76.9 / +44.4 | +118.2 / +77.1 | +57.3 / -10.1 |
167///
168/// Real film wants roughly HALF the rate weight the bars asked for: the bowl
169/// on both film rows bottoms between 0.02 and 0.0275 and is 5-11 points deep
170/// against the shipped 0.05, while the bars rows walk the other way (they are
171/// recorded, not decided on). 0.02 breaks the capture (+2.4 vs libaom), so
172/// 0.0275 ships -- both films 3.5/8.4 points down vs libaom, the capture
173/// +0.3/-0.5 (at the +-0.3 band, and better than baseline once the var-tx
174/// defaults below are on: +50.1 / -15.4). It spends ~5% more encode wall.
175const LAMBDA_SCALE: f64 = 0.0275;
176
177/// The rate weight a HIDDEN frame (a pyramid ARF, coded but not shown) codes
178/// under, as a multiple of [`LAMBDA_SCALE`] (lane-arfcen).
179///
180/// The ARF-vs-ARF census says our top ARF codes residual over HALF its area
181/// (rav1e's, at the same display position, over 26-30%) and comes out 1.4-2.5x
182/// its bytes at the same PSNR, while every leaf that predicts from it is
183/// still 0.4 dB behind rav1e's -- i.e. the ARF's extra fidelity is bought at
184/// a rate weight fitted on shown frames and does not propagate. This is the
185/// one knob that prices a hidden frame's rate differently from its q, which
186/// the pyramid's q offsets cannot do (they move lambda and step together).
187const HIDDEN_LAMBDA_FACTOR: f64 = 1.0;
188
189/// [`HIDDEN_LAMBDA_FACTOR`], swept by `EC_AV1_LAMBDA_HIDDEN` in any build.
190fn hidden_lambda_factor() -> f64 {
191 match std::env::var("EC_AV1_LAMBDA_HIDDEN")
192 .ok()
193 .and_then(|v| v.parse().ok())
194 {
195 Some(f) => f,
196 None => HIDDEN_LAMBDA_FACTOR,
197 }
198}
199
200/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
201/// picks it is the thing running. A release build has no such knob.
202fn lambda_scale() -> f64 {
203 let swept = std::env::var("EC_AV1_LAMBDA")
204 .ok()
205 .and_then(|v| v.parse::<f64>().ok());
206 match swept {
207 Some(scale) if cfg!(test) => scale,
208 _ => LAMBDA_SCALE,
209 }
210}
211
212/// How a key frame's lambda differs from an inter frame's: libaom weighs the
213/// two apart (`rd_frame_type_factor`, key 128 against an inter frame's 144 out
214/// of 128), because every later frame predicts from the key frame, so an error
215/// left in it is paid for over the whole group. This encoder has no temporal
216/// propagation model at all, and this factor is the cheapest stand-in for one.
217/// Swept by `EC_AV1_LAMBDA_KEY` in a test build, like [`lambda_scale`].
218///
219/// MEASURED and NOT KEPT. 640x384 gate at [`LAMBDA_SCALE`] 0.05, BD vs
220/// libaom / vs rav1e:
221///
222/// | k_key | 1080p | 2160p | screen |
223/// |---|---|---|---|
224/// | 1.0 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
225/// | 0.85 | +71.5 / +29.4 | +87.0 / +48.3 | +49.7 / -3.9 |
226/// | 0.7 | +71.3 / +28.9 | +87.2 / +48.6 | +49.4 / -4.1 |
227/// | 0.5 | +71.4 / +28.9 | +88.7 / +49.6 | +50.1 / -3.4 |
228///
229/// The two films want the key frame coded finer and the screen capture wants
230/// the opposite, by about the same amount, and at native the whole lever is
231/// inside the +-0.3 band that decides nothing: k_key 0.7 reads +16.9 / -0.3,
232/// +47.2 / +19.2, +51.4 / -14.7 against 1.0's +17.0 / -0.3, +47.0 / +19.2,
233/// +51.6 / -14.2. A gate whose GOP is one key frame in twelve cannot see a
234/// per-frame-type weight; the real lever here is temporal propagation
235/// (libaom's `tpl`), which weighs each BLOCK by how much of it later frames
236/// predict from, not each frame.
237const KEY_LAMBDA_FACTOR: f64 = 1.0;
238
239/// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build.
240fn key_lambda_factor() -> f64 {
241 match std::env::var("EC_AV1_LAMBDA_KEY")
242 .ok()
243 .and_then(|v| v.parse::<f64>().ok())
244 {
245 Some(k) if cfg!(test) => k,
246 _ => KEY_LAMBDA_FACTOR,
247 }
248}
249
250// Every frame's predicted coefficient bits since the last
251// `take_predicted_bits`, in coding order -- the encoder half of
252// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement.
253#[cfg(test)]
254thread_local! {
255 static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) };
256}
257
258/// Records one frame's predicted coefficient bits.
259#[cfg(test)]
260fn record_predicted_bits(bits: f64) {
261 PREDICTED_BITS.with(|p| p.borrow_mut().push(bits));
262}
263
264/// Takes (and clears) what the frames encoded on this thread were predicted to
265/// spend on coefficients.
266#[cfg(test)]
267pub(crate) fn take_predicted_bits() -> Vec<f64> {
268 PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut()))
269}
270
271/// Whether a 16x16 inter leaf may split into four 8x8 ones of its own.
272pub(crate) const SPLIT_INTER_8: bool = true;
273
274/// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
275/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
276/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0`
277/// turns it off for an A/B on one build.
278/// Whether an INTER frame also carries `TxMode::Select`: an inter block's
279/// residual as one transform over the whole block or as the four transforms
280/// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every
281/// intra block inside the inter frame. ON since lane-av1tx2, which found why
282/// the streams desynced -- the writer counted the [`crate::decode::
283/// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the
284/// reader drops the term -- and measured the split search: BD-rate vs libaom
285/// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the
286/// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an
287/// A/B on one build.
288fn tx_select_inter() -> bool {
289 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
290 crate::envflags::var("EC_AV1_TX_SELECT_INTER")
291 .ok()
292 .map(|v| !matches!(v.as_str(), "0" | "off"))
293 });
294 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_INTER))
295}
296
297/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`, control
298/// vs arm): the capture row goes +27.8/-26.0 -> +20.8/-30.1 -- seven points
299/// against libaom -- while BOTH film rows LOSE (film A +21.7/-4.4 ->
300/// +22.1/-4.0, film B +26.9/-0.6 -> +28.1/+0.7) and 2160p bars lose 0.8/1.1.
301/// The keep rule wants both films down, so this takes the same content gate
302/// palette, intrabc and the angle-delta refinement already stand behind: a
303/// non-screen frame is byte-identical to the encoder before the lane.
304///
305/// The transform types an intra luma transform unit of `set` may be coded
306/// with -- exactly the alphabet the writer's `tx_type` symbol names for that
307/// set, so a searched type is always one the tile can express (lane-txset).
308/// `DCT_DCT` first: it is the incumbent every other candidate has to beat.
309///
310/// Under this encoder's `reduced_tx_set` header bit every intra set at 16x16
311/// and below is `TX_SET_INTRA_2` (spec `get_tx_set`), the five types
312/// [`TxType::from_symbol`] names; 32x32 and 64x64 luma code no symbol at all,
313/// and inter luma reads the two-type `TX_SET_INTER_3`, left at `DCT_DCT`
314/// here.
315pub(crate) fn tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
316 const DCT: [TxType; 1] = [TxType::DctDct];
317 const INTRA1: [TxType; 7] = [
318 TxType::DctDct,
319 TxType::AdstAdst,
320 TxType::AdstDct,
321 TxType::DctAdst,
322 TxType::Idtx,
323 TxType::VDct,
324 TxType::HDct,
325 ];
326 const INTRA2: [TxType; 5] = [
327 TxType::DctDct,
328 TxType::AdstAdst,
329 TxType::AdstDct,
330 TxType::DctAdst,
331 TxType::Idtx,
332 ];
333 match set {
334 TxbSet::Luma16 | TxbSet::Luma8 | TxbSet::Luma4 if intra_tx_search_on(screen) => &INTRA2,
335 // lane-txi: a `reduced_tx_set == 0` frame's intra 8x8/4x4 reads the
336 // SEVEN-type `TX_SET_INTRA_1` (`decode::txbset_for`'s `Luma{8,4}Set1`;
337 // 16x16 stays `TX_SET_INTRA_2`, there is no `Luma16Set1`). The two
338 // extra members are the 1-D DCTs, and the order is the reader's own
339 // map (`decode::tx_type_from_symbol`, 8-wide CDF).
340 TxbSet::Luma8Set1 | TxbSet::Luma4Set1 if intra_tx_search_on(screen) => &INTRA1,
341 _ => &DCT,
342 }
343}
344
345/// The transform types an INTER luma transform unit of `set` may be coded
346/// with (lane-txset2). Under this encoder's `reduced_tx_set` header bit every
347/// inter luma set at 16x16 and below is the two-type `TX_SET_INTER_3`
348/// (`IDTX`, `DCT_DCT`) and 32x32 is `EXT_TX_SET_DCT_IDTX` -- the same two
349/// types, a symbol the writer already codes and never varied. 64x64 codes no
350/// `tx_type` symbol at all, so it is not offered one.
351/// SCREEN CONTENT ONLY, measured (12-frame `bd_rate_screen_native`): the
352/// capture row goes +20.8/-30.1 -> +20.1/-30.4 while the two synthetic bars
353/// rows lose TWENTY points (-1.0/-16.8 -> +23.1/+3.3 and +9.4/-12.7 ->
354/// +31.2/+3.7) and film B 0.3 -- the `local-rd-on-references` class at its
355/// loudest, and restricting the offer to 16x16 and below does not soften it
356/// (`le16`: +22.9/+3.1, +31.6/+4.0). So this takes the same content gate the
357/// intra search, palette and intrabc stand behind: a non-screen frame is
358/// byte-identical to the encoder before the lane.
359///
360/// `EC_AV1_TXSET_INTER`: `0`/`off`, `screen` (screen frames only), `le16`
361/// (16x16 and below, the sizes libaom's own census picks a non-`DCT_DCT`
362/// inter type on -- it never takes `IDTX` at 32x32 on film B), anything else
363/// on for every frame at every size.
364pub(crate) fn inter_tx_type_candidates(set: TxbSet, screen: bool) -> &'static [TxType] {
365 const DCT: [TxType; 1] = [TxType::DctDct];
366 const INTER3: [TxType; 2] = [TxType::DctDct, TxType::Idtx];
367 const INTER_WIDE: [TxType; 7] = [
368 TxType::DctDct,
369 TxType::AdstAdst,
370 TxType::AdstDct,
371 TxType::DctAdst,
372 TxType::Idtx,
373 TxType::VDct,
374 TxType::HDct,
375 ];
376 let mode = inter_tx_type_search();
377 let on = match mode {
378 InterTxSearch::Off => false,
379 InterTxSearch::Screen => screen,
380 InterTxSearch::All | InterTxSearch::Le16 => true,
381 };
382 match set {
383 TxbSet::Luma32Inter if on && mode != InterTxSearch::Le16 => &INTER3,
384 TxbSet::Luma16Inter | TxbSet::Luma8Inter | TxbSet::Luma4Inter if on => &INTER3,
385 // lane-txi: a `reduced_tx_set == 0` frame's inter 16x16 reads the
386 // TWELVE-type `TX_SET_INTER_2` and its 8x8/4x4 `ALL16` (inter 32x32
387 // stays the two-type `DCT_IDTX`). The seven offered here are the
388 // members those two alphabets SHARE with the intra set -- the four
389 // DTT combinations, `IDTX` and the two 1-D DCTs -- which is the
390 // candidate list rav1e's speed 6 prunes to; the FLIPADST family and
391 // the 1-D ADSTs are codable and left unoffered (deferred).
392 TxbSet::Luma16InterSet1 | TxbSet::Luma8InterSet1 | TxbSet::Luma4InterSet1 if on => {
393 &INTER_WIDE
394 }
395 _ => &DCT,
396 }
397}
398
399/// lane-txi: does THIS frame code `reduced_tx_set = 0` (spec 5.9.2), i.e.
400/// the wider `tx_type` alphabets at intra 8x8/4x4 and inter 16x16 and below?
401/// `EC_AV1_TXSET_WIDE`: `0`/`off`, `screen` (screen frames only), anything
402/// else every frame; unset takes [`crate::speed::WIDE_TX_SET`], screen-gated
403/// like both halves of the type search itself.
404pub(crate) fn wide_tx_set(screen: bool) -> bool {
405 match WIDE_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
406 0 => return false,
407 1 => return true,
408 _ => {}
409 }
410 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
411 crate::envflags::var("EC_AV1_TXSET_WIDE")
412 .ok()
413 .map(|v| match v.as_str() {
414 "0" | "off" => InterTxSearch::Off,
415 "screen" => InterTxSearch::Screen,
416 _ => InterTxSearch::All,
417 })
418 });
419 match ENV.unwrap_or(if crate::speed::at(&crate::speed::WIDE_TX_SET) {
420 InterTxSearch::Screen
421 } else {
422 InterTxSearch::Off
423 }) {
424 InterTxSearch::Off => false,
425 InterTxSearch::Screen => screen,
426 _ => true,
427 }
428}
429
430/// A PROCESS-GLOBAL [`wide_tx_set`] override that wins over both the
431/// environment and the preset (`u8::MAX` = unset), the shape
432/// [`set_inter_tx_search`] has: the lever is OFF at every preset, so the
433/// witness that has to see the wider alphabets turns it on through this while
434/// holding [`crate::speed::knob_write`].
435static WIDE_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
436
437/// Sets [`WIDE_TX_OVERRIDE`]; `None` clears it.
438#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
439pub(crate) fn set_wide_tx_set(on: Option<bool>) {
440 WIDE_TX_OVERRIDE.store(
441 on.map_or(u8::MAX, u8::from),
442 std::sync::atomic::Ordering::Relaxed,
443 );
444}
445
446/// The luma [`TxbSet`] the SEARCH and its pricer name for a frame that codes
447/// `reduced_tx_set = 0`: the writer reads the bit once, off the frame's own
448/// [`crate::cdf_state::Cdfs`], but the trial that prices a type has to read
449/// the same alphabet or the two disagree on what a `tx_type` symbol costs.
450pub(crate) fn luma_set_for(set: TxbSet, screen: bool) -> TxbSet {
451 if wide_tx_set(screen) { set.wide() } else { set }
452}
453
454#[derive(Clone, Copy, PartialEq)]
455pub(crate) enum InterTxSearch {
456 Off,
457 Screen,
458 /// 16x16 and below only.
459 Le16,
460 All,
461}
462
463/// A PROCESS-GLOBAL [`inter_tx_type_search`] override that wins over both the
464/// environment and the preset (`u8::MAX` = unset), the shape
465/// [`set_deltaq_res`] has: the lever is OFF at every preset, so the witness
466/// that has to see a non-`DCT_DCT` inter unit turns it on through this while
467/// holding [`crate::speed::knob_write`].
468static INTER_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
469
470/// Sets [`INTER_TX_OVERRIDE`]; `None` clears it.
471#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
472pub(crate) fn set_inter_tx_search(on: Option<bool>) {
473 INTER_TX_OVERRIDE.store(
474 on.map_or(u8::MAX, u8::from),
475 std::sync::atomic::Ordering::Relaxed,
476 );
477}
478
479fn inter_tx_type_search() -> InterTxSearch {
480 match INTER_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
481 0 => return InterTxSearch::Off,
482 1 => return InterTxSearch::All,
483 _ => {}
484 }
485 static ENV: std::sync::LazyLock<Option<InterTxSearch>> = std::sync::LazyLock::new(|| {
486 crate::envflags::var("EC_AV1_TXSET_INTER")
487 .ok()
488 .map(|v| match v.as_str() {
489 "0" | "off" => InterTxSearch::Off,
490 "screen" => InterTxSearch::Screen,
491 "le16" => InterTxSearch::Le16,
492 _ => InterTxSearch::All,
493 })
494 });
495 ENV.unwrap_or_else(|| {
496 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH_INTER) {
497 InterTxSearch::Screen
498 } else {
499 InterTxSearch::Off
500 }
501 })
502}
503
504/// The inter luma [`TxbSet`] a `tx`-sided transform unit reads, `None` for the
505/// 64-point one (it codes no `tx_type` symbol).
506/// lane-txw history, resolved by lane-intertx: the INTER half of the
507/// widening was blocked by `refusal-from-own-desync` twice over. Half of it
508/// was this writer coding a `V_DCT`/`H_DCT` unit as `TX_CLASS_2D`
509/// (`tile::write_coeffs`, fixed by lane-txw, which unblocked the intra
510/// half). The other half was the CHROMA inheritance: an inter block's
511/// chroma transform type is the luma type reduced to the chroma size's set
512/// (`decode::reduce_inherited_chroma_tx_type`), and (a) the encoder never
513/// set `FrameCtx::reduced_tx_set_inter`, so [`recode_inter_chroma`] reduced
514/// against a STALE allowance, and (b) `tile::write_block_planes` coded
515/// every chroma plane as `DCT_DCT`, so an inherited 1-D type desynced the
516/// chroma exactly as luma did. lane-intertx fixed both -- the frame sets
517/// its own bit on the context (`encode_inter_frame`), the writer derives
518/// the chroma type from this frame's own header bit
519/// (`reduce_inherited_chroma_tx_type_flagged`) -- and the widened SEARCH
520/// names these sets through [`luma_set_for`] at its call sites, so the
521/// wider candidates are reachable and honestly priced. The intra half
522/// never needed either (an intra block's chroma type comes off its own UV
523/// mode, never off luma).
524fn inter_luma_set(tx: usize) -> Option<TxbSet> {
525 Some(match tx {
526 4 => TxbSet::Luma4Inter,
527 8 => TxbSet::Luma8Inter,
528 16 => TxbSet::Luma16Inter,
529 32 => TxbSet::Luma32Inter,
530 _ => return None,
531 })
532}
533
534fn tx_type_search() -> bool {
535 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
536 crate::envflags::var("EC_AV1_TXSET")
537 .ok()
538 .map(|v| !matches!(v.as_str(), "0" | "off"))
539 });
540 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_TYPE_SEARCH))
541}
542
543/// Whether an intra luma unit of this frame searches its own type at all:
544/// the preset lever ([`tx_type_search`]) under the screen content gate, which
545/// `EC_AV1_TXSET=all` ([`intra_tx_all_frames`]) lifts and the process-global
546/// [`set_intra_tx_search`] override wins over (the witness needs the search
547/// on a frame the detector called non-screen).
548fn intra_tx_search_on(screen: bool) -> bool {
549 match INTRA_TX_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
550 0 => return false,
551 1 => return true,
552 _ => {}
553 }
554 (screen || intra_tx_all_frames()) && tx_type_search()
555}
556
557/// A PROCESS-GLOBAL [`intra_tx_search_on`] override (`u8::MAX` = unset), the
558/// shape [`set_inter_tx_search`] has.
559static INTRA_TX_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
560
561/// Sets [`INTRA_TX_OVERRIDE`]; `None` clears it.
562#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
563pub(crate) fn set_intra_tx_search(on: Option<bool>) {
564 INTRA_TX_OVERRIDE.store(
565 on.map_or(u8::MAX, u8::from),
566 std::sync::atomic::Ordering::Relaxed,
567 );
568}
569
570/// lane-txi: `EC_AV1_TXSET=all` offers the five-type intra set on EVERY
571/// frame -- the unconditional arm the gate measures -- instead of the screen
572/// content gate [`tx_type_candidates`] ships behind. Any other value keeps
573/// the gate (`0`/`off` still switches the search off entirely).
574fn intra_tx_all_frames() -> bool {
575 static ENV: std::sync::LazyLock<bool> =
576 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_TXSET").is_ok_and(|v| v == "all"));
577 *ENV
578}
579
580fn tx_select() -> bool {
581 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
582 crate::envflags::var("EC_AV1_TX_SELECT")
583 .ok()
584 .map(|v| !matches!(v.as_str(), "0" | "off"))
585 });
586 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::TX_SELECT_KEY))
587}
588
589fn split_inter_8() -> bool {
590 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
591 Some(v) if cfg!(test) => v != "0",
592 _ => crate::speed::at(&crate::speed::SPLIT_8),
593 }
594}
595
596/// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
597/// NEARESTMV candidate it always had.
598pub(crate) const LEAF_NEW_MV: bool = true;
599
600/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
601/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
602/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
603/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
604pub(crate) const EXTRA_REF_NEW_MV: bool = true;
605
606/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
607/// own best vector before that reference's `NEWMV` search is skipped: a
608/// factor on the search cost scale, `1.0` meaning "as good or better".
609/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
610/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
611/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
612/// extra searches drop from +27% to +4% of the base count -- and on screen
613/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
614/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
615/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on: 0.25
616/// reads +16.6/-0.6, +47.0/+19.1, +51.3/-14.3 and 0.5 reads +16.6/-0.7,
617/// +47.0/+19.1, +51.3/-14.3 against the base's +16.7/-0.5, +47.0/+19.1,
618/// +51.3/-14.3 -- one row 0.1-0.2 down, two flat, inside the measurement's
619/// own noise. 0.35 stays; the lever that did move at the new rate weight is
620/// [`LEAF_SECOND_NEW_MARGIN`], not this one.
621const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
622
623/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
624fn extra_new_skip_margin() -> f64 {
625 match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
626 Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
627 _ => EXTRA_NEW_SKIP_MARGIN,
628 }
629}
630
631/// The margin on a LEAF's SECOND-reference motion search, the same early-out
632/// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference
633/// `NEWMV`: the search is skipped when that reference's own
634/// `NEAREST_NEARESTMV` vector already prices this many times better than the
635/// leaf's `LAST` search found. `0.0` never skips.
636///
637/// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs
638/// libaom (1080p/2160p/screen) against the extra `motion::search` calls at
639/// 2160p (38195 with no second-reference search at all):
640/// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093,
641/// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at
642/// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the
643/// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter
644/// of its extra searches; past it the calls double for another -0.3/-0.5.
645/// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is
646/// all `NEAREST_NEARESTMV` and no searched second vector ever wins there --
647/// so the margin is pure wall on that content (+10% searches at 0.8).
648///
649/// RE-SWEPT on lane-av1rejudge after [`LAMBDA_SCALE`] moved 0.1 -> 0.05, on
650/// the native gate with local warp on, BD vs libaom / vs rav1e:
651///
652/// | margin | film 1080p | film 2160p | screen |
653/// |---|---|---|---|
654/// | 0.6 | +16.9 / -0.4 | +47.0 / +19.1 | +51.2 / -14.4 |
655/// | 0.8 (was) | +16.7 / -0.5 | +47.0 / +19.1 | +51.3 / -14.3 |
656/// | 1.2 | +16.2 / -1.1 | +46.6 / +18.8 | +51.3 / -14.4 |
657/// | 1.6 | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
658/// | 0.0 (never skip) | +16.4 / -0.8 | +46.6 / +18.8 | +51.3 / -14.4 |
659///
660/// 1.2 is the floor of that bowl -- two rows 0.3-0.6 down on BOTH columns
661/// with screen flat -- and it beats never-skipping, i.e. the early-out is
662/// still worth having, just at a looser margin than the old rate weight
663/// wanted. It costs about 10% encoder wall on the two film clips (36.6s vs
664/// 32.6s at 2160p), which is the price of the extra second-reference
665/// searches.
666const LEAF_SECOND_NEW_MARGIN: f64 = 1.2;
667
668/// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the
669/// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`.
670fn leaf_second_new_margin() -> f64 {
671 match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() {
672 Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN),
673 None => LEAF_SECOND_NEW_MARGIN,
674 }
675}
676
677/// Whether a leaf searches its SECOND reference at all (lane-av1comp4).
678fn leaf_second_new_mv() -> bool {
679 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
680 Some(v) => v != "0",
681 None => crate::speed::at(&crate::speed::LEAF_SECOND),
682 }
683}
684
685/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
686/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
687/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
688/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
689/// was missing was the encoder ever forming one below 32x32.
690pub(crate) const LEAF_COMPOUND: bool = true;
691
692/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
693fn leaf_compound() -> bool {
694 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
695 Some(v) => v != "0",
696 None => crate::speed::at(&crate::speed::LEAF_COMPOUND),
697 }
698}
699
700/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
701fn leaf_new_mv() -> bool {
702 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
703 Some(v) if cfg!(test) => v != "0",
704 _ => LEAF_NEW_MV,
705 }
706}
707
708/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
709/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
710/// the true frame edge cut through was ever split there; inside the frame
711/// every block was coded whole, which left the partition decision the key
712/// frame already makes unmade for eleven frames out of twelve.
713pub(crate) const SPLIT_INTER_BLOCKS: bool = true;
714
715/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
716/// measurement that keeps it is running (test builds only, like
717/// [`lambda_scale`]).
718fn split_inter_blocks() -> bool {
719 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
720 Some(v) if cfg!(test) => v != "0",
721 _ => crate::speed::at(&crate::speed::SPLIT_INTER),
722 }
723}
724
725/// Whether the inter search offers the whole superblock as ONE 64x64 block
726/// (`PARTITION_NONE` at `BLOCK_64X64`), coded SKIP, against the four 32x32
727/// quadrants it would otherwise always split into.
728///
729/// The census (`lanes/census-filmB.md`) is what points here: rav1e speed 6
730/// codes 45.2% of its blocks at 64x64 -- 73.8% of its LEAF blocks, 99.2% of
731/// them skip at 328 bytes a frame -- while every block this encoder wrote was
732/// 32x32 or smaller, which put our mode+mv+partition+tx_size spend at 162,669
733/// bits against rav1e's 61,988, about 46% of the film B gap.
734///
735/// lane-tx64: no longer skip-only. The root also prices a REAL residual --
736/// one TX_64X64 luma transform (`transform.rs`'s forward network has always
737/// reached 64 points; what was missing was the block coder and the writer
738/// around it) and one TX_32X32 per chroma plane -- see [`b64_residual`],
739/// which carries that arm's own gate table. Still refused at the 64 root:
740/// compound references, a depth-1 4x32x32 var-tx tree, intra, and a
741/// superblock the true frame edge cuts through.
742///
743/// Switched off by `EC_AV1_B64=0` in any build; `EC_AV1_B64RES=0` keeps the
744/// root and restores the skip-only shape lane-b64 shipped.
745pub(crate) const B64_ROOT: bool = true;
746
747/// How many superblocks took the 64x64 root since the last
748/// [`take_b64_root_hits`], so a gate reports how often it fires rather than
749/// assuming it does (class `gate-blind-to-feature`).
750static B64_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
751
752/// The 64x64-root count since the last call, and zero it.
753pub fn take_b64_root_hits() -> usize {
754 B64_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
755}
756
757/// Whether the 128 superblock root offers its `PARTITION_NONE` candidate at
758/// all ([`search_root_128`]). On by default; `EC_AV1_B128=0` turns it off,
759/// which is the attribution arm for a 128-superblock stream: it separates
760/// what the SIZE costs from what the 128x128 BLOCK buys.
761fn b128_root() -> bool {
762 static ENV: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
763 crate::envflags::var("EC_AV1_B128")
764 .ok()
765 .is_none_or(|v| v != "0")
766 });
767 *ENV
768}
769
770/// lane-b128r: whether the 128 root prices a REAL residual as well as the
771/// skip arm -- four TX_64X64 luma units interleaved with a TX_32X32 chroma
772/// pair per 64x64 mu chunk, var-tx depth 0 (the shape
773/// [`crate::tile::write_inter_block_128`] codes and `decode_inter_block`
774/// reads). Written, witnessed and byte-exact through both decoders, and
775/// **off by default** (`EC_AV1_B128RES=1` turns it on) because it is INERT
776/// on content: the RD takes it 0.7-1.9 times per frame against thousands of
777/// whole 128 roots (lane-b128res census, native 12-frame gate, every clip),
778/// and the BD effect is inside the noise on both gates -- long-GOP films
779/// -0.1/+0.1 and all five 12-frame rows within 0.1 of the off default.
780///
781/// The historical reason for the parking is CLOSED: the bars 2160p q=90
782/// frame 11 disagreement with ffmpeg (8 luma samples at the rows above a
783/// 128-superblock horizontal edge) was the CDEF search pricing a preset per
784/// 64x64 unit under a root that codes ONE literal for all four -- lane-
785/// edge128's `crate::tile::cdef_unit_owner` collapses the four to the one
786/// the decoder derives, and on this HEAD the same row re-measures three-way
787/// EXACT (encoder reconstruction == ffmpeg == `decode_stream`, every frame,
788/// every plane, both gates). The knob stays as the arm's gate, not as a
789/// defect flag.
790fn b128_residual() -> bool {
791 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
792 crate::envflags::var("EC_AV1_B128RES")
793 .ok()
794 .map(|v| v != "0")
795 });
796 (ENV.unwrap_or(false) || FORCE_B128_RESIDUAL.load(std::sync::atomic::Ordering::Relaxed))
797 && b128_root()
798}
799/// lane-rectres: whether the 128 root's RECTANGULAR pieces -- the two
800/// HORZ/VERT halves and the four AB shapes' three pieces (two 64x64 squares
801/// plus one half) -- price a REAL residual in the RD as well as the skip arm
802/// ([`search_root_128_rect`] / [`search_root_128_ab`], written through
803/// [`crate::tile::write_inter_block_128_rect`]). **Off by default**
804/// (`EC_AV1_RECTRES=1` turns it on): OFF is today's behavior bit for bit --
805/// no rect/AB piece can come out non-skip, so the writer's refusal is never
806/// reached. The residual shape is the whole 128 block's, halved or quartered
807/// per piece: one TX_64X64 luma unit plus a TX_32X32 chroma pair per 64x64
808/// mu chunk, var-tx depth 0 (exactly what the decoder's mu-chunk loop reads
809/// for any inter partition shape).
810fn rectres() -> bool {
811 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
812 crate::envflags::var("EC_AV1_RECTRES")
813 .ok()
814 .map(|v| v != "0")
815 });
816 ENV.unwrap_or(false) || FORCE_B128_RECTRES.load(std::sync::atomic::Ordering::Relaxed)
817}
818
819/// Test-only: take the rect/AB pieces' residual arm whatever it costs, so a
820/// witness clip codes the shape rather than waiting for content on which the
821/// RD picks it (the same role [`FORCE_B128_RESIDUAL`] plays at the NONE
822/// root). Never read outside `#[cfg(test)]` builds.
823static FORCE_B128_RECTRES: std::sync::atomic::AtomicBool =
824 std::sync::atomic::AtomicBool::new(false);
825
826/// Arms [`FORCE_B128_RECTRES`] for the rest of the process.
827#[cfg(test)]
828pub(crate) fn force_b128_rectres(on: bool) {
829 FORCE_B128_RECTRES.store(on, std::sync::atomic::Ordering::Relaxed);
830}
831
832/// How many rect/AB pieces the search left WITH a residual rather than
833/// skipped, since the last [`take_b128_rectres_hits`] (class
834/// `gate-blind-to-feature`).
835static B128_RECTRES_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
836
837/// The rect/AB-piece-residual count since the last call, and zero it.
838pub fn take_b128_rectres_hits() -> usize {
839 B128_RECTRES_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
840}
841
842/// lane-b128r: whether the 128 root offers the COMPOUND candidates the 64
843/// root already does (`NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`,
844/// `NEW_NEARESTMV` over the LAST+GOLDEN / LAST+ALTREF pairs), at the block's
845/// own 32x32-mi window. `EC_AV1_B128COMP=0` turns it off, which is this
846/// arm's attribution control; the writer has always had the path
847/// (`write_inter_block_128` calls `write_compound_block` for a block that
848/// names a second reference).
849fn b128_compound() -> bool {
850 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
851 crate::envflags::var("EC_AV1_B128COMP")
852 .ok()
853 .map(|v| v != "0")
854 });
855 ENV.unwrap_or(true) && b128_root()
856}
857
858/// How many 128 roots came out COMPOUND since the last
859/// [`take_b128_compound_hits`] (class `gate-blind-to-feature`).
860static B128_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
861
862/// The compound-128 count since the last call, and zero it.
863pub fn take_b128_compound_hits() -> usize {
864 B128_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
865}
866
867/// lane-b128hv: whether the 128 superblock root offers its `PARTITION_HORZ`
868/// and `PARTITION_VERT` candidates -- two 128x64 / 64x128 inter blocks, the
869/// same skip-only single-reference/compound machinery the NONE arm ships,
870/// halved ([`search_root_128_rect`], `crate::tile::write_inter_block_128_rect`).
871/// `EC_AV1_B128HV=0` is this arm's attribution control.
872fn b128_rect() -> bool {
873 static ENV: std::sync::LazyLock<Option<bool>> =
874 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B128HV").ok().map(|v| v != "0"));
875 ENV.unwrap_or(true) && b128_root()
876}
877
878/// lane-rectdq: whether the delta_q symbol group is priced on the root
879/// candidates that really code it. `EC_AV1_RECTDQ=0` is this fix's
880/// attribution control (the pre-lane pricing, where a 128 rect root and the
881/// four-superblock arm were both priced as if the group were free).
882fn rectdq() -> bool {
883 static ENV: std::sync::LazyLock<Option<bool>> =
884 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_RECTDQ").ok().map(|v| v != "0"));
885 ENV.unwrap_or(true)
886}
887
888/// lane-rectdq: what `crate::tile::write_delta_q` spends to move
889/// `CurrentQIndex` from `cur` to `target` at `1 << delta_q_res` steps of
890/// `res` -- the same three pieces that writer codes, in its order: the
891/// `delta_q_abs` symbol of `min(abs, 3)` against the DEFAULT table (the
892/// writer's own `cdfs.delta_q`, which every tile arms fresh, adapts from
893/// exactly this row), the escape literal pair when `abs >= 3`, and the sign
894/// bit when `abs != 0`. Zero when the plan is disarmed (`res <= 0`).
895pub(crate) fn delta_q_bits(target: i32, cur: i32, res: i32) -> f64 {
896 if res <= 0 {
897 return 0.0;
898 }
899 /// spec `DELTA_Q_SMALL`, as in the writer.
900 const DELTA_Q_SMALL: usize = 3;
901 let reduced = (target - cur) / res;
902 let abs = reduced.unsigned_abs() as usize;
903 // A pricing coder, not a sum of table entries: the escape's literal bits
904 // are equiprobable SYMBOLS whose narrowing carries the `EC_MIN_PROB`
905 // floor, so each really costs a little over one bit (class
906 // `price-the-narrowing-not-the-table`). Read off the same
907 // `SymbolEncoder::bits` account the writer's own coder keeps.
908 let mut enc = crate::msac::SymbolEncoder::pricer();
909 enc.reset_bits();
910 enc.symbol_fixed(abs.min(DELTA_Q_SMALL), &cdf::DELTA_Q);
911 if abs >= DELTA_Q_SMALL {
912 let rem_bits = 31 - ((abs as u32) - 1).leading_zeros();
913 enc.literal(rem_bits - 1, 3);
914 enc.literal(abs as u32 - ((1u32 << rem_bits) + 1), rem_bits);
915 }
916 if abs != 0 {
917 enc.literal(u32::from(reduced < 0), 1);
918 }
919 enc.bits()
920}
921
922/// [`delta_q_bits`] for the 128 superblock root at `(root_r, root_c)` (in 64
923/// superblock units): the group every root shape but a SKIPPED
924/// `PARTITION_NONE` root codes, since decode.rs' `whole_sb` asks for
925/// `side == write_w == write_h == sb_px` and neither a rect half nor a 64
926/// superblock under a 128 grid is that.
927///
928/// The target is the root's own cell of the `sb_q` grid, exactly the entry
929/// `write_delta_q` indexes. `CurrentQIndex` is NOT knowable in the search --
930/// the writer's `plan.cur` only advances at the roots that really code a
931/// group, and which those are is decided by this very comparison -- so the
932/// PREVIOUS 128 root's target in raster order stands in for it (the frame's
933/// `base_q_idx` at the first root of the frame, which is also the writer's
934/// own per-tile reset). Wrong only where a neighbouring root came out a
935/// skipped NONE block, and then only by the difference of two adjacent tpl
936/// cells.
937fn delta_q_bits_at_root(
938 sb_q: Option<&Vec<u8>>,
939 sb_cols: usize,
940 base_q_idx: u8,
941 res: i32,
942 (root_r, root_c): (usize, usize),
943) -> f64 {
944 if !rectdq() || res <= 0 {
945 return 0.0;
946 }
947 let Some(q) = sb_q.filter(|q| !q.is_empty()) else {
948 return 0.0;
949 };
950 let at = |r: usize, c: usize| i32::from(q[(r * sb_cols + c).min(q.len() - 1)]);
951 let target = at(root_r, root_c);
952 let cur = if root_c >= 2 {
953 at(root_r, root_c - 2)
954 } else if root_r >= 2 {
955 // The last 128 root of the row above, i.e. the previous one in the
956 // writer's raster walk.
957 at(root_r - 2, (sb_cols.saturating_sub(1)) & !1)
958 } else {
959 i32::from(base_q_idx)
960 };
961 delta_q_bits(target, cur, res)
962}
963
964/// How many 128 roots the search left as two 128x64 (HORZ) / 64x128 (VERT)
965/// halves since the last take (class `gate-blind-to-feature`).
966static B128_HORZ_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
967/// The VERT twin of [`B128_HORZ_HITS`].
968static B128_VERT_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
969
970/// The HORZ-128-root count since the last call, and zero it.
971pub fn take_b128_horz_hits() -> usize {
972 B128_HORZ_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
973}
974
975/// The VERT-128-root count since the last call, and zero it.
976pub fn take_b128_vert_hits() -> usize {
977 B128_VERT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
978}
979
980/// Test-only: force the 128 root's rect partition whatever it costs -- 0 off,
981/// 1 `PARTITION_HORZ`, 2 `PARTITION_VERT`. The witness needs it because
982/// synthetic content is where the shape is cheapest to decode-check and the
983/// RD there prefers one whole block; the gate census is the unforced count.
984static FORCE_B128_RECT: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
985
986/// Arms [`FORCE_B128_RECT`] for the rest of the process (0 / 1 HORZ / 2 VERT).
987#[cfg(test)]
988pub(crate) fn force_b128_rect(which: u8) {
989 FORCE_B128_RECT.store(which, std::sync::atomic::Ordering::Relaxed);
990}
991
992/// lane-ab128: whether the 128 superblock root offers its four AB shapes --
993/// `PARTITION_HORZ_A` (two 64x64 on top, one 128x64 below), `_HORZ_B` (one
994/// 128x64 on top, two 64x64 below), `_VERT_A` (two 64x64 left, one 64x128
995/// right) and `_VERT_B` (one 64x128 left, two 64x64 right). Every piece is
996/// the same skip-only single-reference/compound block the NONE and HORZ/VERT
997/// arms ship, at its own footprint ([`search_root_128_ab`],
998/// `crate::tile::write_inter_block_128_rect`). `EC_AV1_B128AB=0` is this
999/// arm's attribution control.
1000///
1001/// **Off by default** (`EC_AV1_B128AB=1` turns it on): measured on both gates
1002/// and it does not pay. The shapes fire 0-2 roots a frame against ~1000 coded
1003/// blocks (`EC_AV1_B128_CENSUS`), and every row is flat or 0.1 worse --
1004/// long-GOP film A +22.0/-8.5 against a +21.9/-8.6 control, film B +75.8/+0.8
1005/// against the same, 12-frame film A +18.1/-6.2 against +18.0/-6.3, film B
1006/// +23.1/-3.3 against +23.0/-3.5, screen byte-identical (lane-ab128). The
1007/// machinery is written, witnessed sample-exact through both decoders on all
1008/// four shapes, and kept for the arm that makes it pay: a non-skip piece (the
1009/// 64x64 pieces could carry the 64 root's residual, which is where libaom's
1010/// AB shapes earn their keep) or a cheaper partition price.
1011fn b128_ab() -> bool {
1012 static ENV: std::sync::LazyLock<Option<bool>> =
1013 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B128AB").ok().map(|v| v != "0"));
1014 ENV.unwrap_or(false) && b128_root()
1015}
1016
1017/// How many 128 roots the search left as each AB shape since the last take,
1018/// in `PARTITION_HORZ_A`, `_HORZ_B`, `_VERT_A`, `_VERT_B` order (class
1019/// `gate-blind-to-feature`).
1020static B128_AB_HITS: [std::sync::atomic::AtomicUsize; 4] =
1021 [const { std::sync::atomic::AtomicUsize::new(0) }; 4];
1022
1023/// The four per-shape AB-root counts since the last call, and zero them.
1024pub fn take_b128_ab_hits() -> [usize; 4] {
1025 std::array::from_fn(|i| B128_AB_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1026}
1027
1028/// Test-only: force the 128 root's AB shape whatever it costs -- 0 off, then
1029/// 4..=7, the partition symbol itself ([`force_b128_rect`]'s twin; synthetic
1030/// content is where the shapes are cheapest to decode-check and the RD there
1031/// prefers one whole block).
1032static FORCE_B128_AB: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
1033
1034/// Arms [`FORCE_B128_AB`] for the rest of the process (0 off, else 4..=7).
1035#[cfg(test)]
1036pub(crate) fn force_b128_ab(which: u8) {
1037 FORCE_B128_AB.store(which, std::sync::atomic::Ordering::Relaxed);
1038}
1039
1040/// lane-ab128: the three pieces of an AB shape at a 128 root, in the order
1041/// libaom's `decode_partition` codes them and decode.rs' `sb128_ab` arm
1042/// reads them (decode.rs ~35269) -- HORZ_A = TL, TR, bottom half; HORZ_B =
1043/// top half, BL, BR; VERT_A = TL, BL, right half; VERT_B = left half, TR, BR.
1044/// Each entry is the piece's own top-left in mode-info units and its
1045/// footprint in samples.
1046pub(crate) fn ab128_pieces(
1047 symbol: usize,
1048 (mi_row, mi_col): (usize, usize),
1049) -> [((usize, usize), (usize, usize)); 3] {
1050 const S: usize = SUPERBLOCK;
1051 let (r, c) = (mi_row, mi_col);
1052 let (r1, c1) = (mi_row + 16, mi_col + 16);
1053 match symbol {
1054 // PARTITION_HORZ_A
1055 4 => [((r, c), (S, S)), ((r, c1), (S, S)), ((r1, c), (S * 2, S))],
1056 // PARTITION_HORZ_B
1057 5 => [((r, c), (S * 2, S)), ((r1, c), (S, S)), ((r1, c1), (S, S))],
1058 // PARTITION_VERT_A
1059 6 => [((r, c), (S, S)), ((r1, c), (S, S)), ((r, c1), (S, S * 2))],
1060 // PARTITION_VERT_B
1061 _ => [((r, c), (S, S * 2)), ((r, c1), (S, S)), ((r1, c1), (S, S))],
1062 }
1063}
1064
1065/// Test-only: take the 128 root's residual arm whatever it costs, so a
1066/// witness clip codes the shape rather than waiting for content on which the
1067/// RD picks it (the same role [`force_sb128`] plays for the superblock size).
1068/// Never read outside `#[cfg(test)]` builds.
1069static FORCE_B128_RESIDUAL: std::sync::atomic::AtomicBool =
1070 std::sync::atomic::AtomicBool::new(false);
1071
1072/// Test-only twin of [`FORCE_B128_RESIDUAL`] for the PARTITION decision: take
1073/// the 128 root whenever it produced a candidate at all, whatever its four
1074/// cells cost, so a witness codes the block it is about rather than waiting
1075/// for content on which the root also wins its own comparison.
1076static FORCE_B128_ROOT: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
1077
1078/// Arms [`FORCE_B128_RESIDUAL`] -- and with it [`FORCE_B128_ROOT`], since a
1079/// forced residual block only reaches the writer if its root is taken.
1080#[cfg(test)]
1081pub(crate) fn force_b128_residual(on: bool) {
1082 FORCE_B128_RESIDUAL.store(on, std::sync::atomic::Ordering::Relaxed);
1083 force_b128_root(on);
1084}
1085
1086/// Arms [`FORCE_B128_ROOT`] for the rest of the process.
1087#[cfg(test)]
1088pub(crate) fn force_b128_root(on: bool) {
1089 FORCE_B128_ROOT.store(on, std::sync::atomic::Ordering::Relaxed);
1090}
1091
1092/// How many 128 roots came out cheaper WITH a residual than skipped, since
1093/// the last [`take_b128_residual_hits`] (class `gate-blind-to-feature`).
1094static B128_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1095
1096/// The 128-residual count since the last call, and zero it.
1097pub fn take_b128_residual_hits() -> usize {
1098 B128_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1099}
1100
1101/// How many 128x128 `PARTITION_NONE` roots the search took since the last
1102/// [`take_b128_none_hits`] (class `gate-blind-to-feature`): a flat BD result
1103/// is only attributable once the fire count is known.
1104static B128_NONE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1105
1106/// The 128x128-root count since the last call, and zero it.
1107pub fn take_b128_none_hits() -> usize {
1108 B128_NONE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1109}
1110
1111/// Rate-distortion optimised quantisation ([`crate::tile::rdoq`], lane-rdoq).
1112/// Preset-gated: it re-prices the block once per candidate level, so it buys
1113/// bits with wall (see `crate::speed::RDOQ` for the per-preset table).
1114///
1115/// `EC_AV1_RDOQ=0` in any build restores the plain deadzone quantiser --
1116/// which is what the byte pins are taken under when they name it.
1117fn rdoq_on() -> bool {
1118 static ENV: std::sync::LazyLock<Option<bool>> =
1119 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_RDOQ").ok().map(|v| v != "0"));
1120 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::RDOQ))
1121}
1122
1123/// The rate weight [`crate::tile::rdoq`] trades bits for squared error at, in
1124/// units of one squared AC quantiser step -- the search's own
1125/// [`LAMBDA_SCALE`], so the quantiser and the mode search speak one currency.
1126///
1127/// The per-frame factors the search multiplies onto it ([`key_lambda_factor`],
1128/// [`hidden_lambda_factor`], both 1.0 as shipped) and the per-superblock
1129/// temporal map ([`tpl_lambda_factors`]) are NOT threaded down here:
1130/// corner-cut, ceiling = a superblock the temporal map weighs away from the
1131/// frame average has its coefficients optimised at the frame's weight. The
1132/// upgrade is one `lambda` field on the trial call sites, which is the whole
1133/// mode-search argument list.
1134///
1135/// SWEPT (lane-rdoq, 12-frame `bd_rate_screen_native`, BD vs libaom
1136/// `cpu-used 6` on the three real rows). The bowl is a factor of TWO above
1137/// the mode search's own weight, and it is the same multiplier on all three
1138/// rows:
1139///
1140/// | `EC_AV1_RDOQ_LAMBDA` | film A | film B | screen |
1141/// |---|---|---|---|
1142/// | 0.7 | +27.6 | +39.5 | +29.6 |
1143/// | 1.0 | +26.3 | +37.5 | +29.1 |
1144/// | 1.3 | +25.6 | +37.0 | +28.8 |
1145/// | 1.6 | +24.6 | +35.9 | +28.7 |
1146/// | 2.2 (shipped) | +24.4 | +35.5 | +28.1 |
1147/// | 3.2 | +24.7 | +36.1 | +29.4 |
1148///
1149/// A coefficient's rate is worth twice here what the mode search prices it
1150/// at, and the likeliest reason is that the price is taken against tables
1151/// that have not adapted yet ([`crate::tile::coeff_bits`]): a block coded
1152/// late in a frame whose `txb_skip`/`base` tables have narrowed really costs
1153/// less than the pricer says, and this pass is the one decision taken per
1154/// COEFFICIENT, so it feels that error most. The honest fix is an adapted
1155/// price, not a fitted multiplier; this is the fitted multiplier, and its
1156/// bowl is measured rather than assumed.
1157const RDOQ_LAMBDA_MULT: f64 = 2.2;
1158
1159/// [`RDOQ_LAMBDA_MULT`], or what `EC_AV1_RDOQ_LAMBDA` names (the rate-term
1160/// calibration sweep).
1161fn rdoq_lambda() -> f64 {
1162 static MULT: std::sync::LazyLock<f64> = std::sync::LazyLock::new(|| {
1163 crate::envflags::var("EC_AV1_RDOQ_LAMBDA")
1164 .ok()
1165 .and_then(|v| v.parse().ok())
1166 .unwrap_or(RDOQ_LAMBDA_MULT)
1167 });
1168 lambda_scale() * *MULT
1169}
1170
1171/// [`B64_ROOT`], or what `EC_AV1_B64` names.
1172fn b64_root() -> bool {
1173 static ENV: std::sync::LazyLock<Option<bool>> =
1174 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B64").ok().map(|v| v != "0"));
1175 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::B64_ROOT))
1176}
1177
1178/// The KEY frame's own 64x64 root (lane-i64): the whole superblock searched
1179/// as ONE intra block -- every mode the 32x32 search offers, one TX_64X64
1180/// luma transform (`TxbSet::Luma64`, whose coded quarter is the 32x32 corner)
1181/// and one TX_32X32 per chroma plane -- and compared against the four 32x32
1182/// quadrants at the same lambda, exactly the shape the inter root
1183/// ([`B64_ROOT`]) takes on an inter frame. The writer has always been able to
1184/// code one (`crate::tile::sb_coeff_key_frame_tile`'s `Superblock::Whole`);
1185/// nothing produced one, so the key frame -- 21.6% of a real film stream --
1186/// coded every superblock split while libaom and rav1e leave 45-54% of theirs
1187/// whole.
1188///
1189/// No CfL (spec `is_cfl_allowed` stops at 32x32, and `search_chroma` gates on
1190/// it), no filter intra (`filter_intra_size_class` has no 64 row) and no
1191/// transform-depth split (the writer's `Superblock::Whole` arm takes a 32x32
1192/// level grid, so only depth 0 is representable) -- the root is refused
1193/// outright on an `allow_intrabc` frame, whose quadrant searches carry DV
1194/// state a discarded trial would desync.
1195///
1196/// Switched off by `EC_AV1_I64=0` in any build.
1197pub(crate) const I64_ROOT: bool = true;
1198
1199/// How many key-frame superblocks were coded as one 64x64 intra block since
1200/// the last [`take_i64_root_hits`], so a gate reports the fire rate rather
1201/// than assuming it (class `gate-blind-to-feature`).
1202/// Index 1 is how many were OFFERED the trial at all, so a gate reads a
1203/// SHARE and not a bare count, and index 2 how many of the whole ones sat on
1204/// a superblock the true frame edge CUTS THROUGH (lane-corner) -- the
1205/// `gate-blind-to-feature` guard for the edge path, which no
1206/// superblock-aligned clip fires at all.
1207static I64_HITS: [std::sync::atomic::AtomicUsize; 3] =
1208 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
1209
1210/// The key-frame `(whole, offered, edge)` 64x64-intra-root counts since the
1211/// last call, and zero them.
1212pub fn take_i64_root_hits() -> [usize; 3] {
1213 std::array::from_fn(|i| I64_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1214}
1215
1216/// [`I64_ROOT`], or what `EC_AV1_I64` names.
1217fn i64_root() -> bool {
1218 static ENV: std::sync::LazyLock<Option<bool>> =
1219 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_I64").ok().map(|v| v != "0"));
1220 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::I64_ROOT))
1221}
1222
1223/// Whether the 64x64 root also prices a NON-skip candidate (lane-tx64): the
1224/// winner's prediction through one TX_64X64 luma transform and two TX_32X32
1225/// chroma ones. Off by `EC_AV1_B64RES=0`, which restores the skip-only root
1226/// lane-b64 shipped, so the two can be measured against each other on the
1227/// same build.
1228///
1229/// MEASURED on the native gate (two arms of one build, baseline reproduced to
1230/// the tenth): both film rows improve on both columns -- film A
1231/// +43.0/+15.0 -> +42.9/+14.8, film B +64.7/+34.0 -> +63.3/+31.5 -- and
1232/// SCREEN CAPTURE loses +33.4/-23.8 -> +34.3/-23.4, outside the keep rule's
1233/// +-0.3 screen clause. So the caller gates this off on a screen frame
1234/// (`allow_screen_content_tools`), the same content gate the coding pyramid
1235/// takes: a desktop capture's 64x64 superblocks are flat runs whose skip arm
1236/// already codes them for nothing, and a residual there only spends bits the
1237/// intra/palette tools would have spent better.
1238///
1239/// CENSUS on film B (12 frames, q120, `EC_AV1_BITCENSUS=1` +
1240/// `examples/syntax_census.rs`, both streams read by OUR decoder), off vs on:
1241///
1242/// | | skip-only | + residual |
1243/// |---|---|---|
1244/// | 64x64 share, all frames | 36.4% | 38.3% |
1245/// | 64x64 share, leaf frames | 53.3% | 56.0% |
1246/// | skip area, all frames | 80.4% | 78.8% |
1247/// | skip area, leaf frames | 90.2% | 88.5% |
1248/// | stream bytes | 34,366 | 34,295 |
1249/// | encoder wall | 13.4s | 9.6s |
1250///
1251/// `base_luma_64` enters the leaf frames' top tables at 5.7%, i.e. the
1252/// TX_64X64 coefficients are really being coded. The root wins MORE often
1253/// with a residual to offer (rav1e speed 6's own 64x64 share on this clip is
1254/// 45.2%), which is also why the arm is 28% FASTER despite costing three more
1255/// transforms per superblock: a root that wins is four quadrant searches that
1256/// never run.
1257fn b64_residual() -> bool {
1258 static ENV: std::sync::LazyLock<Option<bool>> =
1259 std::sync::LazyLock::new(|| crate::envflags::var("EC_AV1_B64RES").ok().map(|v| v != "0"));
1260 ENV.unwrap_or(true) && b64_root()
1261}
1262
1263/// How many 64x64 roots came out cheaper with a residual than skipped, since
1264/// the last [`take_b64_residual_hits`] -- so a gate reports the fire rate
1265/// rather than assuming one (class `gate-blind-to-feature`).
1266static B64_RESIDUAL_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1267
1268/// The non-skip 64x64-root count since the last call, and zero it.
1269pub fn take_b64_residual_hits() -> usize {
1270 B64_RESIDUAL_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1271}
1272
1273/// Whether the 64x64 root also prices COMPOUND candidates (lane-b64b): the
1274/// `LAST` + extra-reference pairs the 32x32 level already offers, at the
1275/// three modes a root can form without a second 64x64 motion search --
1276/// `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` (whose NEW half
1277/// is the vector `search_skip_64`'s own single-reference search already
1278/// found). `NEAREST_NEWMV`/`NEW_NEWMV` need the SECOND reference's own
1279/// `NEWMV` vector, which only a second search per superblock produces -- the
1280/// wall this root exists to save -- so they are not offered here.
1281///
1282/// Off by `EC_AV1_B64COMP=0`, so both arms measure on one build.
1283fn b64_compound() -> bool {
1284 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1285 crate::envflags::var("EC_AV1_B64COMP")
1286 .ok()
1287 .map(|v| v != "0")
1288 });
1289 ENV.unwrap_or(true) && b64_root()
1290}
1291
1292/// How many 64x64 roots took a COMPOUND candidate since the last
1293/// [`take_b64_compound_hits`] (class `gate-blind-to-feature`).
1294static B64_COMPOUND_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1295
1296/// The compound 64x64-root count since the last call, and zero it.
1297pub fn take_b64_compound_hits() -> usize {
1298 B64_COMPOUND_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1299}
1300
1301/// Whether a 64x64 root that codes a residual may SPLIT its luma transform
1302/// (lane-b64b): four TX_32X32 units instead of the one TX_64X64, decided by
1303/// [`commit_inter_luma`] like every other inter block's var-tx, and coded by
1304/// the writer's `Whole64` arm as `txfm_split = 1`. It exists because
1305/// TX_64X64 zeroes everything outside its 32x32 corner, so a root whose
1306/// residual has detail in the other three quadrants cannot code it at all.
1307///
1308/// Off by `EC_AV1_B64VARTX=0`.
1309fn b64_var_tx() -> bool {
1310 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1311 crate::envflags::var("EC_AV1_B64VARTX")
1312 .ok()
1313 .map(|v| v != "0")
1314 });
1315 ENV.unwrap_or(true) && b64_root()
1316}
1317
1318/// How many 64x64 roots split their luma transform since the last
1319/// [`take_b64_var_tx_hits`].
1320static B64_VAR_TX_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1321
1322/// The split-luma 64x64-root count since the last call, and zero it.
1323pub fn take_b64_var_tx_hits() -> usize {
1324 B64_VAR_TX_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1325}
1326
1327/// Whether a superblock the true frame edge CUTS THROUGH may be left whole
1328/// (lane-b64b). AV1 asks only that the block's own half is inside
1329/// (`has_cols`/`has_rows`, spec `decode_partition`), and the writer already
1330/// codes that case; what was missing was a trial whose SSE is scored over the
1331/// INSIDE part alone ([`Plane::block_sse`], which clips since lane-sse)
1332/// instead of over the padding the encoder
1333/// invented past the edge. Both gate films are superblock-aligned, so this
1334/// only reaches the user's own arbitrary export sizes.
1335///
1336/// Off by `EC_AV1_B64EDGE=0`.
1337fn b64_edge() -> bool {
1338 edge_root_enabled() && b64_root()
1339}
1340
1341/// What `EC_AV1_B64EDGE` names on its own, without the inter root's own
1342/// preset switch -- the key frame's root ([`I64_ROOT`]) reads the same flag
1343/// but is gated by [`i64_root`].
1344fn edge_root_enabled() -> bool {
1345 static ENV: std::sync::LazyLock<Option<bool>> = std::sync::LazyLock::new(|| {
1346 crate::envflags::var("EC_AV1_B64EDGE")
1347 .ok()
1348 .map(|v| v != "0")
1349 });
1350 ENV.unwrap_or(true)
1351}
1352
1353/// How many 64x64 roots the frame edge cut through since the last
1354/// [`take_b64_edge_hits`] (class `gate-blind-to-feature`: both gate films are
1355/// superblock-aligned, so nothing but a synthetic size fires this).
1356static B64_EDGE_HITS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
1357
1358/// The edge 64x64-root count since the last call, and zero it.
1359pub fn take_b64_edge_hits() -> usize {
1360 B64_EDGE_HITS.swap(0, std::sync::atomic::Ordering::Relaxed)
1361}
1362
1363/// Whether the encoder searches loop restoration at all (spec 7.17): one
1364/// Wiener filter per 64x64 luma restoration unit, picked from
1365/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
1366/// test build, like [`lambda_scale`].
1367pub(crate) const RESTORATION: bool = true;
1368
1369/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
1370fn restoration_enabled() -> bool {
1371 match std::env::var("EC_AV1_LR").ok() {
1372 Some(v) if cfg!(test) => v != "0",
1373 _ => crate::speed::at(&crate::speed::RESTORATION),
1374 }
1375}
1376
1377/// libaom's `partition_search_breakout` shape: how many non-zero luma
1378/// coefficients per 256 luma samples a block may code and still be judged
1379/// well enough predicted that the split below it is not worth trying. `0`
1380/// disables the breakout (only the existing all-skip prune applies), which
1381/// is the default until the sweep below justifies otherwise.
1382///
1383/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
1384/// is where this lane's wall would have gone: 1 cuts the three clips'
1385/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
1386/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
1387/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
1388/// encoder's inter quality lives, so `0` ships and the knob stays for a
1389/// future explicit speed preset.
1390pub(crate) const SPLIT_BREAKOUT_COEFFS: usize = 0;
1391
1392/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
1393/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
1394/// out under `threshold * lambda` is not offered the split at all, and a
1395/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
1396/// always, as before this lever.
1397///
1398/// The census is what points here: the split trial runs on nearly every
1399/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
1400/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
1401/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
1402/// points, so the gate has to read the block's own RD cost, not its levels.
1403///
1404/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
1405/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
1406/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
1407/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
1408/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
1409/// the largest threshold whose BD stays inside the +0.3 keep rule on every
1410/// clip.
1411/// RE-SWEPT on lane-av1rejudge at [`LAMBDA_SCALE`] 0.05 with warp on (base
1412/// +16.7/-0.5, +47.0/+19.1, +51.3/-14.3): 0.0625 is +16.9/-0.4, +47.0/+19.1,
1413/// +51.3/-14.2 (the 1080p film 0.2 worse for a finer search) and 0.25 is
1414/// +16.6/-0.6, +46.9/+19.1, +51.6/-14.5 (screen 0.3 worse vs libaom, 3s off
1415/// the screen wall). Neither clears the keep rule; 0.125 stays.
1416pub(crate) const SPLIT_RD_THRESHOLD: f64 = 0.125;
1417
1418/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
1419fn split_rd_threshold() -> f64 {
1420 static ENV: std::sync::LazyLock<Option<f64>> = std::sync::LazyLock::new(|| {
1421 crate::envflags::var("EC_AV1_SPLIT_RD")
1422 .ok()
1423 .and_then(|v| v.parse().ok())
1424 });
1425 ENV.unwrap_or_else(|| crate::speed::at(&crate::speed::SPLIT_RD))
1426}
1427
1428/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
1429/// [`split_rd_threshold`] withholds the split trial.
1430fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
1431 split_rd_breakout_at(split_rd_threshold(), cost, side, lambda)
1432}
1433
1434/// [`split_rd_breakout`] at an explicit threshold -- what the 64x64 root's own
1435/// early-out reads.
1436fn split_rd_breakout_at(t: f64, cost: f64, side: usize, lambda: f64) -> bool {
1437 t > 0.0 && cost < t * lambda * (side * side) as f64
1438}
1439
1440/// The threshold the 64x64 root's early-out uses: [`split_rd_threshold`]
1441/// CLAMPED at the shipped [`SPLIT_RD_THRESHOLD`] (lane-tx64).
1442///
1443/// The 32x32 level is allowed to loosen its breakout with the speed preset
1444/// (`crate::speed::SPLIT_RD` steps to 0.5 at preset 6), but lane-b64 measured
1445/// what that does one size up: at 0.5 a whole superblock is taken at 64x64
1446/// without its four quadrants ever being searched, and film B goes
1447/// +91.5/+53.4 -> +114.6/+71.5. A 64x64 block is four times the area, so the
1448/// same per-pixel threshold withholds four times as much search -- the
1449/// preset's step is priced for the 32 level and does not carry up here.
1450fn b64_breakout_threshold() -> f64 {
1451 split_rd_threshold().min(SPLIT_RD_THRESHOLD)
1452}
1453
1454/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
1455/// build.
1456fn split_breakout_coeffs() -> usize {
1457 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
1458 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
1459 _ => crate::speed::at(&crate::speed::SPLIT_BREAKOUT),
1460 }
1461}
1462
1463/// How often each partition decision was taken since the last
1464/// [`take_partition_hits`], so a gate can report how often a new partition
1465/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
1466/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
1467/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
1468static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
1469 std::sync::atomic::AtomicUsize::new(0),
1470 std::sync::atomic::AtomicUsize::new(0),
1471 std::sync::atomic::AtomicUsize::new(0),
1472 std::sync::atomic::AtomicUsize::new(0),
1473];
1474
1475/// Records one such decision.
1476fn partition_hit(which: usize) {
1477 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1478}
1479
1480/// Takes (and clears) the counts.
1481#[cfg(test)]
1482pub(crate) fn take_partition_hits() -> [usize; 4] {
1483 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
1484}
1485
1486/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
1487/// rate-distortion trials the block search actually runs, by kind, and where
1488/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
1489/// default, and a measurement build rather than a speed one -- the census
1490/// runs the SAD pre-pass the unpruned search otherwise skips.
1491pub fn census_on() -> bool {
1492 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1493 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
1494}
1495
1496/// What each [`CENSUS`] counter counts.
1497pub const CENSUS_KINDS: [&str; 11] = [
1498 "intra blocks searched (key frame + inter leaves)",
1499 "intra luma mode trials",
1500 "chroma searches",
1501 "chroma mode trials (each = 2 plane trials)",
1502 "tx-depth trials (transform units, depth >= 1)",
1503 "inter 32x32 blocks searched",
1504 "inter block intra-mode trials",
1505 "inter mv candidates (each = 3 mc trials)",
1506 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
1507 " of those, intra won",
1508 " of those, the NEARESTMV trial coded no residual",
1509];
1510
1511/// The census counters themselves, indexed by [`CENSUS_KINDS`].
1512static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
1513 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
1514
1515/// Where the RD winner sat in the SAD ranking, for the luma intra search and
1516/// the chroma mode search -- what says whether a top-N prune would have kept
1517/// the block the search actually chose.
1518static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
1519 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
1520static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
1521 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
1522
1523fn census_add(kind: usize, n: usize) {
1524 if census_on() {
1525 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
1526 }
1527}
1528
1529/// Reads (and clears) the census, so a driver can attribute it to its own encode.
1530pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
1531 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
1532 (
1533 std::array::from_fn(|i| take(&CENSUS[i])),
1534 std::array::from_fn(|i| take(&LUMA_RANK[i])),
1535 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
1536 )
1537}
1538
1539/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
1540/// first -- the census's one shared rule, so the luma and chroma histograms
1541/// mean the same thing.
1542fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
1543 scored
1544 .iter()
1545 .filter(|&&(score, mode)| {
1546 mode != winner
1547 && score
1548 < scored
1549 .iter()
1550 .find(|&&(_, m)| m == winner)
1551 .map_or(f64::INFINITY, |&(s, _)| s)
1552 })
1553 .count()
1554}
1555
1556/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
1557/// four cost less. Set from the measurement in the lane report.
1558const SPLIT_BLOCKS: bool = true;
1559
1560/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
1561/// by calling [`encode_key_frame_inner`] both ways.
1562pub(crate) fn split_blocks() -> bool {
1563 SPLIT_BLOCKS
1564}
1565
1566/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
1567/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
1568/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
1569/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
1570/// stream's decode output actually carries 10-bit precision instead of
1571/// silently losing its low 2 bits). The encoder only ever produces values in
1572/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
1573/// decision); `Plane::source` narrows right back to `u8` at its two
1574/// construction sites, a lossless round trip for that range.
1575#[derive(Clone, Debug, PartialEq, Eq)]
1576pub struct Picture {
1577 /// The picture's width in luma samples.
1578 pub width: usize,
1579 /// Its height in luma samples.
1580 pub height: usize,
1581 /// The luma plane, `width * height` samples in raster order.
1582 pub y: Vec<u16>,
1583 /// The U plane: half the width, and the frame's own chroma height -- a
1584 /// quarter of the luma samples at 4:2:0, half at 4:2:2, all of them at
1585 /// 4:4:4. A consumer that only knows the luma size reads the chroma
1586 /// format off this sample count (see `decode::ref_chroma_shape`).
1587 pub u: Vec<u16>,
1588 /// The V plane, the same shape as U.
1589 pub v: Vec<u16>,
1590}
1591
1592impl Picture {
1593 /// A mid-grey picture of the given size.
1594 #[must_use]
1595 pub fn grey(width: usize, height: usize) -> Self {
1596 Self {
1597 width,
1598 height,
1599 y: vec![128; width * height],
1600 u: vec![128; width * height / 4],
1601 v: vec![128; width * height / 4],
1602 }
1603 }
1604
1605 pub(crate) fn check(&self) -> Result<()> {
1606 if self.width == 0
1607 || !self.width.is_multiple_of(BLOCK)
1608 || !self.height.is_multiple_of(BLOCK)
1609 || !self.height.is_multiple_of(BLOCK)
1610 {
1611 return Err(Error::unsupported(
1612 "AV1 encode",
1613 "the picture must be a whole number of 32x32 blocks in each direction",
1614 ));
1615 }
1616 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1617 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1618 return Err(Error::unsupported(
1619 "AV1 encode",
1620 "each plane must carry one sample per position at 4:2:0",
1621 ));
1622 }
1623 Ok(())
1624 }
1625
1626 /// What the public entry points require of the picture they are handed,
1627 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
1628 /// needs a whole chroma sample per two luma ones) and one sample per
1629 /// position on each plane.
1630 pub(crate) fn check_even(&self) -> Result<()> {
1631 if self.width == 0
1632 || self.height == 0
1633 || !self.width.is_multiple_of(2)
1634 || !self.height.is_multiple_of(2)
1635 {
1636 return Err(Error::unsupported(
1637 "AV1 encode",
1638 "the picture's width and height must each be even and nonzero",
1639 ));
1640 }
1641 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
1642 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
1643 return Err(Error::unsupported(
1644 "AV1 encode",
1645 "each plane must carry one sample per position at 4:2:0",
1646 ));
1647 }
1648 Ok(())
1649 }
1650
1651 /// This picture, padded by edge replication to the next whole number of
1652 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
1653 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
1654 /// sequence (what the inter tile writer's partition needs on top of
1655 /// that). Identity (a plain clone, not a copy through the replication
1656 /// loop) when the picture is already that size — the multiple-of-32 (or
1657 /// -64) fast path is unchanged.
1658 pub(crate) fn padded_to(&self, align: usize) -> Picture {
1659 let padded_width = self.width.next_multiple_of(align);
1660 let padded_height = self.height.next_multiple_of(align);
1661 if padded_width == self.width && padded_height == self.height {
1662 return self.clone();
1663 }
1664 Picture {
1665 width: padded_width,
1666 height: padded_height,
1667 y: pad_plane(
1668 &self.y,
1669 self.width,
1670 self.height,
1671 padded_width,
1672 padded_height,
1673 ),
1674 u: pad_plane(
1675 &self.u,
1676 self.width / 2,
1677 self.height / 2,
1678 padded_width / 2,
1679 padded_height / 2,
1680 ),
1681 v: pad_plane(
1682 &self.v,
1683 self.width / 2,
1684 self.height / 2,
1685 padded_width / 2,
1686 padded_height / 2,
1687 ),
1688 }
1689 }
1690}
1691
1692/// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8`
1693/// (8-bit only, unchanged this round -- widening the encoder is out of this
1694/// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that
1695/// lets it keep calling [`crate::intra::predict`] now that shape is `u16`
1696/// in and out. A block-sized round-trip through `u16` is exact for 8-bit
1697/// content (every value fits both ways), so this changes no encoder output.
1698#[allow(clippy::too_many_arguments)]
1699fn intra_predict_u8(
1700 mode: u8,
1701 angle_delta: i32,
1702 above: Option<&[u8]>,
1703 left: Option<&[u8]>,
1704 corner: Option<u8>,
1705 bw: usize,
1706 bh: usize,
1707 enable_edge_filter: bool,
1708 smooth_neighbor: bool,
1709 dst: &mut [u8],
1710 fctx: &crate::decode::FrameCtx,
1711) {
1712 // Three heap allocations per call became three stack buffers: this runs
1713 // once per mode per trial, and an edge is at most `bw + bh` samples while
1714 // a block is at most `SUPERBLOCK * SUPERBLOCK` (lane-i64: the key frame's
1715 // 64x64 intra root predicts through here too, and reads up to `2 * bw`
1716 // samples above).
1717 let mut above_buf = [0u16; 2 * SUPERBLOCK];
1718 let mut left_buf = [0u16; 2 * SUPERBLOCK];
1719 // lane-av1speed2: a `BLOCK * BLOCK` scratch is 2 KB zeroed on every mode
1720 // trial of every block, and a 4x4 block writes 32 bytes of it. The
1721 // predictor fills every sample it is handed, so the zeros are dead
1722 // either way -- size the scratch to the block instead of to the largest
1723 // block there is.
1724
1725 let widen = |src: &[u8], buf: &mut [u16; 2 * SUPERBLOCK]| {
1726 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1727 *d = u16::from(v);
1728 }
1729 };
1730 if let Some(s) = above {
1731 widen(s, &mut above_buf);
1732 }
1733 if let Some(s) = left {
1734 widen(s, &mut left_buf);
1735 }
1736 let above16 = above.map(|s| &above_buf[..s.len()]);
1737 let left16 = left.map(|s| &left_buf[..s.len()]);
1738 let mut run = |dst16: &mut [u16]| {
1739 crate::intra::predict(
1740 mode,
1741 angle_delta,
1742 above16,
1743 left16,
1744 corner.map(u16::from),
1745 bw,
1746 bh,
1747 enable_edge_filter,
1748 smooth_neighbor,
1749 dst16,
1750 fctx,
1751 );
1752 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
1753 *d = s as u8;
1754 }
1755 };
1756 let n = bw * bh;
1757 if n <= 64 {
1758 run(&mut [0u16; 64][..n]);
1759 } else if n <= 256 {
1760 run(&mut [0u16; 256][..n]);
1761 } else if n <= BLOCK * BLOCK {
1762 run(&mut [0u16; BLOCK * BLOCK][..n]);
1763 } else {
1764 run(&mut [0u16; SUPERBLOCK * SUPERBLOCK][..n]);
1765 }
1766}
1767
1768/// [`intra_predict_u8`] for recursive filter intra (spec 7.11.2.3): the same
1769/// `u8` box around [`crate::intra::predict_filter_intra`], whose `mode` is one
1770/// of the five `FILTER_INTRA_MODES` rather than an ordinary intra mode.
1771fn filter_intra_predict_u8(
1772 mode: usize,
1773 above: Option<&[u8]>,
1774 left: Option<&[u8]>,
1775 corner: Option<u8>,
1776 side: usize,
1777 dst: &mut [u8],
1778 fctx: &crate::decode::FrameCtx,
1779) {
1780 let mut above_buf = [0u16; 2 * BLOCK];
1781 let mut left_buf = [0u16; 2 * BLOCK];
1782 let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
1783 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
1784 *d = u16::from(v);
1785 }
1786 };
1787 if let Some(a) = above {
1788 widen(a, &mut above_buf);
1789 }
1790 if let Some(l) = left {
1791 widen(l, &mut left_buf);
1792 }
1793 let mut dst16 = [0u16; BLOCK * BLOCK];
1794 let n = side * side;
1795 crate::intra::predict_filter_intra(
1796 mode,
1797 above.map(|a| &above_buf[..a.len()]),
1798 left.map(|l| &left_buf[..l.len()]),
1799 corner.map(u16::from),
1800 side,
1801 side,
1802 &mut dst16[..n],
1803 fctx,
1804 );
1805 for (d, &v) in dst.iter_mut().zip(dst16[..n].iter()) {
1806 *d = v as u8;
1807 }
1808}
1809
1810/// Pads one plane to `(padded_width, padded_height)` by repeating its last
1811/// row and column, so the block coder always sees a whole number of blocks.
1812/// [`crop_plane`] undoes this on the way back out.
1813fn pad_plane<T: Copy + Default>(
1814 source: &[T],
1815 width: usize,
1816 height: usize,
1817 padded_width: usize,
1818 padded_height: usize,
1819) -> Vec<T> {
1820 let mut out = vec![T::default(); padded_width * padded_height];
1821 for row in 0..padded_height {
1822 let src = source[row.min(height - 1) * width..][..width].as_ref();
1823 let dst = &mut out[row * padded_width..][..padded_width];
1824 dst[..width].copy_from_slice(src);
1825 dst[width..].fill(src[width - 1]);
1826 }
1827 out
1828}
1829
1830/// The top-left `width` x `height` region of a plane that is `padded_width`
1831/// wide, which is the render-size crop [`Picture::padded`]'s replication
1832/// exists to let a decoder undo.
1833fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
1834 let mut out = Vec::with_capacity(width * height);
1835 for row in 0..height {
1836 out.extend_from_slice(&source[row * padded_width..][..width]);
1837 }
1838 out
1839}
1840
1841/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
1842/// region a decoder produces, which is the public contract for what a caller
1843/// sees back — the padded planes the encoder coded against never leave this
1844/// module. Identity when the reconstruction is already that size.
1845///
1846/// The chroma extent is `ROUND_POWER_OF_TWO(size, 1)` -- `(size + 1) / 2`,
1847/// libaom's `av1_common_plane_width` (`av1/common/av1_common_int.h`) -- so an
1848/// ODD declared luma size keeps the chroma column a decoder keeps (a 65-wide
1849/// 4:2:0 frame has 33, not 32). Every even size is unaffected: `(2k+1)/2 ==
1850/// k`, so this is a no-op for every caller `encode_key_frame`'s even-size
1851/// check lets through.
1852pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
1853 let reconstruction = &encoded.reconstruction;
1854 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
1855 let cropped = if reconstruction.width == width && reconstruction.height == height {
1856 reconstruction.clone()
1857 } else {
1858 Picture {
1859 width,
1860 height,
1861 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
1862 u: crop_plane(&reconstruction.u, reconstruction.width / 2, cw, ch),
1863 v: crop_plane(&reconstruction.v, reconstruction.width / 2, cw, ch),
1864 }
1865 };
1866 Encoded {
1867 stream: encoded.stream.clone(),
1868 modes: encoded.modes.clone(),
1869 inter_block_share: encoded.inter_block_share,
1870 reconstruction: cropped,
1871 tile: encoded.tile.clone(),
1872 mi_cols: encoded.mi_cols,
1873 mi_rows: encoded.mi_rows,
1874 base_q_idx: encoded.base_q_idx,
1875 tx_select: encoded.tx_select,
1876 switchable_motion_mode: encoded.switchable_motion_mode,
1877 screen: encoded.screen,
1878 reduced_tx_set: encoded.reduced_tx_set,
1879 start_cdfs: encoded.start_cdfs.clone(),
1880 next_cdfs: encoded.next_cdfs.clone(),
1881 loop_filter: encoded.loop_filter,
1882 loop_restoration: encoded.loop_restoration,
1883 allow_intrabc: encoded.allow_intrabc,
1884 delta: encoded.delta,
1885 cdef: encoded.cdef,
1886 }
1887}
1888
1889/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
1890/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
1891#[derive(Clone)]
1892pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
1893
1894impl std::fmt::Debug for CdfSnapshot {
1895 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1896 f.write_str("CdfSnapshot")
1897 }
1898}
1899
1900/// What one call to [`encode_key_frame`] produced.
1901#[derive(Clone, Debug)]
1902pub struct Encoded {
1903 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
1904 /// OBU carrying one tile.
1905 pub stream: Vec<u8>,
1906 /// What a decoder will produce from `stream` — the encoder's own
1907 /// reconstruction, which its prediction was built on.
1908 pub reconstruction: Picture,
1909 /// The luma intra mode each block was coded under, in the order the blocks
1910 /// are coded — raster order among the quadrants of each superblock, and
1911 /// among the four 16x16 blocks of a quadrant that was split.
1912 pub modes: Vec<u8>,
1913 /// The fraction of this frame's 32x32 blocks that were coded inter (any
1914 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
1915 /// for a key frame, which has no such choice — so a caller can tell a
1916 /// frame with no motion worth coding from one that never got the chance.
1917 pub inter_block_share: f64,
1918 /// The tile payload alone, undecorated by any OBU framing, and the frame
1919 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
1920 /// `crate::decode`'s tests are the only reader; a real decoder gets these
1921 /// off the wire by parsing `stream`'s OBUs instead.
1922 pub(crate) tile: Vec<u8>,
1923 pub(crate) mi_cols: u32,
1924 pub(crate) mi_rows: u32,
1925 pub(crate) base_q_idx: u8,
1926 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
1927 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
1928 /// and reading it off `stream`'s header is what `decode_stream` does. A
1929 /// test that decodes `tile` directly must pass this one along, or it reads
1930 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
1931 /// block.
1932 pub(crate) tx_select: bool,
1933 /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the
1934 /// bit that makes every eligible single-reference inter block carry a
1935 /// `motion_mode` symbol. Same contract as `tx_select` above: a test
1936 /// decoding `tile` directly must pass it along or it desyncs at the
1937 /// first eligible block.
1938 pub(crate) switchable_motion_mode: bool,
1939 /// The CDF state this frame's tile writer started from -- the defaults
1940 /// for a key frame and for the first inter frame, and the previous
1941 /// frame's stored tables after that. A test that decodes `tile` directly
1942 /// must feed the decoder this, exactly as `decode_stream` feeds it what
1943 /// the frame's `primary_ref_frame` slot holds (same class as
1944 /// `tx_select`: a header bit a raw tile decode cannot guess).
1945 ///
1946 /// BOXED (lane-av1stacksweep), and this is the whole point: the payload is
1947 /// a 15232-byte `Cdfs`, and `Encoded` is returned BY VALUE from a
1948 /// four-deep `Result<Encoded>` constructor chain, so an inline copy of two
1949 /// of them made `Encoded` 30728 bytes -- 99.2% of this struct was these
1950 /// two fields, and it was the largest by-value return in the crate.
1951 /// `DpbSlot::cdfs` was boxed for the same reason in lane-av1enchang; this
1952 /// is the other copy of the same table. The VALUES are untouched, so the
1953 /// bitstream is byte-identical; `crate::stack_budget` gates the result.
1954 pub(crate) start_cdfs: Box<CdfSnapshot>,
1955 /// What this frame stores into the slots it refreshes (spec 7.20,
1956 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
1957 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
1958 /// started from when it is on.
1959 pub(crate) next_cdfs: Box<CdfSnapshot>,
1960 /// This frame header's chosen deblocking parameters
1961 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
1962 /// picture the decoder produces UNDER them, so a test that decodes
1963 /// `tile` directly must pass these along, exactly as it must `tx_select`
1964 /// (class: test asserts against a stale header).
1965 pub(crate) loop_filter: LoopFilterParams,
1966 /// This frame header's chosen CDEF parameters, threaded for the same
1967 /// reason as `loop_filter`.
1968 pub(crate) cdef: CdefParams,
1969 /// This frame header's `allow_screen_content_tools`
1970 /// ([`screen_content`]) -- every intra block of the tile carries the two
1971 /// palette-mode symbols under it, so a raw tile decode that guessed
1972 /// `false` would desync at the first block (same class as `tx_select`).
1973 pub(crate) screen: bool,
1974 /// This frame header's own `reduced_tx_set` (spec 5.9.2) -- the bit that
1975 /// picks the inter `tx_type` alphabets AND, on an inter block, the
1976 /// allowance the chroma transform's inherited type reduces against
1977 /// ([`crate::decode::reduce_inherited_chroma_tx_type`]). A raw tile
1978 /// decode that guesses `true` here mis-derives every inherited chroma
1979 /// type on a `reduced_tx_set = 0` frame (lane-intertx; same class as
1980 /// `tx_select`/`screen` above).
1981 pub(crate) reduced_tx_set: bool,
1982 /// This frame header's chosen loop restoration parameters, threaded for
1983 /// the same reason as `loop_filter` -- and doubly so: the per-unit
1984 /// filters themselves are coded in `tile`, so a decode of it under a
1985 /// stale `RESTORE_NONE` header desyncs at the first superblock.
1986 pub(crate) loop_restoration: LoopRestorationParams,
1987 /// This frame header's `allow_intrabc` -- every intra block of the tile
1988 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
1989 /// guessed `false` would desync at the first block (same class as
1990 /// `screen`/`tx_select`).
1991 pub(crate) allow_intrabc: bool,
1992 /// This frame header's `delta_q_params`/`delta_lf_params` (spec
1993 /// 5.9.17/5.9.18) -- with `delta_q_present` every superblock's first
1994 /// coded block carries a `delta_qindex` symbol group, so a raw tile
1995 /// decode that guessed the defaults desyncs at the first superblock
1996 /// (same class as `screen`/`tx_select`).
1997 pub(crate) delta: ec_av1_syntax::DeltaParams,
1998}
1999
2000thread_local! {
2001 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
2002 /// for on the last key frame encoded on this thread -- read by the gates,
2003 /// which print it beside the block counts (class `gate-blind-to-feature`).
2004 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
2005}
2006
2007/// [`IBC_SHARE`] for the last key frame encoded on this thread.
2008#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2009pub(crate) fn intrabc_source_share() -> f64 {
2010 IBC_SHARE.with(std::cell::Cell::get)
2011}
2012
2013thread_local! {
2014 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
2015 /// header offers the per-frame `allow_screen_content_tools` bit at all.
2016 /// Armed once by the key frame ([`encode_key_frame_inner`], from
2017 /// [`screen_content`]) and read by every header builder after it, so that
2018 /// the inter frames of a screen sequence lay their headers out the same
2019 /// way the sequence header the key frame wrote says they do -- a per-call
2020 /// parameter would have to thread through `inter_frame_headers`' four
2021 /// public entry points and every hand-built-stream test that calls them.
2022 /// A sequence with no screen content leaves this false and writes exactly
2023 /// the bits it wrote before this lane.
2024 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2025}
2026
2027thread_local! {
2028 /// Overrides [`screen_content`] for the calling thread, which is what the
2029 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
2030 /// codes every block losslessly, so both arms of a mode ablation reach
2031 /// infinite PSNR and the ablation measures nothing at all (the
2032 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
2033 /// variable cannot do this -- the tests run in one process, in parallel.
2034 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
2035}
2036
2037thread_local! {
2038 /// What the last [`encode_sequence_with_ctx`] call on this thread coded
2039 /// under, AFTER the content gate: the pyramid, or `None` for a stream
2040 /// that stayed flat. Read by the BD gates, which print the requested and
2041 /// the effective pyramid side by side -- a screen clip requests one and
2042 /// codes flat, and that difference is the gate (class
2043 /// `gate-blind-to-feature`).
2044 static LAST_SEQ_PYRAMID: std::cell::Cell<Option<crate::encoder::Pyramid>> =
2045 const { std::cell::Cell::new(None) };
2046}
2047
2048/// The pyramid the last sequence coded on this thread was EFFECTIVELY under.
2049#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2050pub(crate) fn last_sequence_pyramid() -> Option<crate::encoder::Pyramid> {
2051 LAST_SEQ_PYRAMID.with(std::cell::Cell::get)
2052}
2053
2054#[cfg(test)]
2055pub(crate) fn force_screen(value: Option<bool>) {
2056 SCREEN_FORCE.with(|c| c.set(value));
2057}
2058
2059// lane-fintra: [`force_screen`] for the filter-intra candidate, so a MODE
2060// ablation can measure the mode search alone. Setting it also clears the
2061// sequence header's own `enable_filter_intra` bit, so the stream the arm
2062// writes is exactly the one this encoder wrote before the lane.
2063#[cfg(test)]
2064thread_local! {
2065 static FILTER_INTRA_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
2066}
2067
2068#[cfg(test)]
2069pub(crate) fn force_filter_intra(value: Option<bool>) {
2070 FILTER_INTRA_FORCE.with(|c| c.set(value));
2071}
2072
2073pub(crate) fn arm_seq_screen(on: bool) {
2074 SEQ_SCREEN.with(|c| c.set(on));
2075}
2076
2077fn seq_screen() -> bool {
2078 SEQ_SCREEN.with(std::cell::Cell::get)
2079}
2080
2081/// How many distinct colours a 16x16 luma block may hold and still count as
2082/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
2083/// `av1_set_screen_content_options` bound is 4, which separates nothing on
2084/// lossily coded (so noisy) material: `probe_screen_detect` sweeps N against
2085/// the variance floor below on the five gate clips at BOTH the native crop
2086/// and the 640x384 gate's scale, and 16 colours / var > 16 / an eighth of
2087/// the frame is the widest-margin split of those ten rows -- every
2088/// non-screen row at most 9.6% of blocks (bars 3.6/2.3 native, 9.6/9.5
2089/// scaled; film A 0.6/0.3, film B 0.5/0.9) against the OBS capture's 23.6%
2090/// native and 17.9% scaled.
2091fn screen_colors() -> usize {
2092 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2093 *N.get_or_init(|| {
2094 std::env::var("EC_AV1_SCREEN_COLORS")
2095 .ok()
2096 .and_then(|v| v.parse().ok())
2097 .unwrap_or(16)
2098 })
2099}
2100
2101/// The reciprocal of the frame area those blocks must cover, in tenths --
2102/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is a tenth;
2103/// 8 (an eighth) is the midpoint of the two populations
2104/// `probe_screen_detect` measures at the colour bound and variance floor
2105/// around it. `EC_AV1_SCREEN_PCT`.
2106fn screen_pct() -> usize {
2107 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2108 *N.get_or_init(|| {
2109 std::env::var("EC_AV1_SCREEN_PCT")
2110 .ok()
2111 .and_then(|v| v.parse().ok())
2112 .unwrap_or(10)
2113 })
2114}
2115
2116/// The per-pixel variance a few-colour block must clear before it counts as
2117/// screen content, `EC_AV1_SCREEN_VAR`. libaom keeps the same term (its
2118/// `counts_2`/`var_thresh` in `av1_set_screen_content_options`); without it
2119/// a smooth dark film frame is all few-colour blocks and reads as a desktop
2120/// capture -- which is exactly what this detector did until 2026-09-07, when
2121/// it called BOTH real films screen content on 48/48 frames, priced every
2122/// coefficient against the default CDFs and ran the palette search over
2123/// film. `probe_screen_detect`: at 16 colours the floor takes both films
2124/// from 46.2/52.5% of blocks to 0.6/0.5% and the capture only from 29.9% to
2125/// 23.6%.
2126fn screen_var() -> u64 {
2127 static N: std::sync::OnceLock<u64> = std::sync::OnceLock::new();
2128 *N.get_or_init(|| {
2129 std::env::var("EC_AV1_SCREEN_VAR")
2130 .ok()
2131 .and_then(|v| v.parse().ok())
2132 .unwrap_or(16)
2133 })
2134}
2135
2136/// How many frames [`screen_content`] said yes/no to, so a gate can print
2137/// whether the detector fired at all (class `gate-blind-to-feature`).
2138pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
2139 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
2140
2141/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
2142/// the distinct colours of every 16x16 block and turn the screen-content
2143/// tools on when the blocks holding between 2 and [`screen_colors`] of them
2144/// AND clearing [`screen_var`] cover more than a [`screen_pct`]th of the
2145/// frame. `width` is the plane's
2146/// stride, `true_*` the frame's real (decodable) extent.
2147fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
2148 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
2149 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2150 return forced;
2151 }
2152 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
2153 let on = v != "0";
2154 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2155 return on;
2156 }
2157 let (blk, limit, floor) = (16usize, screen_colors(), screen_var());
2158 let mut counted = 0usize;
2159 for by in (0..true_height).step_by(blk) {
2160 for bx in (0..true_width).step_by(blk) {
2161 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
2162 let mut seen = [false; 256];
2163 let (mut colors, mut sum, mut sq) = (0usize, 0u64, 0u64);
2164 for row in 0..h {
2165 for col in 0..w {
2166 let v = y[(by + row) * width + bx + col];
2167 sum += u64::from(v);
2168 sq += u64::from(v) * u64::from(v);
2169 if !seen[usize::from(v)] {
2170 seen[usize::from(v)] = true;
2171 colors += 1;
2172 }
2173 }
2174 }
2175 // Per-pixel variance over the block's real (edge-clipped) extent.
2176 let n = (h * w) as u64;
2177 let var = (sq - sum * sum / n) / n;
2178 if colors > 1 && colors <= limit && var > floor {
2179 counted += 1;
2180 }
2181 }
2182 }
2183 let on = counted * blk * blk * screen_pct() > true_width * true_height;
2184 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2185 on
2186}
2187
2188/// Whether this SOURCE picture reads as screen content, for a caller that has
2189/// to decide something BEFORE the frame is coded: [`crate::encoder::Av1Encoder`]
2190/// gates its coding pyramid on this (a desktop capture keeps the flat
2191/// one-in-one-out structure the BD gate measured it on, camera material takes
2192/// the mini-GOP). The key frame runs the same detector again when it builds
2193/// its header -- that is the run the [`SCREEN_FRAMES`] histogram is meant to
2194/// count, so this probe undoes its own tick and leaves the gate prints
2195/// reading one detection per coded frame.
2196pub(crate) fn picture_is_screen(picture: &Picture) -> bool {
2197 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
2198 let on = screen_content(&y, picture.width, picture.width, picture.height);
2199 SCREEN_FRAMES[usize::from(on)].fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
2200 on
2201}
2202
2203/// The sequence and frame headers a picture of this size is coded under: one
2204/// tile, one transform size per block, no in-loop filter parameters yet
2205/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
2206/// CDEF strengths in once the tile is coded), no CDF adaptation
2207/// and no tool the tile writer does not code.
2208///
2209/// # Errors
2210/// Returns an error when the picture is larger than the 16-bit frame size the
2211/// sequence header carries.
2212pub fn key_frame_headers(
2213 width: usize,
2214 height: usize,
2215 base_q_idx: u8,
2216) -> Result<(SequenceHeader, FrameHeader)> {
2217 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
2218}
2219
2220/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
2221/// studio (limited) range: what this crate's sequence header carried before
2222/// [`crate::encoder`]'s facade could configure it, and what
2223/// [`key_frame_headers`] still asks for.
2224fn unspecified_color_config() -> ColorConfig {
2225 ColorConfig {
2226 bit_depth: 8,
2227 mono_chrome: false,
2228 num_planes: 3,
2229 color_primaries: 2,
2230 transfer_characteristics: 2,
2231 matrix_coefficients: 2,
2232 color_range: false,
2233 subsampling_x: 1,
2234 subsampling_y: 1,
2235 chroma_sample_position: ChromaSamplePosition::Unknown,
2236 separate_uv_delta_q: false,
2237 }
2238}
2239
2240/// [`key_frame_headers`] with the sequence header's colour config named
2241/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
2242/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
2243/// which is all a player picks a colour transform from and which
2244/// [`crate::encoder::Colour`] is the facade's own name for.
2245///
2246/// `color_config` also carries the chroma shape, and that is what a coverage
2247/// witness needs: nothing in this crate's ENCODER codes a shape other than
2248/// 4:2:0, but a sequence header can still be written at any
2249/// `subsampling_x`/`subsampling_y` the spec allows, which is how the 4:4:0
2250/// header witness is built. It builds HEADERS only -- pair the pair it
2251/// returns with a tile from [`encode_key_frame`] (4:2:0) or
2252/// [`encode_key_frame_at_size`].
2253///
2254/// # Errors
2255/// The same as [`key_frame_headers`].
2256pub fn key_frame_headers_colour(
2257 width: usize,
2258 height: usize,
2259 base_q_idx: u8,
2260 color_config: ColorConfig,
2261) -> Result<(SequenceHeader, FrameHeader)> {
2262 let bits = |n: usize| -> Result<u32> {
2263 let n = u32::try_from(n).map_err(|_| too_large())?;
2264 if n == 0 || n > 1 << 16 {
2265 return Err(too_large());
2266 }
2267 Ok((32 - (n - 1).leading_zeros()).max(1))
2268 };
2269 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
2270 let (w, h) = (width as u32, height as u32);
2271 let seq = SequenceHeader {
2272 seq_profile: 0,
2273 operating_points: vec![OperatingPoint {
2274 seq_level_idx: 8,
2275 ..OperatingPoint::default()
2276 }],
2277 frame_width_bits,
2278 frame_height_bits,
2279 max_frame_width: w,
2280 max_frame_height: h,
2281 use_128x128_superblock: sb128_on(),
2282 // lane-fintra: the encoder's intra search offers the five recursive
2283 // filter-intra modes on eligible blocks, so the sequence bit is set
2284 // whenever that search is on (`EC_AV1_FILTER_INTRA=0` switches both
2285 // off and restores the streams this encoder wrote before the lane).
2286 enable_filter_intra: filter_intra_on(),
2287 enable_intra_edge_filter: false,
2288 enable_order_hint: true,
2289 order_hint_bits: 7,
2290 enable_superres: false,
2291 // spec 5.9.19: with the sequence bit set every frame header carries
2292 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
2293 // pair for the whole frame, chosen by `crate::filter_search` -- so no
2294 // `cdef_idx` literal is coded in the tile and a frame that wants no
2295 // CDEF simply carries zero strengths.
2296 enable_cdef: true,
2297 enable_restoration: true,
2298 // SELECT (2) when this sequence's key frame detected screen content
2299 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
2300 // is then coded in every frame header, and only the frames that want
2301 // the palette syntax set it. 0 -- the forced-off form, no bit at all
2302 // -- otherwise, which is what every non-screen stream this encoder
2303 // writes still carries.
2304 seq_force_screen_content_tools: if seq_screen() {
2305 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
2306 } else {
2307 0
2308 },
2309 seq_force_integer_mv: 0,
2310 color_config,
2311 still_picture: false,
2312 reduced_still_picture_header: false,
2313 timing_info: None,
2314 decoder_model_info: None,
2315 initial_display_delay_present_flag: false,
2316 operating_point: 0,
2317 operating_point_idc: 0,
2318 frame_id_numbers_present_flag: false,
2319 delta_frame_id_length: 0,
2320 additional_frame_id_length: 0,
2321 enable_interintra_compound: false,
2322 enable_masked_compound: false,
2323 // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
2324 // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
2325 // header is byte-identical to the streams before this lane.
2326 enable_warped_motion: warp_on(),
2327 enable_dual_filter: false,
2328 enable_jnt_comp: false,
2329 enable_ref_frame_mvs: false,
2330 film_grain_params_present: false,
2331 };
2332 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
2333 // own (true, unpadded) width and height, not from any block-grid
2334 // alignment — a decoder derives these straight from `frame_width`/
2335 // `frame_height` below, so this must match it exactly.
2336 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
2337 let header = FrameHeader {
2338 frame_type: FrameType::Key,
2339 frame_is_intra: true,
2340 show_frame: true,
2341 error_resilient_mode: true,
2342 // The tile writer keeps the same CDF state the decoder does and
2343 // updates it in the same order, so the frame lets the decoder adapt.
2344 disable_cdf_update: false,
2345 // Nothing reads the state this frame leaves behind: a key frame always
2346 // starts from the defaults, and this encoder emits one frame.
2347 disable_frame_end_update_cdf: true,
2348 force_integer_mv: true,
2349 refresh_frame_flags: 0xFF,
2350 primary_ref_frame: PRIMARY_REF_NONE,
2351 frame_width: w,
2352 frame_height: h,
2353 upscaled_width: w,
2354 render_width: w,
2355 render_height: h,
2356 mi_cols,
2357 mi_rows,
2358 tile_info: TileInfo {
2359 uniform_spacing: true,
2360 cols: 1,
2361 rows: 1,
2362 mi_col_starts: vec![0, mi_cols],
2363 mi_row_starts: vec![0, mi_rows],
2364 tile_size_bytes: 1,
2365 ..TileInfo::default()
2366 },
2367 quantization: QuantizationParams {
2368 base_q_idx,
2369 ..QuantizationParams::default()
2370 },
2371 tx_mode: TxMode::Largest,
2372 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
2373 // intra transform below 32x32, not only 16x16 -- the set this crate
2374 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
2375 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
2376 // so a decoder honouring the header picks the same CDF the writer
2377 // used only if this is set here too, not only on the inter variant
2378 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
2379 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
2380 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
2381 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
2382 // the arithmetic coder's `rng` register from the very first 8x8-leaf
2383 // luma transform onward with no symbol value ever differing.
2384 reduced_tx_set: true,
2385 ..FrameHeader::default()
2386 };
2387 Ok((seq, header))
2388}
2389
2390/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
2391/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
2392/// 1 still holds the key frame however long the GOP runs.
2393pub const GOLDEN_SLOT: u8 = 1;
2394
2395/// lane-refs: the frame-level `interpolation_filter` (spec 6.8.9) every inter
2396/// frame this encoder writes carries. `EC_AV1_INTERP=smooth|sharp` codes the
2397/// EIGHTTAP_SMOOTH / EIGHTTAP_SHARP kernel instead of the default REGULAR --
2398/// one filter for the whole frame, which is what libaom does on this content
2399/// too (`lanes/obmc3.report.md` read `switchable_interp 0/0` out of its own
2400/// stream, so a per-BLOCK filter search has no bits to win). The kernel
2401/// reaches the search, the trials and the recon through
2402/// `FrameCtx::interp_filter`, so the stream a decoder reads and the
2403/// prediction the search priced are the same one.
2404/// A PROCESS-GLOBAL [`frame_interp_filter`] override that wins over the
2405/// environment (`u8::MAX` = unset), the shape [`set_inter_tx_search`] has:
2406/// the witness that has to see a non-REGULAR kernel coded and decoded turns
2407/// it on through this while holding [`crate::speed::knob_write`].
2408static INTERP_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
2409
2410/// Sets [`INTERP_OVERRIDE`]; `None` clears it.
2411#[allow(dead_code)] // set only from the `#[cfg(test)]` gates
2412pub(crate) fn set_frame_interp(filter: Option<ec_av1_syntax::InterpolationFilter>) {
2413 INTERP_OVERRIDE.store(
2414 filter.map_or(u8::MAX, |f| f as u8),
2415 std::sync::atomic::Ordering::Relaxed,
2416 );
2417}
2418
2419fn frame_interp_filter() -> ec_av1_syntax::InterpolationFilter {
2420 use ec_av1_syntax::InterpolationFilter as F;
2421 match INTERP_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
2422 0 => return F::Eighttap,
2423 1 => return F::EighttapSmooth,
2424 2 => return F::EighttapSharp,
2425 _ => {}
2426 }
2427 static ENV: std::sync::LazyLock<Option<F>> = std::sync::LazyLock::new(|| {
2428 crate::envflags::var("EC_AV1_INTERP")
2429 .ok()
2430 .map(|v| match v.as_str() {
2431 "smooth" => F::EighttapSmooth,
2432 "sharp" => F::EighttapSharp,
2433 _ => F::Eighttap,
2434 })
2435 });
2436 ENV.unwrap_or(F::Eighttap)
2437}
2438
2439/// The frame header for a shown inter frame that predicts from the single
2440/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
2441/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
2442/// reused verbatim: an inter frame never changes the sequence.
2443///
2444/// # Errors
2445/// Returns an error under the same conditions as [`key_frame_headers`].
2446pub fn inter_frame_headers(
2447 width: usize,
2448 height: usize,
2449 base_q_idx: u8,
2450 order_hint: u32,
2451 last_slot: u8,
2452) -> Result<(SequenceHeader, FrameHeader)> {
2453 inter_frame_headers_slots(
2454 width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot,
2455 )
2456}
2457
2458/// [`inter_frame_headers`] with the three slots named apart: the one read as
2459/// `LAST_FRAME`, the one this frame refreshes, and the one read as
2460/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
2461/// so that the frame two back is still intact in the slot this one is about
2462/// to overwrite -- read before write, spec 7.20's decode order.
2463///
2464/// # Errors
2465/// As [`inter_frame_headers`].
2466pub fn inter_frame_headers_slots(
2467 width: usize,
2468 height: usize,
2469 base_q_idx: u8,
2470 order_hint: u32,
2471 last_slot: u8,
2472 self_slot: u8,
2473 altref_slot: u8,
2474) -> Result<(SequenceHeader, FrameHeader)> {
2475 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
2476 let header = FrameHeader {
2477 frame_type: FrameType::Inter,
2478 frame_is_intra: false,
2479 show_frame: true,
2480 error_resilient_mode: false,
2481 disable_cdf_update: false,
2482 // The tile writer hands its end-of-tile tables to the next frame
2483 // (`encode_sequence_with_ctx`), so the frame stores them the way the
2484 // decoder will load them (spec 7.20).
2485 disable_frame_end_update_cdf: false,
2486 force_integer_mv: false,
2487 order_hint,
2488 primary_ref_frame: 0,
2489 refresh_frame_flags: 1 << self_slot,
2490 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
2491 // names the slot this frame both predicts from and refreshes;
2492 // GOLDEN names slot 1, which the key frame wrote when it refreshed
2493 // all eight and which no inter frame ever overwrites, so it holds
2494 // the key frame's own picture for the whole GOP.
2495 ref_frame_idx: {
2496 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
2497 idx[3] = GOLDEN_SLOT;
2498 idx[6] = altref_slot;
2499 idx
2500 },
2501 // lane-hpmv: libaom's own rule (`av1_pick_and_set_high_precision_mv`:
2502 // `use_hp = qindex < HIGH_PRECISION_MV_QTHRESH`), with this crate's
2503 // threshold in [`HP_MV_QTHRESH`]. `force_integer_mv` is false in
2504 // every frame this constructor builds, so no further guard is needed.
2505 allow_high_precision_mv: high_precision_mv_at(base_q_idx),
2506 // A FIXED frame-level filter, so no block codes an `interp_filter`
2507 // symbol. lane-obmc3 instrumented whether that costs anything: a
2508 // libaom `cpu-used 6` crf 41 stream of the long-GOP film B window
2509 // (45941 B, the same point `lanes/libcen.report.md` matched) read
2510 // back through `EC_AV1_BITCENSUS=1 syntax_census` codes
2511 // `switchable_interp 0/0` in EVERY frame -- libaom picks a fixed
2512 // frame filter here too, so there are ZERO per-block filter bits at
2513 // stake on this content and the per-block switchable search was not
2514 // built (the charter's premise that libaom codes switchable interp
2515 // per block on film B is refuted by its own stream).
2516 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
2517 // lane-av1obmc: with this bit set every single-reference inter block
2518 // libaom's `motion_mode_allowed` accepts carries a `motion_mode`
2519 // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion`
2520 // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied
2521 // to the OBMC knob rather than always on: with every block choosing
2522 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
2523 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
2524 // and stays byte-identical to the streams before this lane.
2525 // lane-av1obmc2: the warp knob joins that disjunction, and turns on
2526 // `allow_warped_motion` besides -- which is what makes an eligible
2527 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
2528 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
2529 is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC") || warp_on(),
2530 allow_warped_motion: warp_on(),
2531 use_ref_frame_mvs: false,
2532 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
2533 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
2534 // set this crate carries a table for at 16x16 (see
2535 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
2536 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
2537 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
2538 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
2539 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
2540 // path) -- with this flag set, `get_tx_set`'s intra branch returns
2541 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
2542 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
2543 reduced_tx_set: true,
2544 ..key
2545 };
2546 Ok((seq, header))
2547}
2548
2549fn too_large() -> Error {
2550 Error::unsupported(
2551 "AV1 encode",
2552 "the picture is larger than a frame size can carry",
2553 )
2554}
2555
2556mod coef;
2557pub use coef::*;
2558
2559mod split;
2560pub(crate) use split::*;
2561
2562mod inter_search;
2563pub use inter_search::*;
2564
2565mod frame;
2566pub use frame::*;
2567
2568#[cfg(test)]
2569mod tests;
2570
2571#[cfg(test)]
2572mod more_tests;