forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.1 MiBa69dfabTahinli4 hours ago4073 commits

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