forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.8 MiBe83e29aTahinli2 months ago2365 commits

encode.rs10196 lines, 448.3 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, dequant_and_inverse_typed, forward_and_quantize,
45 forward_and_quantize_typed,
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/// How heavily the mode search weighs rate against squared error, in units of
76/// the quantizer's reconstruction step squared per bit.
77///
78/// Swept three times over his clips and three synthetic pictures
79/// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in
80/// the three lane reports). The first sweep, before the mode symbol was
81/// costed, put the best point at 0.05; costing it moved the point to 0.1. The
82/// third sweep, after the levels were costed through the writer's own CDFs
83/// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98%
84/// on film and -0.20% against -0.14% on screen capture.
85const LAMBDA_SCALE: f64 = 0.1;
86
87/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
88/// picks it is the thing running. A release build has no such knob.
89fn lambda_scale() -> f64 {
90 let swept = std::env::var("EC_AV1_LAMBDA")
91 .ok()
92 .and_then(|v| v.parse::<f64>().ok());
93 match swept {
94 Some(scale) if cfg!(test) => scale,
95 _ => LAMBDA_SCALE,
96 }
97}
98
99// Every frame's predicted coefficient bits since the last
100// `take_predicted_bits`, in coding order -- the encoder half of
101// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement.
102#[cfg(test)]
103thread_local! {
104 static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) };
105}
106
107/// Records one frame's predicted coefficient bits.
108#[cfg(test)]
109fn record_predicted_bits(bits: f64) {
110 PREDICTED_BITS.with(|p| p.borrow_mut().push(bits));
111}
112
113/// Takes (and clears) what the frames encoded on this thread were predicted to
114/// spend on coefficients.
115#[cfg(test)]
116pub(crate) fn take_predicted_bits() -> Vec<f64> {
117 PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut()))
118}
119
120/// Whether a 16x16 inter leaf may split into four 8x8 ones of its own.
121const SPLIT_INTER_8: bool = true;
122
123/// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
124/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
125/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0`
126/// turns it off for an A/B on one build.
127/// Whether an INTER frame also carries `TxMode::Select`: an inter block's
128/// residual as one transform over the whole block or as the four transforms
129/// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every
130/// intra block inside the inter frame. ON since lane-av1tx2, which found why
131/// the streams desynced -- the writer counted the [`crate::decode::
132/// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the
133/// reader drops the term -- and measured the split search: BD-rate vs libaom
134/// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the
135/// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an
136/// A/B on one build.
137fn tx_select_inter() -> bool {
138 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
139 *ON.get_or_init(|| {
140 !matches!(
141 std::env::var("EC_AV1_TX_SELECT_INTER").as_deref(),
142 Ok("0") | Ok("off")
143 )
144 })
145}
146
147fn tx_select() -> bool {
148 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
149 *ON.get_or_init(|| {
150 !matches!(
151 std::env::var("EC_AV1_TX_SELECT").as_deref(),
152 Ok("0") | Ok("off")
153 )
154 })
155}
156
157fn split_inter_8() -> bool {
158 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
159 Some(v) if cfg!(test) => v != "0",
160 _ => SPLIT_INTER_8,
161 }
162}
163
164/// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
165/// NEARESTMV candidate it always had.
166const LEAF_NEW_MV: bool = true;
167
168/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
169/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
170/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
171/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
172const EXTRA_REF_NEW_MV: bool = true;
173
174/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
175/// own best vector before that reference's `NEWMV` search is skipped: a
176/// factor on the search cost scale, `1.0` meaning "as good or better".
177/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
178/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
179/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
180/// extra searches drop from +27% to +4% of the base count -- and on screen
181/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
182/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
183const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
184
185/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
186fn extra_new_skip_margin() -> f64 {
187 match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
188 Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
189 _ => EXTRA_NEW_SKIP_MARGIN,
190 }
191}
192
193/// The margin on a LEAF's SECOND-reference motion search, the same early-out
194/// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference
195/// `NEWMV`: the search is skipped when that reference's own
196/// `NEAREST_NEARESTMV` vector already prices this many times better than the
197/// leaf's `LAST` search found. `0.0` never skips.
198///
199/// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs
200/// libaom (1080p/2160p/screen) against the extra `motion::search` calls at
201/// 2160p (38195 with no second-reference search at all):
202/// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093,
203/// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at
204/// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the
205/// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter
206/// of its extra searches; past it the calls double for another -0.3/-0.5.
207/// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is
208/// all `NEAREST_NEARESTMV` and no searched second vector ever wins there --
209/// so the margin is pure wall on that content (+10% searches at 0.8).
210const LEAF_SECOND_NEW_MARGIN: f64 = 0.8;
211
212/// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the
213/// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`.
214fn leaf_second_new_margin() -> f64 {
215 match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() {
216 Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN),
217 None => LEAF_SECOND_NEW_MARGIN,
218 }
219}
220
221/// Whether a leaf searches its SECOND reference at all (lane-av1comp4).
222fn leaf_second_new_mv() -> bool {
223 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
224 Some(v) => v != "0",
225 None => true,
226 }
227}
228
229/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
230/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
231/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
232/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
233/// was missing was the encoder ever forming one below 32x32.
234const LEAF_COMPOUND: bool = true;
235
236/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
237fn leaf_compound() -> bool {
238 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
239 Some(v) => v != "0",
240 None => LEAF_COMPOUND,
241 }
242}
243
244/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
245fn leaf_new_mv() -> bool {
246 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
247 Some(v) if cfg!(test) => v != "0",
248 _ => LEAF_NEW_MV,
249 }
250}
251
252/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
253/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
254/// the true frame edge cut through was ever split there; inside the frame
255/// every block was coded whole, which left the partition decision the key
256/// frame already makes unmade for eleven frames out of twelve.
257const SPLIT_INTER_BLOCKS: bool = true;
258
259/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
260/// measurement that keeps it is running (test builds only, like
261/// [`lambda_scale`]).
262fn split_inter_blocks() -> bool {
263 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
264 Some(v) if cfg!(test) => v != "0",
265 _ => SPLIT_INTER_BLOCKS,
266 }
267}
268
269/// Whether the encoder searches loop restoration at all (spec 7.17): one
270/// Wiener filter per 64x64 luma restoration unit, picked from
271/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
272/// test build, like [`lambda_scale`].
273const RESTORATION: bool = true;
274
275/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
276fn restoration_enabled() -> bool {
277 match std::env::var("EC_AV1_LR").ok() {
278 Some(v) if cfg!(test) => v != "0",
279 _ => RESTORATION,
280 }
281}
282
283/// libaom's `partition_search_breakout` shape: how many non-zero luma
284/// coefficients per 256 luma samples a block may code and still be judged
285/// well enough predicted that the split below it is not worth trying. `0`
286/// disables the breakout (only the existing all-skip prune applies), which
287/// is the default until the sweep below justifies otherwise.
288///
289/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
290/// is where this lane's wall would have gone: 1 cuts the three clips'
291/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
292/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
293/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
294/// encoder's inter quality lives, so `0` ships and the knob stays for a
295/// future explicit speed preset.
296const SPLIT_BREAKOUT_COEFFS: usize = 0;
297
298/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
299/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
300/// out under `threshold * lambda` is not offered the split at all, and a
301/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
302/// always, as before this lever.
303///
304/// The census is what points here: the split trial runs on nearly every
305/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
306/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
307/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
308/// points, so the gate has to read the block's own RD cost, not its levels.
309///
310/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
311/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
312/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
313/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
314/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
315/// the largest threshold whose BD stays inside the +0.3 keep rule on every
316/// clip.
317const SPLIT_RD_THRESHOLD: f64 = 0.125;
318
319/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
320fn split_rd_threshold() -> f64 {
321 static T: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
322 *T.get_or_init(|| {
323 std::env::var("EC_AV1_SPLIT_RD")
324 .ok()
325 .and_then(|v| v.parse().ok())
326 .unwrap_or(SPLIT_RD_THRESHOLD)
327 })
328}
329
330/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
331/// [`split_rd_threshold`] withholds the split trial.
332fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
333 let t = split_rd_threshold();
334 t > 0.0 && cost < t * lambda * (side * side) as f64
335}
336
337/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
338/// build.
339fn split_breakout_coeffs() -> usize {
340 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
341 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
342 _ => SPLIT_BREAKOUT_COEFFS,
343 }
344}
345
346/// How often each partition decision was taken since the last
347/// [`take_partition_hits`], so a gate can report how often a new partition
348/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
349/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
350/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
351static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
352 std::sync::atomic::AtomicUsize::new(0),
353 std::sync::atomic::AtomicUsize::new(0),
354 std::sync::atomic::AtomicUsize::new(0),
355 std::sync::atomic::AtomicUsize::new(0),
356];
357
358/// Records one such decision.
359fn partition_hit(which: usize) {
360 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
361}
362
363/// Takes (and clears) the counts.
364#[cfg(test)]
365pub(crate) fn take_partition_hits() -> [usize; 4] {
366 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
367}
368
369/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
370/// rate-distortion trials the block search actually runs, by kind, and where
371/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
372/// default, and a measurement build rather than a speed one -- the census
373/// runs the SAD pre-pass the unpruned search otherwise skips.
374pub fn census_on() -> bool {
375 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
376 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
377}
378
379/// What each [`CENSUS`] counter counts.
380pub const CENSUS_KINDS: [&str; 11] = [
381 "intra blocks searched (key frame + inter leaves)",
382 "intra luma mode trials",
383 "chroma searches",
384 "chroma mode trials (each = 2 plane trials)",
385 "tx-depth trials (transform units, depth >= 1)",
386 "inter 32x32 blocks searched",
387 "inter block intra-mode trials",
388 "inter mv candidates (each = 3 mc trials)",
389 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
390 " of those, intra won",
391 " of those, the NEARESTMV trial coded no residual",
392];
393
394/// The census counters themselves, indexed by [`CENSUS_KINDS`].
395static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
396 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
397
398/// Where the RD winner sat in the SAD ranking, for the luma intra search and
399/// the chroma mode search -- what says whether a top-N prune would have kept
400/// the block the search actually chose.
401static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
402 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
403static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
404 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
405
406fn census_add(kind: usize, n: usize) {
407 if census_on() {
408 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
409 }
410}
411
412/// Reads (and clears) the census, so a driver can attribute it to its own encode.
413pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
414 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
415 (
416 std::array::from_fn(|i| take(&CENSUS[i])),
417 std::array::from_fn(|i| take(&LUMA_RANK[i])),
418 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
419 )
420}
421
422/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
423/// first -- the census's one shared rule, so the luma and chroma histograms
424/// mean the same thing.
425fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
426 scored
427 .iter()
428 .filter(|&&(score, mode)| {
429 mode != winner
430 && score
431 < scored
432 .iter()
433 .find(|&&(_, m)| m == winner)
434 .map_or(f64::INFINITY, |&(s, _)| s)
435 })
436 .count()
437}
438
439/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
440/// four cost less. Set from the measurement in the lane report.
441const SPLIT_BLOCKS: bool = true;
442
443/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
444/// by calling [`encode_key_frame_inner`] both ways.
445pub(crate) fn split_blocks() -> bool {
446 SPLIT_BLOCKS
447}
448
449/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
450/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
451/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
452/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
453/// stream's decode output actually carries 10-bit precision instead of
454/// silently losing its low 2 bits). The encoder only ever produces values in
455/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
456/// decision); `Plane::source` narrows right back to `u8` at its two
457/// construction sites, a lossless round trip for that range.
458#[derive(Clone, Debug, PartialEq, Eq)]
459pub struct Picture {
460 /// The picture's width in luma samples.
461 pub width: usize,
462 /// Its height in luma samples.
463 pub height: usize,
464 /// The luma plane, `width * height` samples in raster order.
465 pub y: Vec<u16>,
466 /// The U plane, at half the width and half the height.
467 pub u: Vec<u16>,
468 /// The V plane, the same shape as U.
469 pub v: Vec<u16>,
470}
471
472impl Picture {
473 /// A mid-grey picture of the given size.
474 #[must_use]
475 pub fn grey(width: usize, height: usize) -> Self {
476 Self {
477 width,
478 height,
479 y: vec![128; width * height],
480 u: vec![128; width * height / 4],
481 v: vec![128; width * height / 4],
482 }
483 }
484
485 pub(crate) fn check(&self) -> Result<()> {
486 if self.width == 0
487 || !self.width.is_multiple_of(BLOCK)
488 || !self.height.is_multiple_of(BLOCK)
489 || !self.height.is_multiple_of(BLOCK)
490 {
491 return Err(Error::unsupported(
492 "AV1 encode",
493 "the picture must be a whole number of 32x32 blocks in each direction",
494 ));
495 }
496 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
497 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
498 return Err(Error::unsupported(
499 "AV1 encode",
500 "each plane must carry one sample per position at 4:2:0",
501 ));
502 }
503 Ok(())
504 }
505
506 /// What the public entry points require of the picture they are handed,
507 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
508 /// needs a whole chroma sample per two luma ones) and one sample per
509 /// position on each plane.
510 pub(crate) fn check_even(&self) -> Result<()> {
511 if self.width == 0
512 || self.height == 0
513 || !self.width.is_multiple_of(2)
514 || !self.height.is_multiple_of(2)
515 {
516 return Err(Error::unsupported(
517 "AV1 encode",
518 "the picture's width and height must each be even and nonzero",
519 ));
520 }
521 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
522 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
523 return Err(Error::unsupported(
524 "AV1 encode",
525 "each plane must carry one sample per position at 4:2:0",
526 ));
527 }
528 Ok(())
529 }
530
531 /// This picture, padded by edge replication to the next whole number of
532 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
533 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
534 /// sequence (what the inter tile writer's partition needs on top of
535 /// that). Identity (a plain clone, not a copy through the replication
536 /// loop) when the picture is already that size — the multiple-of-32 (or
537 /// -64) fast path is unchanged.
538 pub(crate) fn padded_to(&self, align: usize) -> Picture {
539 let padded_width = self.width.next_multiple_of(align);
540 let padded_height = self.height.next_multiple_of(align);
541 if padded_width == self.width && padded_height == self.height {
542 return self.clone();
543 }
544 Picture {
545 width: padded_width,
546 height: padded_height,
547 y: pad_plane(
548 &self.y,
549 self.width,
550 self.height,
551 padded_width,
552 padded_height,
553 ),
554 u: pad_plane(
555 &self.u,
556 self.width / 2,
557 self.height / 2,
558 padded_width / 2,
559 padded_height / 2,
560 ),
561 v: pad_plane(
562 &self.v,
563 self.width / 2,
564 self.height / 2,
565 padded_width / 2,
566 padded_height / 2,
567 ),
568 }
569 }
570}
571
572/// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8`
573/// (8-bit only, unchanged this round -- widening the encoder is out of this
574/// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that
575/// lets it keep calling [`crate::intra::predict`] now that shape is `u16`
576/// in and out. A block-sized round-trip through `u16` is exact for 8-bit
577/// content (every value fits both ways), so this changes no encoder output.
578#[allow(clippy::too_many_arguments)]
579fn intra_predict_u8(
580 mode: u8,
581 angle_delta: i32,
582 above: Option<&[u8]>,
583 left: Option<&[u8]>,
584 corner: Option<u8>,
585 bw: usize,
586 bh: usize,
587 enable_edge_filter: bool,
588 smooth_neighbor: bool,
589 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
590) {
591 let above16: Option<Vec<u16>> = above.map(|s| s.iter().map(|&v| u16::from(v)).collect());
592 let left16: Option<Vec<u16>> = left.map(|s| s.iter().map(|&v| u16::from(v)).collect());
593 let mut dst16 = vec![0u16; dst.len()];
594 crate::intra::predict(
595 mode,
596 angle_delta,
597 above16.as_deref(),
598 left16.as_deref(),
599 corner.map(u16::from),
600 bw,
601 bh,
602 enable_edge_filter,
603 smooth_neighbor,
604 &mut dst16, fctx,
605 );
606 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
607 *d = s as u8;
608 }
609}
610
611/// Pads one plane to `(padded_width, padded_height)` by repeating its last
612/// row and column, so the block coder always sees a whole number of blocks.
613/// [`crop_plane`] undoes this on the way back out.
614fn pad_plane<T: Copy + Default>(
615 source: &[T],
616 width: usize,
617 height: usize,
618 padded_width: usize,
619 padded_height: usize,
620) -> Vec<T> {
621 let mut out = vec![T::default(); padded_width * padded_height];
622 for row in 0..padded_height {
623 let src = source[row.min(height - 1) * width..][..width].as_ref();
624 let dst = &mut out[row * padded_width..][..padded_width];
625 dst[..width].copy_from_slice(src);
626 dst[width..].fill(src[width - 1]);
627 }
628 out
629}
630
631/// The top-left `width` x `height` region of a plane that is `padded_width`
632/// wide, which is the render-size crop [`Picture::padded`]'s replication
633/// exists to let a decoder undo.
634fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
635 let mut out = Vec::with_capacity(width * height);
636 for row in 0..height {
637 out.extend_from_slice(&source[row * padded_width..][..width]);
638 }
639 out
640}
641
642/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
643/// region a decoder produces, which is the public contract for what a caller
644/// sees back — the padded planes the encoder coded against never leave this
645/// module. Identity when the reconstruction is already that size.
646pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
647 let reconstruction = &encoded.reconstruction;
648 let cropped = if reconstruction.width == width && reconstruction.height == height {
649 reconstruction.clone()
650 } else {
651 Picture {
652 width,
653 height,
654 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
655 u: crop_plane(
656 &reconstruction.u,
657 reconstruction.width / 2,
658 width / 2,
659 height / 2,
660 ),
661 v: crop_plane(
662 &reconstruction.v,
663 reconstruction.width / 2,
664 width / 2,
665 height / 2,
666 ),
667 }
668 };
669 Encoded {
670 stream: encoded.stream.clone(),
671 modes: encoded.modes.clone(),
672 inter_block_share: encoded.inter_block_share,
673 reconstruction: cropped,
674 tile: encoded.tile.clone(),
675 mi_cols: encoded.mi_cols,
676 mi_rows: encoded.mi_rows,
677 base_q_idx: encoded.base_q_idx,
678 tx_select: encoded.tx_select,
679 screen: encoded.screen,
680 start_cdfs: encoded.start_cdfs.clone(),
681 next_cdfs: encoded.next_cdfs.clone(),
682 loop_filter: encoded.loop_filter,
683 loop_restoration: encoded.loop_restoration,
684 cdef: encoded.cdef,
685 }
686}
687
688/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
689/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
690#[derive(Clone)]
691pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
692
693impl std::fmt::Debug for CdfSnapshot {
694 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
695 f.write_str("CdfSnapshot")
696 }
697}
698
699/// What one call to [`encode_key_frame`] produced.
700#[derive(Clone, Debug)]
701pub struct Encoded {
702 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
703 /// OBU carrying one tile.
704 pub stream: Vec<u8>,
705 /// What a decoder will produce from `stream` — the encoder's own
706 /// reconstruction, which its prediction was built on.
707 pub reconstruction: Picture,
708 /// The luma intra mode each block was coded under, in the order the blocks
709 /// are coded — raster order among the quadrants of each superblock, and
710 /// among the four 16x16 blocks of a quadrant that was split.
711 pub modes: Vec<u8>,
712 /// The fraction of this frame's 32x32 blocks that were coded inter (any
713 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
714 /// for a key frame, which has no such choice — so a caller can tell a
715 /// frame with no motion worth coding from one that never got the chance.
716 pub inter_block_share: f64,
717 /// The tile payload alone, undecorated by any OBU framing, and the frame
718 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
719 /// `crate::decode`'s tests are the only reader; a real decoder gets these
720 /// off the wire by parsing `stream`'s OBUs instead.
721 pub(crate) tile: Vec<u8>,
722 pub(crate) mi_cols: u32,
723 pub(crate) mi_rows: u32,
724 pub(crate) base_q_idx: u8,
725 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
726 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
727 /// and reading it off `stream`'s header is what `decode_stream` does. A
728 /// test that decodes `tile` directly must pass this one along, or it reads
729 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
730 /// block.
731 pub(crate) tx_select: bool,
732 /// The CDF state this frame's tile writer started from -- the defaults
733 /// for a key frame and for the first inter frame, and the previous
734 /// frame's stored tables after that. A test that decodes `tile` directly
735 /// must feed the decoder this, exactly as `decode_stream` feeds it what
736 /// the frame's `primary_ref_frame` slot holds (same class as
737 /// `tx_select`: a header bit a raw tile decode cannot guess).
738 pub(crate) start_cdfs: CdfSnapshot,
739 /// What this frame stores into the slots it refreshes (spec 7.20,
740 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
741 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
742 /// started from when it is on.
743 pub(crate) next_cdfs: CdfSnapshot,
744 /// This frame header's chosen deblocking parameters
745 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
746 /// picture the decoder produces UNDER them, so a test that decodes
747 /// `tile` directly must pass these along, exactly as it must `tx_select`
748 /// (class: test asserts against a stale header).
749 pub(crate) loop_filter: LoopFilterParams,
750 /// This frame header's chosen CDEF parameters, threaded for the same
751 /// reason as `loop_filter`.
752 pub(crate) cdef: CdefParams,
753 /// This frame header's `allow_screen_content_tools`
754 /// ([`screen_content`]) -- every intra block of the tile carries the two
755 /// palette-mode symbols under it, so a raw tile decode that guessed
756 /// `false` would desync at the first block (same class as `tx_select`).
757 pub(crate) screen: bool,
758 /// This frame header's chosen loop restoration parameters, threaded for
759 /// the same reason as `loop_filter` -- and doubly so: the per-unit
760 /// filters themselves are coded in `tile`, so a decode of it under a
761 /// stale `RESTORE_NONE` header desyncs at the first superblock.
762 pub(crate) loop_restoration: LoopRestorationParams,
763}
764
765thread_local! {
766 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
767 /// header offers the per-frame `allow_screen_content_tools` bit at all.
768 /// Armed once by the key frame ([`encode_key_frame_inner`], from
769 /// [`screen_content`]) and read by every header builder after it, so that
770 /// the inter frames of a screen sequence lay their headers out the same
771 /// way the sequence header the key frame wrote says they do -- a per-call
772 /// parameter would have to thread through `inter_frame_headers`' four
773 /// public entry points and every hand-built-stream test that calls them.
774 /// A sequence with no screen content leaves this false and writes exactly
775 /// the bits it wrote before this lane.
776 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
777}
778
779thread_local! {
780 /// Overrides [`screen_content`] for the calling thread, which is what the
781 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
782 /// codes every block losslessly, so both arms of a mode ablation reach
783 /// infinite PSNR and the ablation measures nothing at all (the
784 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
785 /// variable cannot do this -- the tests run in one process, in parallel.
786 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
787}
788
789#[cfg(test)]
790pub(crate) fn force_screen(value: Option<bool>) {
791 SCREEN_FORCE.with(|c| c.set(value));
792}
793
794pub(crate) fn arm_seq_screen(on: bool) {
795 SEQ_SCREEN.with(|c| c.set(on));
796}
797
798fn seq_screen() -> bool {
799 SEQ_SCREEN.with(std::cell::Cell::get)
800}
801
802/// How many distinct colours a 16x16 luma block may hold and still count as
803/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
804/// `av1_set_screen_content_options` bound is 4, which separates NOTHING on a
805/// real (lossily coded, so noisy) desktop capture: `probe_screen_detect`
806/// measures the share of 16x16 blocks under each bound on the gate's own
807/// three clips, and only at 32 do the populations part -- film 20.3..21.9%,
808/// his OBS capture 51.1..51.5%.
809fn screen_colors() -> usize {
810 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
811 *N.get_or_init(|| {
812 std::env::var("EC_AV1_SCREEN_COLORS")
813 .ok()
814 .and_then(|v| v.parse().ok())
815 .unwrap_or(32)
816 })
817}
818
819/// The reciprocal of the frame area those blocks must cover, in tenths --
820/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is 10 (one
821/// tenth). 3 (a third) is the midpoint of the two populations
822/// `probe_screen_detect` measured at the colour bound above.
823/// `EC_AV1_SCREEN_PCT`.
824fn screen_pct() -> usize {
825 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
826 *N.get_or_init(|| {
827 std::env::var("EC_AV1_SCREEN_PCT")
828 .ok()
829 .and_then(|v| v.parse().ok())
830 .unwrap_or(3)
831 })
832}
833
834/// How many frames [`screen_content`] said yes/no to, so a gate can print
835/// whether the detector fired at all (class `gate-blind-to-feature`).
836pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
837 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
838
839/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
840/// the distinct colours of every 16x16 block and turn the screen-content
841/// tools on when the blocks holding between 2 and [`screen_colors`] of them
842/// cover more than a [`screen_pct`]th of the frame. `width` is the plane's
843/// stride, `true_*` the frame's real (decodable) extent.
844fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
845 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
846 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
847 return forced;
848 }
849 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
850 let on = v != "0";
851 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
852 return on;
853 }
854 let (blk, limit) = (16usize, screen_colors());
855 let mut counted = 0usize;
856 for by in (0..true_height).step_by(blk) {
857 for bx in (0..true_width).step_by(blk) {
858 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
859 let mut seen = [false; 256];
860 let mut colors = 0usize;
861 for row in 0..h {
862 for col in 0..w {
863 let v = usize::from(y[(by + row) * width + bx + col]);
864 if !seen[v] {
865 seen[v] = true;
866 colors += 1;
867 }
868 }
869 }
870 if colors > 1 && colors <= limit {
871 counted += 1;
872 }
873 }
874 }
875 let on = counted * blk * blk * screen_pct() > true_width * true_height;
876 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
877 on
878}
879
880/// The sequence and frame headers a picture of this size is coded under: one
881/// tile, one transform size per block, no in-loop filter parameters yet
882/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
883/// CDEF strengths in once the tile is coded), no CDF adaptation
884/// and no tool the tile writer does not code.
885///
886/// # Errors
887/// Returns an error when the picture is larger than the 16-bit frame size the
888/// sequence header carries.
889pub fn key_frame_headers(
890 width: usize,
891 height: usize,
892 base_q_idx: u8,
893) -> Result<(SequenceHeader, FrameHeader)> {
894 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
895}
896
897/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
898/// studio (limited) range: what this crate's sequence header carried before
899/// [`crate::encoder`]'s facade could configure it, and what
900/// [`key_frame_headers`] still asks for.
901fn unspecified_color_config() -> ColorConfig {
902 ColorConfig {
903 bit_depth: 8,
904 mono_chrome: false,
905 num_planes: 3,
906 color_primaries: 2,
907 transfer_characteristics: 2,
908 matrix_coefficients: 2,
909 color_range: false,
910 subsampling_x: 1,
911 subsampling_y: 1,
912 chroma_sample_position: ChromaSamplePosition::Unknown,
913 separate_uv_delta_q: false,
914 }
915}
916
917/// [`key_frame_headers`] with the sequence header's colour config named
918/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
919/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
920/// which is all a player picks a colour transform from and which
921/// [`crate::encoder::Colour`] is the facade's own name for.
922///
923/// # Errors
924/// The same as [`key_frame_headers`].
925pub(crate) fn key_frame_headers_colour(
926 width: usize,
927 height: usize,
928 base_q_idx: u8,
929 color_config: ColorConfig,
930) -> Result<(SequenceHeader, FrameHeader)> {
931 let bits = |n: usize| -> Result<u32> {
932 let n = u32::try_from(n).map_err(|_| too_large())?;
933 if n == 0 || n > 1 << 16 {
934 return Err(too_large());
935 }
936 Ok((32 - (n - 1).leading_zeros()).max(1))
937 };
938 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
939 let (w, h) = (width as u32, height as u32);
940 let seq = SequenceHeader {
941 seq_profile: 0,
942 operating_points: vec![OperatingPoint {
943 seq_level_idx: 8,
944 ..OperatingPoint::default()
945 }],
946 frame_width_bits,
947 frame_height_bits,
948 max_frame_width: w,
949 max_frame_height: h,
950 use_128x128_superblock: false,
951 enable_filter_intra: false,
952 enable_intra_edge_filter: false,
953 enable_order_hint: true,
954 order_hint_bits: 7,
955 enable_superres: false,
956 // spec 5.9.19: with the sequence bit set every frame header carries
957 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
958 // pair for the whole frame, chosen by `crate::filter_search` -- so no
959 // `cdef_idx` literal is coded in the tile and a frame that wants no
960 // CDEF simply carries zero strengths.
961 enable_cdef: true,
962 enable_restoration: true,
963 // SELECT (2) when this sequence's key frame detected screen content
964 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
965 // is then coded in every frame header, and only the frames that want
966 // the palette syntax set it. 0 -- the forced-off form, no bit at all
967 // -- otherwise, which is what every non-screen stream this encoder
968 // writes still carries.
969 seq_force_screen_content_tools: if seq_screen() {
970 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
971 } else {
972 0
973 },
974 seq_force_integer_mv: 0,
975 color_config,
976 still_picture: false,
977 reduced_still_picture_header: false,
978 timing_info: None,
979 decoder_model_info: None,
980 initial_display_delay_present_flag: false,
981 operating_point: 0,
982 operating_point_idc: 0,
983 frame_id_numbers_present_flag: false,
984 delta_frame_id_length: 0,
985 additional_frame_id_length: 0,
986 enable_interintra_compound: false,
987 enable_masked_compound: false,
988 enable_warped_motion: false,
989 enable_dual_filter: false,
990 enable_jnt_comp: false,
991 enable_ref_frame_mvs: false,
992 film_grain_params_present: false,
993 };
994 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
995 // own (true, unpadded) width and height, not from any block-grid
996 // alignment — a decoder derives these straight from `frame_width`/
997 // `frame_height` below, so this must match it exactly.
998 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
999 let header = FrameHeader {
1000 frame_type: FrameType::Key,
1001 frame_is_intra: true,
1002 show_frame: true,
1003 error_resilient_mode: true,
1004 // The tile writer keeps the same CDF state the decoder does and
1005 // updates it in the same order, so the frame lets the decoder adapt.
1006 disable_cdf_update: false,
1007 // Nothing reads the state this frame leaves behind: a key frame always
1008 // starts from the defaults, and this encoder emits one frame.
1009 disable_frame_end_update_cdf: true,
1010 force_integer_mv: true,
1011 refresh_frame_flags: 0xFF,
1012 primary_ref_frame: PRIMARY_REF_NONE,
1013 frame_width: w,
1014 frame_height: h,
1015 upscaled_width: w,
1016 render_width: w,
1017 render_height: h,
1018 mi_cols,
1019 mi_rows,
1020 tile_info: TileInfo {
1021 uniform_spacing: true,
1022 cols: 1,
1023 rows: 1,
1024 mi_col_starts: vec![0, mi_cols],
1025 mi_row_starts: vec![0, mi_rows],
1026 tile_size_bytes: 1,
1027 ..TileInfo::default()
1028 },
1029 quantization: QuantizationParams {
1030 base_q_idx,
1031 ..QuantizationParams::default()
1032 },
1033 tx_mode: TxMode::Largest,
1034 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
1035 // intra transform below 32x32, not only 16x16 -- the set this crate
1036 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
1037 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
1038 // so a decoder honouring the header picks the same CDF the writer
1039 // used only if this is set here too, not only on the inter variant
1040 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
1041 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
1042 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
1043 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
1044 // the arithmetic coder's `rng` register from the very first 8x8-leaf
1045 // luma transform onward with no symbol value ever differing.
1046 reduced_tx_set: true,
1047 ..FrameHeader::default()
1048 };
1049 Ok((seq, header))
1050}
1051
1052/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
1053/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
1054/// 1 still holds the key frame however long the GOP runs.
1055pub const GOLDEN_SLOT: u8 = 1;
1056
1057/// The frame header for a shown inter frame that predicts from the single
1058/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
1059/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
1060/// reused verbatim: an inter frame never changes the sequence.
1061///
1062/// # Errors
1063/// Returns an error under the same conditions as [`key_frame_headers`].
1064pub fn inter_frame_headers(
1065 width: usize,
1066 height: usize,
1067 base_q_idx: u8,
1068 order_hint: u32,
1069 last_slot: u8,
1070) -> Result<(SequenceHeader, FrameHeader)> {
1071 inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
1072}
1073
1074/// [`inter_frame_headers`] with the three slots named apart: the one read as
1075/// `LAST_FRAME`, the one this frame refreshes, and the one read as
1076/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
1077/// so that the frame two back is still intact in the slot this one is about
1078/// to overwrite -- read before write, spec 7.20's decode order.
1079///
1080/// # Errors
1081/// As [`inter_frame_headers`].
1082pub fn inter_frame_headers_slots(
1083 width: usize,
1084 height: usize,
1085 base_q_idx: u8,
1086 order_hint: u32,
1087 last_slot: u8,
1088 self_slot: u8,
1089 altref_slot: u8,
1090) -> Result<(SequenceHeader, FrameHeader)> {
1091 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
1092 let header = FrameHeader {
1093 frame_type: FrameType::Inter,
1094 frame_is_intra: false,
1095 show_frame: true,
1096 error_resilient_mode: false,
1097 disable_cdf_update: false,
1098 // The tile writer hands its end-of-tile tables to the next frame
1099 // (`encode_sequence_with_ctx`), so the frame stores them the way the
1100 // decoder will load them (spec 7.20).
1101 disable_frame_end_update_cdf: false,
1102 force_integer_mv: false,
1103 order_hint,
1104 primary_ref_frame: 0,
1105 refresh_frame_flags: 1 << self_slot,
1106 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
1107 // names the slot this frame both predicts from and refreshes;
1108 // GOLDEN names slot 1, which the key frame wrote when it refreshed
1109 // all eight and which no inter frame ever overwrites, so it holds
1110 // the key frame's own picture for the whole GOP.
1111 ref_frame_idx: {
1112 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
1113 idx[3] = GOLDEN_SLOT;
1114 idx[6] = altref_slot;
1115 idx
1116 },
1117 allow_high_precision_mv: false,
1118 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
1119 is_motion_mode_switchable: false,
1120 use_ref_frame_mvs: false,
1121 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
1122 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
1123 // set this crate carries a table for at 16x16 (see
1124 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
1125 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
1126 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
1127 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
1128 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
1129 // path) -- with this flag set, `get_tx_set`'s intra branch returns
1130 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
1131 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
1132 reduced_tx_set: true,
1133 ..key
1134 };
1135 Ok((seq, header))
1136}
1137
1138fn too_large() -> Error {
1139 Error::unsupported(
1140 "AV1 encode",
1141 "the picture is larger than a frame size can carry",
1142 )
1143}
1144
1145/// One plane of the picture being coded, and the reconstruction being built
1146/// beside it.
1147struct Plane<'a> {
1148 source: &'a [u8],
1149 reconstruction: Vec<u8>,
1150 width: usize,
1151 height: usize,
1152 /// The frame's true, decodable extent in this plane's own units --
1153 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
1154 /// not `width`/`height` above, which is the padded coding-surface size.
1155 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
1156 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
1157 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
1158 /// this bound, even though the padded reconstruction buffer holds real
1159 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
1160 /// those instead of stopping here is what desyncs prediction at the true
1161 /// edge.
1162 true_width: usize,
1163 true_height: usize,
1164 /// This plane's own tile's pixel bounds, in this plane's units -- the
1165 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
1166 /// prediction never reaches across a tile edge even though the
1167 /// neighbouring tile's real samples sit right there in the shared
1168 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
1169 /// leaves every edge exactly as it was before tiles existed.
1170 tile_x0: usize,
1171 tile_y0: usize,
1172 tile_x1: usize,
1173 tile_y1: usize,
1174}
1175
1176impl Plane<'_> {
1177 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
1178 /// called at every superblock of the frame-raster search with the rect
1179 /// of the tile that superblock belongs to.
1180 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
1181 self.tile_x0 = x0;
1182 self.tile_y0 = y0;
1183 self.tile_x1 = x1.min(self.width);
1184 self.tile_y1 = y1.min(self.height);
1185 }
1186 /// The reconstructed samples a block at `(x, y)` predicts from: the row
1187 /// above it, the column to its left and the sample between them, each
1188 /// missing where the block sits against an edge of the frame.
1189 ///
1190 /// `reach` says whether the samples above the block's right and below its
1191 /// left are decoded, which is what a directional mode reads into; where
1192 /// they are not, or where the frame ends first, the edge is shorter and
1193 /// the predictor repeats its last sample, exactly as the decoder's clamp
1194 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
1195 fn edges(
1196 &self,
1197 x: usize,
1198 y: usize,
1199 side: usize,
1200 reach: Reach,
1201 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
1202 // Even a block's *own* edge is clamped to the true frame bound, not
1203 // just a `reach` extension: libaom's `av1_predict_intra_block`
1204 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
1205 // this block's own right/bottom to the frame edge -- from
1206 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
1207 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
1208 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
1209 // samples the row/column above/left holds before the decoder starts
1210 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
1211 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
1212 // extent straddles that edge legally (`has_half`) -- the transform
1213 // still covers the whole block, but prediction does not get to read
1214 // real reconstructed pixels past the true edge for its own row/column,
1215 // only for the padded tail it invents.
1216 let own_across = x + side.min(self.true_width.saturating_sub(x));
1217 let across = if reach.above_right {
1218 own_across + side.min(self.true_width.saturating_sub(own_across))
1219 } else {
1220 own_across
1221 }
1222 .min(self.width);
1223 let own_down = y + side.min(self.true_height.saturating_sub(y));
1224 let down = if reach.below_left {
1225 own_down + side.min(self.true_height.saturating_sub(own_down))
1226 } else {
1227 own_down
1228 }
1229 .min(self.height);
1230 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
1231 // whose own origin already sits past the true edge -- only reachable
1232 // through a partition trial priced for comparison on a split this
1233 // frame's straddling quadrant will go on to refuse (see
1234 // `a_picture_off_the_block_grid_is_refused`), never through a block
1235 // this encoder actually commits. Such a block has no true-edge
1236 // samples above or left of it at all, same as `y == 0`/`x == 0`.
1237 let across = across.min(self.tile_x1);
1238 let down = down.min(self.tile_y1);
1239 let above = (y > self.tile_y0 && across > x)
1240 .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec());
1241 let left = (x > self.tile_x0 && down > y).then(|| {
1242 (y..down)
1243 .map(|row| self.reconstruction[row * self.width + x - 1])
1244 .collect::<Vec<_>>()
1245 });
1246 let corner = (x > self.tile_x0 && y > self.tile_y0)
1247 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
1248 (above, left, corner)
1249 }
1250
1251 /// Codes one block under one mode without committing it: hands back the
1252 /// levels, the block the decoder would reconstruct, the squared error
1253 /// against the source and an estimate of what the levels cost in bits.
1254 fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
1255 self.trial_typed(at, mode, base_q_idx, deadzone, TxType::DctDct, fctx)
1256 }
1257
1258 /// [`Self::trial`] under a named transform type -- what an intra chroma
1259 /// block gets, since chroma codes no `tx_type` symbol and the decoder
1260 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
1261 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
1262 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
1263 #[allow(clippy::too_many_arguments)]
1264 fn trial_typed(
1265 &self,
1266 at: At,
1267 mode: u8,
1268 base_q_idx: u8,
1269 deadzone: f64,
1270 tx_type: TxType,
1271 fctx: &crate::decode::FrameCtx,
1272 ) -> Trial {
1273 let At {
1274 x, y, side, reach, ..
1275 } = at;
1276 let (above, left, corner) = self.edges(x, y, side, reach);
1277 // Per-candidate scratch on the search's hottest path, so both buffers
1278 // live on the stack -- `side` is at most `BLOCK` -- rather than
1279 // costing a malloc/free pair per trial (`mc_trial` already does this).
1280 let mut prediction = [0u8; BLOCK * BLOCK];
1281 let prediction = &mut prediction[..side * side];
1282 intra_predict_u8(
1283 mode,
1284 0,
1285 above.as_deref(),
1286 left.as_deref(),
1287 corner,
1288 side,
1289 side,
1290 false,
1291 false,
1292 prediction, fctx,
1293 );
1294
1295 let mut residual = [0i32; BLOCK * BLOCK];
1296 let residual = &mut residual[..side * side];
1297 for row in 0..side {
1298 for col in 0..side {
1299 residual[row * side + col] =
1300 i32::from(self.source[(y + row) * self.width + x + col])
1301 - i32::from(prediction[row * side + col]);
1302 }
1303 }
1304 #[cfg(test)]
1305 let t = std::time::Instant::now();
1306 let levels =
1307 forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type);
1308 let coded =
1309 dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type);
1310 #[cfg(test)]
1311 stage_add(2, t.elapsed());
1312
1313 let mut reconstruction = vec![0u8; side * side];
1314 let mut sse = 0.0;
1315 for row in 0..side {
1316 for col in 0..side {
1317 let i = row * side + col;
1318 let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;
1319 reconstruction[i] = sample;
1320 let error = f64::from(
1321 i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample),
1322 );
1323 sse += error * error;
1324 }
1325 }
1326 // What the levels cost is priced through the same CDFs the tile writer
1327 // will code them with, so the search ranks modes -- and the partition
1328 // trial ranks trees -- by the bits they actually spend.
1329 #[cfg(test)]
1330 let t = std::time::Instant::now();
1331 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
1332 // What the search used before it could price a block exactly: a
1333 // level costs its magnitude's width plus a sign and a run. Kept
1334 // reachable from the sweep so the two rate terms can be compared
1335 // on one build.
1336 levels
1337 .iter()
1338 .filter(|&&level| level != 0)
1339 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
1340 .sum()
1341 } else {
1342 crate::tile::coeff_bits(&levels, at.set, crate::decode::q_ctx_of(base_q_idx))
1343 };
1344 #[cfg(test)]
1345 stage_add(3, t.elapsed());
1346 Trial {
1347 levels,
1348 reconstruction,
1349 sse,
1350 bits,
1351 }
1352 }
1353
1354 /// [`Self::trial`] with the prediction already built, so that an inter
1355 /// block's motion-compensated prediction can go through the same
1356 /// residual/quantize/reconstruct path an intra block's does. `skip`
1357 /// takes the prediction as the reconstruction outright, coding no
1358 /// residual at all — what a `NEARESTMV` block that names no coefficients
1359 /// codes.
1360 #[allow(clippy::too_many_arguments)]
1361 fn code_from_prediction(
1362 &self,
1363 x: usize,
1364 y: usize,
1365 side: usize,
1366 prediction: &[u8],
1367 skip: bool,
1368 base_q_idx: u8,
1369 deadzone: f64,
1370 set: TxbSet,
1371 ) -> Trial {
1372 if skip {
1373 let mut sse = 0.0;
1374 for row in 0..side {
1375 for col in 0..side {
1376 let error = f64::from(
1377 i32::from(self.source[(y + row) * self.width + x + col])
1378 - i32::from(prediction[row * side + col]),
1379 );
1380 sse += error * error;
1381 }
1382 }
1383 return Trial {
1384 levels: vec![0i32; side * side],
1385 reconstruction: prediction.to_vec(),
1386 sse,
1387 bits: 0.0,
1388 };
1389 }
1390 let mut residual = [0i32; BLOCK * BLOCK];
1391 let residual = &mut residual[..side * side];
1392 for row in 0..side {
1393 for col in 0..side {
1394 residual[row * side + col] =
1395 i32::from(self.source[(y + row) * self.width + x + col])
1396 - i32::from(prediction[row * side + col]);
1397 }
1398 }
1399 #[cfg(test)]
1400 let t = std::time::Instant::now();
1401 let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone);
1402 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
1403 #[cfg(test)]
1404 stage_add(2, t.elapsed());
1405 let mut reconstruction = vec![0u8; side * side];
1406 let mut sse = 0.0;
1407 for row in 0..side {
1408 for col in 0..side {
1409 let i = row * side + col;
1410 let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;
1411 reconstruction[i] = sample;
1412 let error = f64::from(
1413 i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample),
1414 );
1415 sse += error * error;
1416 }
1417 }
1418 #[cfg(test)]
1419 let t = std::time::Instant::now();
1420 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
1421 levels
1422 .iter()
1423 .filter(|&&level| level != 0)
1424 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
1425 .sum()
1426 } else {
1427 crate::tile::coeff_bits(&levels, set, crate::decode::q_ctx_of(base_q_idx))
1428 };
1429 #[cfg(test)]
1430 stage_add(3, t.elapsed());
1431 Trial {
1432 levels,
1433 reconstruction,
1434 sse,
1435 bits,
1436 }
1437 }
1438
1439 /// Codes this block's luma at transform depth `depth`: the
1440 /// `(side >> depth)^2` transform units in raster order, each predicted
1441 /// from the reconstruction the units before it left behind -- exactly
1442 /// what the decoder's multi-transform-unit branch does (decode.rs
1443 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
1444 /// reconstructed on its own. Commits the result and hands back the
1445 /// block-coordinate levels, the block's squared error and what its
1446 /// coefficients cost.
1447 fn code_tx_depth(
1448 &mut self,
1449 at: At,
1450 mode: u8,
1451 depth: usize,
1452 search: &Search, fctx: &crate::decode::FrameCtx,
1453 ) -> (Vec<i32>, f64, f64) {
1454 let At { x, y, side, reach, .. } = at;
1455 let tx = side >> depth;
1456 let n = 1usize << depth;
1457 let set = match tx {
1458 32 => TxbSet::Luma32,
1459 16 => TxbSet::Luma16,
1460 8 => TxbSet::Luma8,
1461 _ => TxbSet::Luma4,
1462 };
1463 let mut levels = vec![0i32; side * side];
1464 census_add(4, n * n);
1465 let (mut sse, mut bits) = (0.0, 0.0);
1466 for tu_row in 0..n {
1467 for tu_col in 0..n {
1468 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
1469 let tu = At {
1470 x: x + col_off,
1471 y: y + row_off,
1472 side: tx,
1473 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
1474 set,
1475 };
1476 let trial = self.trial(tu, mode, search.base_q_idx, search.deadzone, fctx);
1477 sse += trial.sse;
1478 bits += trial.bits;
1479 self.commit(tu.x, tu.y, tx, &trial);
1480 for row in 0..tx {
1481 levels[(row_off + row) * side + col_off..][..tx]
1482 .copy_from_slice(&trial.levels[row * tx..][..tx]);
1483 }
1484 }
1485 }
1486 (levels, sse, bits)
1487 }
1488
1489 /// Writes a trial's reconstruction back into the plane.
1490 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
1491 for row in 0..side {
1492 self.reconstruction[(y + row) * self.width + x..][..side]
1493 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
1494 }
1495 }
1496
1497 /// The source samples of one square, contiguous — what a motion search
1498 /// compares its candidates' predictions against ([`motion::search`]'s
1499 /// `source`), since [`Self::source`] itself is the whole plane, strided
1500 /// by [`Self::width`].
1501 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
1502 (y..y + side)
1503 .flat_map(|row| self.source[row * self.width + x..][..side].to_vec())
1504 .collect()
1505 }
1506
1507 /// The reconstructed samples of one square, so that a partition trial can
1508 /// be undone.
1509 fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
1510 (y..y + side)
1511 .flat_map(|row| self.reconstruction[row * self.width + x..][..side].to_vec())
1512 .collect()
1513 }
1514
1515 /// Puts a snapshot back.
1516 fn restore(&mut self, x: usize, y: usize, side: usize, samples: &[u8]) {
1517 for row in 0..side {
1518 self.reconstruction[(y + row) * self.width + x..][..side]
1519 .copy_from_slice(&samples[row * side..][..side]);
1520 }
1521 }
1522
1523 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
1524 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
1525 /// prescreen by the identical rule rather than a second one that could
1526 /// drift from it.
1527 fn intra_scores(
1528 &self,
1529 at: At,
1530 modes: &[u8],
1531 mode_bits: &[f64; 13],
1532 lambda: f64, fctx: &crate::decode::FrameCtx,
1533 ) -> Vec<(f64, u8)> {
1534 let At {
1535 x, y, side, reach, ..
1536 } = at;
1537 let (above, left, corner) = self.edges(x, y, side, reach);
1538 modes
1539 .iter()
1540 .map(|&mode| {
1541 let mut prediction = vec![0u8; side * side];
1542 intra_predict_u8(
1543 mode,
1544 0,
1545 above.as_deref(),
1546 left.as_deref(),
1547 corner,
1548 side,
1549 side,
1550 false,
1551 false,
1552 &mut prediction, fctx,
1553 );
1554 let sad: f64 = (0..side * side)
1555 .map(|i| {
1556 let (row, col) = (i / side, i % side);
1557 f64::from(
1558 (i32::from(self.source[(y + row) * self.width + x + col])
1559 - i32::from(prediction[i]))
1560 .abs(),
1561 )
1562 })
1563 .sum();
1564 (sad + lambda * mode_bits[usize::from(mode)], mode)
1565 })
1566 .collect()
1567 }
1568
1569 /// Codes one block under every mode the search offers (or, when
1570 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
1571 /// pre-pass plus DC) and commits the one whose squared error and
1572 /// estimated rate come out cheapest.
1573 ///
1574 /// The prediction is built once per mode regardless -- the full RD trial
1575 /// needs it too -- so ranking modes by SAD on that same prediction before
1576 /// running the expensive part (forward transform, quantize, reconstruct,
1577 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
1578 /// only to sum.
1579 fn search_block(
1580 &mut self,
1581 at: At,
1582 search: &Search,
1583 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
1584 ) -> (Vec<Coeff>, u8, f64) {
1585 let At {
1586 x, y, side, reach, ..
1587 } = at;
1588 let (above, left, corner) = self.edges(x, y, side, reach);
1589 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
1590 // the census reports it), so summing it under the default unpruned
1591 // search is `side * side` absolute differences per mode spent on a
1592 // number no one reads.
1593 let want_sad = search.top_k.is_some() || census_on();
1594 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
1595 .modes
1596 .iter()
1597 .map(|&mode| {
1598 let mut prediction = vec![0u8; side * side];
1599 intra_predict_u8(
1600 mode,
1601 0,
1602 above.as_deref(),
1603 left.as_deref(),
1604 corner,
1605 side,
1606 side,
1607 false,
1608 false,
1609 &mut prediction, fctx,
1610 );
1611 let sad: f64 = if want_sad {
1612 (0..side * side)
1613 .map(|i| {
1614 let (row, col) = (i / side, i % side);
1615 f64::from(
1616 (i32::from(self.source[(y + row) * self.width + x + col])
1617 - i32::from(prediction[i]))
1618 .abs(),
1619 )
1620 })
1621 .sum()
1622 } else {
1623 0.0
1624 };
1625 (
1626 sad + search.lambda * mode_bits[usize::from(mode)],
1627 mode,
1628 prediction,
1629 )
1630 })
1631 .collect();
1632 if let Some(k) = search.top_k {
1633 if k < scored.len() {
1634 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
1635 let dc_entry = dc_pos.map(|i| scored.remove(i));
1636 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
1637 scored.truncate(if dc_entry.is_some() {
1638 k.saturating_sub(1)
1639 } else {
1640 k
1641 });
1642 if let Some(dc_entry) = dc_entry {
1643 scored.push(dc_entry);
1644 }
1645 }
1646 }
1647 let ranking: Vec<(f64, u8)> = if census_on() {
1648 scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
1649 } else {
1650 Vec::new()
1651 };
1652 census_add(0, 1);
1653 census_add(1, scored.len());
1654 let mut best: Option<(f64, u8, Trial)> = None;
1655 for (_, mode, prediction) in scored {
1656 let trial = self.code_from_prediction(
1657 x,
1658 y,
1659 side,
1660 &prediction,
1661 false,
1662 search.base_q_idx,
1663 search.deadzone,
1664 at.set,
1665 );
1666 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
1667 if best
1668 .as_ref()
1669 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
1670 {
1671 best = Some((cost, mode, trial));
1672 }
1673 }
1674 let (cost, mode, trial) = best.expect("the search offers at least one mode");
1675 if census_on() {
1676 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
1677 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1678 }
1679 self.commit(x, y, side, &trial);
1680 (coeffs(&trial.levels, side), mode, cost)
1681 }
1682}
1683
1684/// Where one block sits in its plane, and how far past its own edges its
1685/// prediction may read.
1686#[derive(Clone, Copy)]
1687struct At {
1688 x: usize,
1689 y: usize,
1690 side: usize,
1691 reach: Reach,
1692 /// Which of the tile writer's coefficient tables this block's levels are
1693 /// coded with, and so which the search prices them through.
1694 set: TxbSet,
1695}
1696
1697/// Which of the samples past a block's own edges the decoder has decoded by
1698/// the time it predicts the block, and so which a directional mode may read.
1699///
1700/// The decoder derives these from its `BlockDecoded` flags, which are cleared
1701/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
1702/// that map, this reads the answer the same way libaom and rav1e do: for a
1703/// block whose transform covers it whole, whether the samples above its right
1704/// (or below its left) are decoded depends only on where the block sits inside
1705/// its 64x64 superblock, which is a pinned table per block size.
1706#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1707pub(crate) struct Reach {
1708 pub(crate) above_right: bool,
1709 pub(crate) below_left: bool,
1710}
1711
1712/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
1713/// libaom): for a block that is neither in the superblock's top row nor its
1714/// rightmost column, whether the block above and to its right is coded before
1715/// it. Indexed by the block's position in the superblock, in blocks of its own
1716/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
1717/// 128, not this crate's 64 superblock -- bit by bit from the low end.
1718const HAS_TOP_RIGHT: [&[u8]; 4] = [
1719 &[255, 85, 119, 85, 127, 85, 119, 85],
1720 &[95, 87],
1721 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
1722 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
1723 &[
1724 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
1725 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
1726 ],
1727
1728 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
1729 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
1730 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
1731 // with side 4 outside a TX4 split; without their own row they clamped
1732 // into the 8x8 table and read above-right samples the decoder has not
1733 // written yet (all-zero pixels in the bottom-right triangle of a
1734 // directional 4x4 leaf).
1735 &[
1736 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
1737 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
1738 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
1739 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
1740 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
1741 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
1742 119, 119, 119, 119, 85, 85, 85, 85,
1743 ],
1744];
1745
1746/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
1747/// left.
1748const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
1749 &[84, 16, 84, 0, 84, 16, 84, 0],
1750 &[4, 4],
1751 // has_bl_8x8 (libaom av1/common/reconintra.c)
1752 &[
1753 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
1754 84, 85, 16, 17, 84, 85, 0, 0,
1755 ],
1756
1757 // has_bl_4x4 (same source, same order).
1758 &[
1759 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
1760 84, 85, 85, 85, 0, 0, 1, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84,
1761 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
1762 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 1, 0, 84, 85,
1763 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
1764 85, 85, 0, 0, 0, 0,
1765 ],
1766];
1767
1768/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
1769/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
1770/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
1771/// rather than in raster order, so the bottom-left square's top-right
1772/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
1773/// libaom switches tables on the partition type (`get_has_tr_table`); the
1774/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
1775/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
1776/// lane-part32 r5 caught reading undecoded samples.
1777const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
1778 // has_tr_vert_16x16
1779 &[255, 0, 119, 0, 127, 0, 119, 0],
1780 // has_tr_vert_32x32
1781 &[15, 7],
1782 // has_tr_vert_8x8
1783 &[
1784 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
1785 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
1786 ],
1787];
1788
1789/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
1790const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
1791 // has_bl_vert_16x16
1792 &[254, 16, 254, 0, 254, 16, 254, 0],
1793 // has_bl_vert_32x32
1794 &[14, 14],
1795 // has_bl_vert_8x8
1796 &[
1797 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
1798 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
1799 ],
1800];
1801
1802thread_local! {
1803 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
1804 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
1805 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
1806 /// threading one bool through this crate's already twenty-argument
1807 /// `decode_block` would touch every call site instead of the two arms
1808 /// that need it.
1809 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1810}
1811
1812/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
1813pub(crate) struct VertAbGuard(bool);
1814
1815impl Drop for VertAbGuard {
1816 fn drop(&mut self) {
1817 VERT_AB_PARTITION.with(|c| c.set(self.0));
1818 }
1819}
1820
1821/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
1822/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
1823/// so no byte is retyped). Each is indexed by
1824/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
1825/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
1826/// superblock grid; on this crate's 64-pixel superblock the highest index a
1827/// shape can reach stays inside its own table, so no wrap is involved.
1828///
1829/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
1830/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
1831/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
1832/// 10 of the 21 reachable superblock positions for above-right and 7 for
1833/// below-left.
1834/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
1835const HAS_TR_4X8: [u8; 64] = [255, 255, 255, 255, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 255, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119, 255, 127, 255, 127, 119, 119, 119, 119, 127, 127, 127, 127, 119, 119, 119, 119];
1836/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
1837const HAS_BL_4X8: [u8; 64] = [16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 1, 0, 16, 17, 17, 17, 0, 1, 1, 1, 16, 17, 17, 17, 0, 0, 0, 0];
1838/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
1839const HAS_TR_8X4: [u8; 64] = [255, 255, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 255, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0, 127, 127, 0, 0, 85, 85, 0, 0, 119, 119, 0, 0, 85, 85, 0, 0];
1840/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
1841const HAS_BL_8X4: [u8; 64] = [254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 1, 254, 255, 84, 85, 254, 255, 16, 17, 254, 255, 84, 85, 254, 255, 0, 0];
1842/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
1843const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119];
1844/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
1845const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
1846/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
1847const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
1848/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
1849const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0];
1850/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
1851const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
1852/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
1853const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
1854/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
1855const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
1856/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
1857const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
1858/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
1859const HAS_TR_32X64: [u8; 1] = [127];
1860/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
1861const HAS_BL_32X64: [u8; 1] = [0];
1862/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
1863const HAS_TR_64X32: [u8; 1] = [19];
1864/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
1865const HAS_BL_64X32: [u8; 1] = [34];
1866/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
1867const HAS_TR_4X16: [u8; 32] = [255, 255, 255, 255, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127, 255, 255, 255, 127, 127, 127, 127, 127, 255, 127, 255, 127, 127, 127, 127, 127];
1868/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
1869const HAS_BL_4X16: [u8; 32] = [0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0];
1870/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
1871const HAS_TR_16X4: [u8; 32] = [255, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0, 127, 0, 0, 0, 85, 0, 0, 0, 119, 0, 0, 0, 85, 0, 0, 0];
1872/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
1873const HAS_BL_16X4: [u8; 32] = [254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0, 254, 254, 254, 84, 254, 254, 254, 16, 254, 254, 254, 84, 254, 254, 254, 0];
1874/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
1875const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
1876/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
1877const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
1878/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
1879const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
1880/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
1881const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
1882/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
1883const HAS_TR_16X64: [u8; 2] = [255, 127];
1884/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
1885const HAS_BL_16X64: [u8; 2] = [0, 0];
1886/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
1887const HAS_TR_64X16: [u8; 2] = [3, 1];
1888/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
1889const HAS_BL_64X16: [u8; 2] = [42, 42];
1890
1891/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
1892fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
1893 match (bw, bh) {
1894 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
1895 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
1896 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
1897 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
1898 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
1899 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
1900 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
1901 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
1902 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
1903 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
1904 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
1905 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
1906 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
1907 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
1908 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
1909 }
1910}
1911
1912impl Reach {
1913 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
1914 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
1915 /// own answer is `block` -- a different rule from the standalone-block
1916 /// tables, because a unit's neighbours are mostly its own block's
1917 /// already-reconstructed units:
1918 /// * top-right: available while the unit to the right is still inside
1919 /// the block (`col_off + tx < bw`); otherwise only the block's top row
1920 /// of units reaches past it, through the block-level answer
1921 /// (libaom's `row_off > 0` branch returns exactly
1922 /// `col_off + txw < plane_bw`).
1923 /// * bottom-left: a unit outside the block's left column has none
1924 /// (libaom returns 0 for `col_off > 0`); inside the block
1925 /// (`row_off + tx < bh`) they are the left unit's, already
1926 /// reconstructed; the bottom row falls back to the block-level answer.
1927 pub(crate) fn of_tu(
1928 bw: usize,
1929 bh: usize,
1930 col_off: usize,
1931 row_off: usize,
1932 // The unit's own width and height in pixels; equal for a square
1933 // transform, different for the rect unit a 1:4 strip's first split
1934 // produces (lane-rectsplitx r1).
1935 tx_w: usize,
1936 tx_h: usize,
1937 block: Self,
1938 ) -> Self {
1939 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
1940 // order, so both libaom predicates special-case it (lane-sb128c r10);
1941 // without this the last unit column of every chunk of a 128x64 block
1942 // predicts from a chunk libaom has not decoded yet.
1943 let wide = bw > 64;
1944 Self {
1945 above_right: if row_off > 0 {
1946 // `has_top_right`'s `row_off > 0` branch: the offset is taken
1947 // modulo the 64-wide chunk, except for the one unit whose
1948 // top-right corner is the centre of a 128x128 block.
1949 if wide {
1950 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
1951 } else {
1952 col_off + tx_w < bw
1953 }
1954 } else if col_off + tx_w < bw {
1955 true
1956 } else {
1957 block.above_right
1958 },
1959 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
1960 // `has_bottom_left`: at the left edge of a right-hand chunk
1961 // the bottom-left pixels are in the already-coded left chunk,
1962 // provided they stay inside it.
1963 (row_off % 64) + tx_h < bh.min(64)
1964 } else if col_off > 0 {
1965 false
1966 } else if row_off + tx_h < bh {
1967 true
1968 } else {
1969 block.below_left
1970 },
1971 }
1972 }
1973
1974 /// What a block of `side` samples at `(x, y)` may read past its own edges,
1975 /// in a frame of `width` by `height`.
1976 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
1977 Self {
1978 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
1979 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
1980 }
1981 }
1982
1983 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
1984 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
1985 /// block's own width for the row stride and by its own height for the
1986 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
1987 /// unlike the square [`Self::of`] which uses one `side` for everything.
1988 pub(crate) fn of_rect(
1989 bw: usize,
1990 bh: usize,
1991 x: usize,
1992 y: usize,
1993 width: usize,
1994 height: usize, fctx: &crate::decode::FrameCtx,
1995 ) -> Self {
1996 Self {
1997 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
1998 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
1999 }
2000 }
2001
2002 /// [`Self::of`] for one transform unit of a square block whose transform
2003 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
2004 /// non-zero `row_off`/`col_off`): interior units answer from the block's
2005 /// own geometry, and only a unit on the block's top row (resp. left
2006 /// column) reaches the table -- which is the BLOCK's table read at the
2007 /// BLOCK's position, never a table row for the transform's size. Letting
2008 /// the unit stand in for a block of its own size agrees with libaom for
2009 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
2010 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
2011 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
2012 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
2013 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
2014 /// the transform covering the whole block, luma): everything before the
2015 /// table lookup is that function's own early-exit ladder.
2016 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2017 let sb_mi: usize = reach_sb_px(fctx) / 4;
2018 let (mi_row, mi_col) = (y / 4, x / 4);
2019 let bw_log2 = (bw / 4).trailing_zeros() as usize;
2020 let bh_log2 = (bh / 4).trailing_zeros() as usize;
2021 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
2022 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
2023 // Top row of the superblock: the top-right pixels are in the (already
2024 // decoded) superblock above.
2025 if blk_row == 0 {
2026 return true;
2027 }
2028 // Rightmost column: they fall in the superblock to the right.
2029 if ((blk_col + 1) << bw_log2) >= sb_mi {
2030 return false;
2031 }
2032 let table = rect_reach_tables(bw, bh).0;
2033 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
2034 }
2035
2036 /// libaom `has_top_right`'s own index arithmetic:
2037 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
2038 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
2039 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
2040 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
2041 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
2042 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
2043 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
2044 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
2045 (blk_row << (5 - bw_log2)) + blk_col
2046 }
2047
2048 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
2049 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2050 let sb_mi: usize = reach_sb_px(fctx) / 4;
2051 let (mi_row, mi_col) = (y / 4, x / 4);
2052 let bw_log2 = (bw / 4).trailing_zeros() as usize;
2053 let bh_log2 = (bh / 4).trailing_zeros() as usize;
2054 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
2055 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
2056 // Leftmost column of the superblock: the bottom-left pixels are in
2057 // the left superblock iff they stay inside its height.
2058 if blk_col == 0 {
2059 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
2060 }
2061 // Bottom row (and not the leftmost column): they fall in the
2062 // superblock below, which is not decoded yet.
2063 if ((blk_row + 1) << bh_log2) >= sb_mi {
2064 return false;
2065 }
2066 let table = rect_reach_tables(bw, bh).1;
2067 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
2068 }
2069
2070 /// Marks every [`Reach::of`] made until the returned guard drops as being
2071 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
2072 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
2073 /// unaffected: libaom's own comment says vertical rectangles keep their
2074 /// non-vert table, which is what [`Reach::of_rect`] already reads.
2075 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
2076 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
2077 /// can count the sub-block work that partition creates (lane-ab16).
2078 pub(crate) fn in_vert_ab() -> bool {
2079 VERT_AB_PARTITION.with(std::cell::Cell::get)
2080 }
2081
2082 pub(crate) fn vert_ab_partition() -> VertAbGuard {
2083 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
2084 }
2085
2086 /// Neither, which is all a mode that reads no further than its own edges
2087 /// needs.
2088 pub(crate) fn none() -> Self {
2089 Self {
2090 above_right: false,
2091 below_left: false,
2092 }
2093 }
2094
2095 /// `has_top_right` for a block whose transform covers it whole: the top
2096 /// row of a superblock reads into the superblock above, which is decoded;
2097 /// the rightmost column would read into the superblock to the right, which
2098 /// is not; and everything between is the table's to answer.
2099 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2100 let (row, col, per_side) = Self::position(side, x, y, fctx);
2101 if row == 0 {
2102 return true;
2103 }
2104 if col + 1 == per_side {
2105 return false;
2106 }
2107 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
2108 // (the clamp corner-cut that used to live here is gone); sides
2109 // 16/32/64 share row 0 exactly as libaom's tables repeat.
2110 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
2111 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
2112 // -- a reach over-estimate (extra above-right reference pixels),
2113 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
2114 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
2115 // NB: named `table_row`, not `row` -- `row` above is the block's
2116 // position inside the superblock and is what the bit index below
2117 // steps by (a merge that shadowed it desynced every block size).
2118 let table_row = Self::table(side);
2119 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() {
2120 HAS_TOP_RIGHT_VERT[table_row]
2121 } else {
2122 HAS_TOP_RIGHT[table_row]
2123 };
2124 Self::bit(
2125 table,
2126 (row * Self::table_stride(side) + col) % (table.len() * 8),
2127 )
2128 }
2129
2130 /// `has_bottom_left` for such a block: the leftmost column of a superblock
2131 /// reads into the superblock to its left, which is decoded only as far
2132 /// down as its own bottom; the bottom row would read into the superblock
2133 /// below, which is not decoded at all; and the table answers the rest.
2134 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2135 let (row, col, per_side) = Self::position(side, x, y, fctx);
2136 if col == 0 {
2137 return row * side + side < reach_sb_px(fctx);
2138 }
2139 if row + 1 == per_side {
2140 return false;
2141 }
2142 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
2143 // (the clamp corner-cut that used to live here is gone); sides
2144 // 16/32/64 share row 0 exactly as libaom's tables repeat.
2145 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
2146 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
2147 // -- a reach over-estimate (extra above-right reference pixels),
2148 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
2149 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
2150 // NB: named `table_row`, not `row` -- `row` above is the block's
2151 // position inside the superblock and is what the bit index below
2152 // steps by (a merge that shadowed it desynced every block size).
2153 let table_row = Self::table(side);
2154 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() {
2155 HAS_BOTTOM_LEFT_VERT[table_row]
2156 } else {
2157 HAS_BOTTOM_LEFT[table_row]
2158 };
2159 Self::bit(
2160 table,
2161 (row * Self::table_stride(side) + col) % (table.len() * 8),
2162 )
2163 }
2164
2165 /// Where a block sits inside its superblock, in blocks of its own size,
2166 /// and how many of them a superblock is across.
2167 fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
2168 let sb = reach_sb_px(fctx);
2169 ((y % sb) / side, (x % sb) / side, sb / side)
2170 }
2171
2172 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
2173 /// these tables to its compile-time maximum superblock (128, spec
2174 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
2175 /// size an encode actually uses, so a block's row in the bit index steps
2176 /// by 128 / `side` even though this crate only ever codes a 64
2177 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
2178 /// here instead indexes the wrong bit for every block size but the one
2179 /// where 64 and 128 give the same stride.
2180 fn table_stride(side: usize) -> usize {
2181 128 / side
2182 }
2183
2184 /// Which of the three block sizes the encoder codes a table row is for.
2185 fn table(side: usize) -> usize {
2186 if side == BLOCK {
2187 1
2188 } else if side == 8 {
2189 2
2190 } else if side == 4 {
2191 3
2192 } else {
2193 0
2194 }
2195 }
2196
2197 /// One bit of a table, counting from the low end of its first byte.
2198 fn bit(table: &[u8], index: usize) -> bool {
2199 (table[index / 8] >> (index % 8)) & 1 != 0
2200 }
2201}
2202
2203/// What one symbol costs against a CDF, in bits.
2204pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
2205 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
2206 let width = cdf[symbol] - low;
2207 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
2208 // 32769 prices a symbol can carry; the `log2` behind each is computed
2209 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
2210 // profile -- this function is called for every symbol of every candidate
2211 // the RD search prices). Each entry is exactly the expression this used
2212 // to evaluate, so every price is bit-identical.
2213 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
2214 PRICES.get_or_init(|| {
2215 (0..=32768u32)
2216 .map(|w| -(f64::from(w) / 32768.0).log2())
2217 .collect()
2218 })[usize::from(width)]
2219}
2220
2221/// What the tile writer spends to say a block is coded in each of the thirteen
2222/// modes, given the modes of the blocks above it and to its left: the luma mode
2223/// symbol against the CDF those two neighbours pick, the angle delta a
2224/// directional mode carries, and the chroma mode symbol, whose CDF the luma
2225/// mode itself indexes.
2226///
2227/// Without this the search is blind to what a mode costs to name, which is not
2228/// a rounding error: a directional mode on a picture that does not run that way
2229/// is a rate loss the squared error never sees.
2230/// Codes one square of the picture as a single block: searches the luma mode,
2231/// codes both chroma planes DC, and hands back the block and what it cost --
2232/// squared error plus lambda times the bits its symbols spend.
2233/// How many halvings of a `side`-square block's transform the `tx_depth`
2234/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
2235/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
2236fn max_tx_depth(side: usize) -> usize {
2237 match side {
2238 8 => 1,
2239 16 | 32 => 2,
2240 _ => 0,
2241 }
2242}
2243
2244/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
2245/// Priced at context row 0 -- the writer picks the real row from its
2246/// neighbours' transform sizes, which the search has no view of; the term is
2247/// the same for every depth of one block either way, so it only shifts the
2248/// depth-0-versus-split margin, never the ordering between two splits.
2249fn tx_depth_bits(side: usize, depth: usize) -> f64 {
2250 match side {
2251 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
2252 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
2253 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
2254 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
2255 }
2256}
2257
2258/// How many blocks resolved to each `tx_depth`, the fire count that says
2259/// whether the depth search below reaches its candidates at all.
2260static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
2261 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
2262
2263/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
2264/// to its own encode.
2265#[cfg(test)]
2266pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
2267 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
2268}
2269
2270/// How many inter blocks resolved to each var-tx depth (0 = one transform
2271/// over the whole block, 1 = its four halves), the fire count a gate prints
2272/// to see the split search reach its candidates at all.
2273static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 2] =
2274 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
2275
2276/// How many 32x32-and-below inter blocks each reference frame won, indexed by
2277/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
2278/// fire count a gate prints to see an extra reference reach a block at all
2279/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
2280/// chosen is a pyramid that costs bytes and buys nothing).
2281static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
2282 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
2283
2284/// Reads [`REF_FRAME_HITS`] and zeroes it.
2285#[cfg(test)]
2286pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
2287 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
2288}
2289
2290/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
2291#[cfg(test)]
2292pub(crate) fn take_inter_tx_split_hits() -> [usize; 2] {
2293 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
2294}
2295
2296/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
2297/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
2298/// is one flag, depth 1 is a split root plus one unsplit flag per child
2299/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
2300/// or a 4x4 sub-size).
2301fn txfm_split_bits(side: usize, depth: usize) -> f64 {
2302 let max_tx = side.min(64);
2303 let ctx = |tx: usize| {
2304 crate::decode::txfm_partition_ctx_rect(
2305 crate::decode::TXFM_CTX_INIT,
2306 crate::decode::TXFM_CTX_INIT,
2307 side,
2308 tx,
2309 tx,
2310 )
2311 };
2312 if depth == 0 {
2313 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
2314 }
2315 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
2316 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
2317}
2318
2319/// The inter block's own var-tx decision, once its motion vector is settled:
2320/// its residual as ONE transform over the whole block, or as the four
2321/// transforms of half the side the tree's first halving names. The prediction
2322/// is the same motion compensation either way, so the split trial
2323/// re-transforms the identical residual in four pieces -- it wins where four
2324/// small transforms carry a locally varying residual cheaper than one big
2325/// one. Commits the winner into `luma` and hands back its block-coordinate
2326/// levels, the depth the writer codes and the cost the winner adds to (or
2327/// takes off) the caller's already-computed flat cost.
2328///
2329/// Only for a block wholly inside the frame: past the true edge the reader's
2330/// var-tx recursion skips the units that fall outside
2331/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
2332/// leave the residual units this writes unpaired.
2333#[allow(clippy::too_many_arguments)]
2334fn commit_inter_luma(
2335 luma: &mut Plane,
2336 (x, y): (usize, usize),
2337 side: usize,
2338 mv: (i32, i32),
2339 reference: (&[u16], usize, usize, usize),
2340 search: &Search,
2341 flat: &Trial,
2342 skip: bool, fctx: &crate::decode::FrameCtx,
2343) -> (Vec<i32>, u8, f64) {
2344 let eligible = tx_select()
2345 && tx_select_inter()
2346 && !skip
2347 && side >= 16
2348 && x + side <= luma.true_width
2349 && y + side <= luma.true_height;
2350 if !eligible {
2351 luma.commit(x, y, side, flat);
2352 return (flat.levels.clone(), 0, 0.0);
2353 }
2354 let tx = side / 2;
2355 let set = if tx >= 16 { TxbSet::Luma16Inter } else { TxbSet::Luma8Inter };
2356 let mut levels = vec![0i32; side * side];
2357 let (mut sse, mut bits) = (0.0, 0.0);
2358 let mut units = Vec::with_capacity(4);
2359 for tu_row in 0..2 {
2360 for tu_col in 0..2 {
2361 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
2362 let trial = mc_trial(
2363 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
2364 reference.3, false, search.base_q_idx, search.deadzone, set, fctx,
2365 );
2366 sse += trial.sse;
2367 bits += trial.bits;
2368 for row in 0..tx {
2369 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
2370 .copy_from_slice(&trial.levels[row * tx..][..tx]);
2371 }
2372 units.push((tu_x, tu_y, trial));
2373 }
2374 }
2375 let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1));
2376 let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0));
2377 if split_cost < flat_cost {
2378 for (tu_x, tu_y, trial) in &units {
2379 luma.commit(*tu_x, *tu_y, tx, trial);
2380 }
2381 INTER_TX_SPLIT_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2382 return (levels, 1, split_cost - flat_cost);
2383 }
2384 INTER_TX_SPLIT_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2385 luma.commit(x, y, side, flat);
2386 (flat.levels.clone(), 0, 0.0)
2387}
2388
2389/// The largest distinct-colour count a block may hold and still be offered a
2390/// palette candidate at all: past it the k-means quantisation costs more
2391/// error than the map saves rate, and every trial is wasted wall.
2392///
2393/// Swept on the gate's own screen capture (lane-av1pal2, the
2394/// `unswept-decision-constants` class): 32 (the value this lane inherited)
2395/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
2396/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
2397/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
2398/// binds on nothing this content holds. 128 ships: best BD against both
2399/// references and no wall cost at all (6.1s, the same as at 32, because the
2400/// blocks it newly admits are ones the RD then keeps).
2401/// `EC_AV1_PAL_MAXCOLORS`.
2402fn palette_max_colors() -> usize {
2403 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2404 *N.get_or_init(|| {
2405 std::env::var("EC_AV1_PAL_MAXCOLORS")
2406 .ok()
2407 .and_then(|v| v.parse().ok())
2408 .unwrap_or(128)
2409 })
2410}
2411
2412/// The palettes worth trying for one block's luma, in the shape libaom's
2413/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
2414/// distinct colours takes them ALL (the prediction is then exact and the
2415/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
2416/// one-dimensional Lloyd iteration seeded evenly across its range -- both
2417/// offered, because which wins is an RD question the caller answers.
2418/// `block` is `side*side` source samples, row-major.
2419fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
2420 let mut histogram = [0u32; 256];
2421 for &v in block {
2422 histogram[usize::from(v)] += 1;
2423 }
2424 let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
2425 if present.len() < 2 {
2426 return Vec::new();
2427 }
2428 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
2429 let mut base = [0u16; 8];
2430 base[..colors.len()].copy_from_slice(colors);
2431 let map = block
2432 .iter()
2433 .map(|&v| {
2434 colors
2435 .iter()
2436 .enumerate()
2437 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
2438 .map(|(i, _)| i as u8)
2439 .expect("a palette holds at least two colours")
2440 })
2441 .collect();
2442 crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
2443 };
2444 if present.len() <= 8 {
2445 return vec![exact(&present)];
2446 }
2447 if present.len() > palette_max_colors() {
2448 return Vec::new();
2449 }
2450 let (lo, hi) = (
2451 i32::from(present[0]),
2452 i32::from(present[present.len() - 1]),
2453 );
2454 let mut out = Vec::with_capacity(2);
2455 for n in [8usize, 4] {
2456 // Even seeding across the block's own range, then four Lloyd passes
2457 // over the histogram (256 bins, not `side*side` pixels).
2458 let mut centres: Vec<f64> = (0..n)
2459 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
2460 .collect();
2461 for _ in 0..4 {
2462 let mut sums = vec![0f64; n];
2463 let mut counts = vec![0u32; n];
2464 for (v, &count) in histogram.iter().enumerate() {
2465 if count == 0 {
2466 continue;
2467 }
2468 let k = (0..n)
2469 .min_by(|&a, &b| {
2470 (centres[a] - v as f64)
2471 .abs()
2472 .total_cmp(&(centres[b] - v as f64).abs())
2473 })
2474 .expect("n >= 2");
2475 sums[k] += (v as u32 * count) as f64;
2476 counts[k] += count;
2477 }
2478 for k in 0..n {
2479 if counts[k] > 0 {
2480 centres[k] = sums[k] / f64::from(counts[k]);
2481 }
2482 }
2483 }
2484 let mut colors: Vec<u16> = centres
2485 .iter()
2486 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
2487 .collect();
2488 colors.sort_unstable();
2489 colors.dedup();
2490 if colors.len() >= 2 {
2491 out.push(exact(&colors));
2492 }
2493 }
2494 out
2495}
2496
2497#[allow(clippy::too_many_arguments)]
2498fn code_square(
2499 luma: &mut Plane,
2500 chroma: &mut [Plane; 2],
2501 (x, y): (usize, usize),
2502 side: usize,
2503 search: &Search,
2504 mode_bits: &[f64; 13],
2505 // The frame header's `tx_mode == TxMode::Select`: the block then searches
2506 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
2507 // transform over its whole side.
2508 tx_select: bool, fctx: &crate::decode::FrameCtx,
2509) -> (BlockCoeffs, f64) {
2510 let (luma_set, chroma_set) = if side == BLOCK {
2511 (TxbSet::Luma32, TxbSet::Chroma16)
2512 } else if side == 8 {
2513 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
2514 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
2515 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
2516 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
2517 // (this branch is still unreached), so leaving `Chroma8` here would
2518 // silently wire the wrong table the moment one does; `Chroma4` is
2519 // what a real caller needs.
2520 (TxbSet::Luma8, TxbSet::Chroma4)
2521 } else {
2522 (TxbSet::Luma16, TxbSet::Chroma8)
2523 };
2524 let at = At {
2525 x,
2526 y,
2527 side,
2528 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
2529 set: luma_set,
2530 };
2531 let (mut luma_coeffs, mode, mut cost) = luma.search_block(at, search, mode_bits, fctx);
2532 // The depth search runs on the mode the whole-block transform picked --
2533 // libaom's own ordering, and the reason it costs one extra pass per depth
2534 // rather than one per (mode, depth) pair.
2535 let mut tx_depth = 0u8;
2536 if tx_select && max_tx_depth(side) > 0 {
2537 let mut best = (
2538 cost + search.lambda * tx_depth_bits(side, 0),
2539 0usize,
2540 luma.snapshot(x, y, side),
2541 luma_coeffs,
2542 );
2543 for depth in 1..=max_tx_depth(side) {
2544 let (levels, sse, bits) = luma.code_tx_depth(at, mode, depth, search, fctx);
2545 let cost_d = sse
2546 + search.lambda
2547 * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth));
2548 if cost_d < best.0 {
2549 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
2550 }
2551 }
2552 luma.restore(x, y, side, &best.2);
2553 cost = best.0;
2554 tx_depth = best.1 as u8;
2555 luma_coeffs = best.3;
2556 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2557 }
2558 // The palette candidate is priced against the mode the luma search (and
2559 // its transform-depth search) already settled on, so a block only takes
2560 // one when it beats the best ordinary intra coding of the same pixels.
2561 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
2562 // prediction is the colour map, not the DC of its neighbours.
2563 let mut mode = mode;
2564 let mut palette = None;
2565 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
2566 let source: Vec<u8> = (y..y + side)
2567 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
2568 .collect();
2569 let kept = luma.snapshot(x, y, side);
2570 for pal in palette_candidates(&source) {
2571 let n = usize::from(pal.size);
2572 let prediction: Vec<u8> = pal
2573 .map
2574 .iter()
2575 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
2576 .collect();
2577 let trial = luma.code_from_prediction(
2578 x,
2579 y,
2580 side,
2581 &prediction,
2582 false,
2583 search.base_q_idx,
2584 search.deadzone,
2585 luma_set,
2586 );
2587 let cost_p = trial.sse
2588 + search.lambda
2589 * (trial.bits
2590 + mode_bits[DC_PRED as usize]
2591 + crate::tile::palette_bits(&pal, side)
2592 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
2593 if cost_p < cost {
2594 cost = cost_p;
2595 mode = DC_PRED as u8;
2596 tx_depth = 0;
2597 luma_coeffs = coeffs(&trial.levels, side);
2598 luma.commit(x, y, side, &trial);
2599 palette = Some(pal);
2600 }
2601 }
2602 if palette.is_none() {
2603 luma.restore(x, y, side, &kept);
2604 }
2605 }
2606
2607 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
2608 // planes; what it costs still counts towards the partition decision.
2609 let ([u, v], uv_mode, chroma_cost, palette_uv) =
2610 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);
2611 cost += chroma_cost;
2612 (
2613 BlockCoeffs {
2614 u,
2615 v,
2616 luma: luma_coeffs,
2617 mode,
2618 uv_mode,
2619 tx_depth,
2620 palette,
2621 palette_uv,
2622 ..BlockCoeffs::default()
2623 },
2624 cost,
2625 )
2626}
2627
2628/// The chroma modes the search offers, and the only ones it may offer: each
2629/// predicts from the row directly above and the column directly to the left
2630/// and nothing further, so none of them needs the above-right/below-left
2631/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
2632/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
2633/// reconstruction and its own alpha syntax; both are left out here.
2634const CHROMA_MODES: [u8; 7] = [
2635 DC_PRED,
2636 V_PRED,
2637 H_PRED,
2638 SMOOTH_PRED,
2639 SMOOTH_V_PRED,
2640 SMOOTH_H_PRED,
2641 PAETH_PRED,
2642];
2643
2644/// The thirteen intra mode names, for the chroma fire count's print.
2645#[cfg(test)]
2646const UV_MODE_NAMES: [&str; 13] = [
2647 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
2648 "SMOOTH_H", "PAETH",
2649];
2650
2651/// How many blocks each chroma mode has won, indexed by the mode itself --
2652/// the fire count that says whether the search below reaches its candidates
2653/// at all (the `gate-blind-to-feature` class), printed once per gate run.
2654static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 13] =
2655 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
2656
2657/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
2658/// to its own encode.
2659#[cfg(test)]
2660pub(crate) fn take_uv_mode_hits() -> [usize; 13] {
2661 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
2662}
2663
2664/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
2665/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
2666/// Returns each plane's levels, the mode, and what the pair cost (squared
2667/// error plus lambda times bits, the same currency the luma search speaks).
2668///
2669/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
2670/// which is what the luma mode decision was taken against, so what a
2671/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
2672/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
2673/// writer then has to code.
2674#[allow(clippy::too_many_arguments)]
2675/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
2676/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
2677/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
2678/// trials all seven, as before this lever.
2679///
2680/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
2681/// the search's largest trial population by far -- seven modes times two
2682/// planes for every intra block, against 3.7 luma trials -- and the RD
2683/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
2684/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
2685fn chroma_top_k() -> Option<usize> {
2686 static K: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
2687 *K.get_or_init(|| match std::env::var("EC_AV1_CHROMA_K").ok() {
2688 Some(v) => v.parse::<usize>().ok().filter(|&k| k > 0),
2689 None => CHROMA_TOP_K,
2690 })
2691}
2692
2693/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
2694/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
2695/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
2696/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
2697/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
2698/// BD swings by about a point in either direction as near-tie chroma modes
2699/// flip, which is the measurement's own sensitivity, not a trend: nothing
2700/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
2701const CHROMA_TOP_K: Option<usize> = None;
2702
2703fn search_chroma(
2704 chroma: &mut [Plane; 2],
2705 (x, y): (usize, usize),
2706 side: usize,
2707 set: TxbSet,
2708 search: &Search,
2709 luma_mode: u8,
2710 fctx: &crate::decode::FrameCtx,
2711) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) {
2712 let at = At {
2713 x: x / 2,
2714 y: y / 2,
2715 side: side / 2,
2716 reach: Reach::none(),
2717 set,
2718 };
2719 // The census's cheap proxy for a chroma mode: the SAD of its prediction
2720 // summed over both planes, ranked by the same rule the luma histogram
2721 // uses. Only built under `EC_AV1_CENSUS`.
2722 // The SAD of each mode's prediction, summed over both planes -- the
2723 // census's ranking rule, and what [`chroma_top_k`] prunes by.
2724 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
2725 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
2726 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
2727 u.iter()
2728 .zip(v.iter())
2729 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
2730 .collect()
2731 };
2732 let modes: Vec<u8> = match chroma_top_k() {
2733 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
2734 _ => CHROMA_MODES.to_vec(),
2735 };
2736 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
2737 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
2738 let ranking: Vec<(f64, u8)> = if census_on() {
2739 sad_scores(chroma)
2740 } else {
2741 Vec::new()
2742 };
2743 census_add(2, 1);
2744 census_add(3, modes.len());
2745 let mut best: Option<(f64, u8, Trial, Trial)> = None;
2746 for mode in modes {
2747 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
2748 if (V_PRED..=D67_PRED).contains(&mode) {
2749 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
2750 }
2751 let tx_type = crate::decode::default_intra_tx_type(mode);
2752 let u = chroma[0].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx);
2753 let v = chroma[1].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx);
2754 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
2755 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
2756 best = Some((cost, mode, u, v));
2757 }
2758 }
2759 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
2760 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
2761 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
2762 // what keeps `u_colors` ascending and distinct the way
2763 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
2764 // each cluster's own mean, since the colour-index map is SHARED by the
2765 // two planes. Priced against the best ordinary chroma mode above, so a
2766 // block only takes one when it beats it; a palette block's chroma mode is
2767 // `UV_DC_PRED` by construction.
2768 let mut palette_uv = None;
2769 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
2770 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
2771 let plane_source = |p: &Plane| -> Vec<u8> {
2772 (at.y..at.y + at.side)
2773 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
2774 .collect()
2775 };
2776 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
2777 for pal in palette_candidates(&u_source) {
2778 let n = usize::from(pal.size);
2779 // V's base colour per cluster: the mean of the samples the shared
2780 // map assigns to it (an empty cluster cannot happen -- every
2781 // colour `palette_candidates` returns is some pixel's nearest).
2782 let mut sums = [0u32; 8];
2783 let mut counts = [0u32; 8];
2784 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
2785 let k = usize::from(i).min(n - 1);
2786 sums[k] += u32::from(sample);
2787 counts[k] += 1;
2788 }
2789 let mut v_colors = [0u16; 8];
2790 for k in 0..n {
2791 v_colors[k] = if counts[k] > 0 {
2792 ((sums[k] + counts[k] / 2) / counts[k]) as u16
2793 } else {
2794 0
2795 };
2796 }
2797 let candidate = crate::tile::PaletteUv {
2798 size: pal.size,
2799 u_colors: pal.colors,
2800 v_colors,
2801 map: pal.map,
2802 };
2803 let predict = |colors: &[u16; 8]| -> Vec<u8> {
2804 candidate
2805 .map
2806 .iter()
2807 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
2808 .collect()
2809 };
2810 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
2811 let u_trial = chroma[0].code_from_prediction(
2812 at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
2813 );
2814 let v_trial = chroma[1].code_from_prediction(
2815 at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
2816 );
2817 let cost_p = u_trial.sse
2818 + v_trial.sse
2819 + search.lambda
2820 * (u_trial.bits
2821 + v_trial.bits
2822 + crate::tile::palette_uv_bits(&candidate, side));
2823 if cost_p < cost {
2824 cost = cost_p;
2825 mode = DC_PRED;
2826 u = u_trial;
2827 v = v_trial;
2828 palette_uv = Some(candidate);
2829 }
2830 }
2831 }
2832 if census_on() {
2833 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
2834 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2835 }
2836 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2837 chroma[0].commit(at.x, at.y, at.side, &u);
2838 chroma[1].commit(at.x, at.y, at.side, &v);
2839 (
2840 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
2841 mode,
2842 cost,
2843 palette_uv,
2844 )
2845}
2846
2847/// Codes one leaf of a straddling quadrant as whichever costs least of intra
2848/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
2849/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
2850/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
2851/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
2852/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
2853/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
2854/// attempted here: these leaves only ever fill the sliver of real content a
2855/// true edge lands in the middle of a larger block, not a leaf worth a full
2856/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
2857/// (see `write_inter_frame_leaf`'s doc comment).
2858#[allow(clippy::too_many_arguments)]
2859fn code_square_inter(
2860 luma: &mut Plane,
2861 chroma: &mut [Plane; 2],
2862 (x, y): (usize, usize),
2863 side: usize,
2864 search: &Search,
2865 mode_bits: &[f64; 13],
2866 reference: &Picture,
2867 stack: &MvStack,
2868 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
2869 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
2870 // `reference_select`, and at the straddling call sites).
2871 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
2872 fctx: &crate::decode::FrameCtx,
2873) -> (BlockCoeffs, f64) {
2874 let (intra_block, intra_cost) =
2875 code_square(
2876 luma,
2877 chroma,
2878 (x, y),
2879 side,
2880 search,
2881 mode_bits,
2882 tx_select() && tx_select_inter(),
2883 fctx,
2884 );
2885 let luma_set = if side == 8 {
2886 TxbSet::Luma8Inter
2887 } else {
2888 TxbSet::Luma16Inter
2889 };
2890 let chroma_set = if side == 8 {
2891 TxbSet::Chroma4
2892 } else {
2893 TxbSet::Chroma8
2894 };
2895
2896 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
2897 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
2898 let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0)
2899 + symbol_bits(&cdf::SINGLE_REF[0][2], 0)
2900 + symbol_bits(&cdf::SINGLE_REF[0][3], 0);
2901 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
2902 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
2903 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
2904
2905 let mv = stack.nearest_mv;
2906 let ref_luma = (
2907 &reference.y,
2908 reference.width,
2909 luma.true_width,
2910 luma.true_height,
2911 );
2912 let ref_u = (
2913 &reference.u,
2914 reference.width / 2,
2915 chroma[0].true_width,
2916 chroma[0].true_height,
2917 );
2918 let ref_v = (
2919 &reference.v,
2920 reference.width / 2,
2921 chroma[1].true_width,
2922 chroma[1].true_height,
2923 );
2924 let luma_trial = mc_trial(
2925 luma,
2926 x,
2927 y,
2928 side,
2929 mv,
2930 true,
2931 ref_luma.0,
2932 ref_luma.1,
2933 ref_luma.2,
2934 ref_luma.3,
2935 false,
2936 search.base_q_idx,
2937 search.deadzone,
2938 luma_set, fctx,
2939 );
2940 let u = mc_trial(
2941 &chroma[0],
2942 x / 2,
2943 y / 2,
2944 side / 2,
2945 mv,
2946 false,
2947 ref_u.0,
2948 ref_u.1,
2949 ref_u.2,
2950 ref_u.3,
2951 false,
2952 search.base_q_idx,
2953 search.deadzone,
2954 chroma_set, fctx,
2955 );
2956 let v = mc_trial(
2957 &chroma[1],
2958 x / 2,
2959 y / 2,
2960 side / 2,
2961 mv,
2962 false,
2963 ref_v.0,
2964 ref_v.1,
2965 ref_v.2,
2966 ref_v.3,
2967 false,
2968 search.base_q_idx,
2969 search.deadzone,
2970 chroma_set, fctx,
2971 );
2972 let skip = luma_trial.levels.iter().all(|&l| l == 0)
2973 && u.levels.iter().all(|&l| l == 0)
2974 && v.levels.iter().all(|&l| l == 0);
2975 let inter_cost = luma_trial.sse
2976 + u.sse
2977 + v.sse
2978 + search.lambda
2979 * (skip_bits(skip)
2980 + intra_inter_bits(true)
2981 + single_ref_bits
2982 + mode_bits_inter
2983 + if skip {
2984 0.0
2985 } else {
2986 luma_trial.bits + u.bits + v.bits
2987 });
2988
2989 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
2990 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
2991 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
2992 // scan's own coverage already reached as far) but a real gap at 4-mi
2993 // leaf geometry. r3 ported the extended scan and, while proving it a
2994 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
2995 // `mvstack.rs`), found and fixed a second bug the extended scan's
2996 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
2997 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
2998 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
2999 // regardless of whether it also casts a ref-frame-matching vote) --
3000 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
3001 // branches), which is what made 8-mi geometry a true no-op instead of
3002 // one that only held when every neighbour happened to be inter.
3003 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
3004 // only ever took the stack's NEARESTMV candidate or went intra, so a
3005 // 32x32 block splitting because its four quarters MOVE differently could
3006 // not code the movement it split for. Same candidate `search_inter_block`
3007 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
3008 // a vector the residual syntax can name -- at this leaf's own side.
3009 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
3010 // This leaf's own `NEWMV` vector, kept whether or not it won the
3011 // single-reference comparison: it seeds the compound half-new candidate
3012 // below, exactly as `search_inter_block` seeds its own from the searches
3013 // it already ran.
3014 let mut searched_new: Option<(i32, i32)> = None;
3015 // What that search cost, kept for the second reference's own early-out
3016 // below (`None` when this leaf ran no search at all).
3017 let mut searched_new_cost: Option<f64> = None;
3018 let source_block = luma.source_block(x, y, side);
3019 if leaf_new_mv() {
3020 let (seeds, seed_n) = mv_seeds(stack);
3021 let found = motion::search(
3022 ref_luma.0,
3023 ref_luma.1,
3024 ref_luma.2,
3025 ref_luma.3,
3026 &source_block,
3027 x,
3028 y,
3029 side,
3030 side,
3031 stack.pred_mv,
3032 &seeds[..seed_n],
3033 search.lambda, fctx,
3034 1,
3035 );
3036 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
3037 searched_new_cost = Some(found.cost);
3038 if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) {
3039 searched_new = Some(new_mv);
3040 // Same reuse as `search_inter_block`: a NEWMV equal to the
3041 // stack's NEARESTMV is the same three trials, already run above.
3042 let (luma_new, u_new, v_new) = if new_mv == mv {
3043 (luma_trial.clone(), u.clone(), v.clone())
3044 } else {
3045 (
3046 mc_trial(
3047 luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2,
3048 ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx,
3049 ),
3050 mc_trial(
3051 &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1,
3052 ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set,
3053 fctx,
3054 ),
3055 mc_trial(
3056 &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1,
3057 ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set,
3058 fctx,
3059 ),
3060 )
3061 };
3062 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
3063 && u_new.levels.iter().all(|&l| l == 0)
3064 && v_new.levels.iter().all(|&l| l == 0);
3065 let drl_bits = if stack.entries.len() > 1 {
3066 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
3067 } else {
3068 0.0
3069 };
3070 let cost_new = luma_new.sse
3071 + u_new.sse
3072 + v_new.sse
3073 + search.lambda
3074 * (skip_bits(skip_new)
3075 + intra_inter_bits(true)
3076 + single_ref_bits
3077 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
3078 + drl_bits
3079 + mv_bits
3080 + if skip_new {
3081 0.0
3082 } else {
3083 luma_new.bits + u_new.bits + v_new.bits
3084 });
3085 if cost_new < best.0 {
3086 best = (
3087 cost_new,
3088 Some((
3089 luma_new,
3090 u_new,
3091 v_new,
3092 skip_new,
3093 InterInfo {
3094 ref1: None,
3095 mv1: (0, 0),
3096 ref_frame: crate::mvstack::LAST_FRAME,
3097 mode: InterMode::NewMv,
3098 mv: new_mv,
3099 ref_mv_idx: 0,
3100 },
3101 )),
3102 );
3103 }
3104 }
3105 }
3106
3107 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
3108 // `search_inter_block` prices for a whole 32x32 block:
3109 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
3110 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
3111 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
3112 // too. Priced with the same static-CDF approximation, plus the
3113 // compound-only syntax the writer emits.
3114 for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) {
3115 let (ref1, g) = (*ref1, *g);
3116 let uni =
3117 (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1);
3118 let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
3119 + if uni {
3120 symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
3121 + symbol_bits(&cdf::COMP_REF[0][0], 0)
3122 + symbol_bits(&cdf::COMP_REF[0][1], 0)
3123 + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
3124 } else {
3125 symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
3126 + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
3127 + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
3128 + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
3129 };
3130 let mode_ctx =
3131 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
3132 let mode_bits_of =
3133 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
3134 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
3135 (
3136 cstack.nearest_mv,
3137 mode_bits_of(0),
3138 InterInfo {
3139 ref_frame: crate::mvstack::LAST_FRAME,
3140 mode: InterMode::NearestNearestMv,
3141 mv: cstack.nearest_mv.0,
3142 mv1: cstack.nearest_mv.1,
3143 ref1: Some(ref1),
3144 ref_mv_idx: 0,
3145 },
3146 ),
3147 (
3148 ((0, 0), (0, 0)),
3149 mode_bits_of(6),
3150 InterInfo {
3151 ref_frame: crate::mvstack::LAST_FRAME,
3152 mode: InterMode::GlobalGlobalMv,
3153 mv: (0, 0),
3154 mv1: (0, 0),
3155 ref1: Some(ref1),
3156 ref_mv_idx: 0,
3157 },
3158 ),
3159 ];
3160 // Every compound MV residual here is priced against compound stack
3161 // entry 0, which is what `assign_compound_mv` predicts from at
3162 // `ref_mv_idx = 0` -- so it is also what the second-reference search
3163 // below seeds from and rounds to, and no candidate it finds can then
3164 // fail `mv_residual_bits`.
3165 let cbase = cstack
3166 .entries
3167 .first()
3168 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
3169 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
3170 // it a leaf could only name a stack vector for the second half, and
3171 // screen capture showed the consequence: every leaf compound block
3172 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
3173 // extra-reference `NEWMV`, when this reference's own
3174 // `NEAREST_NEARESTMV` vector already prices `margin` times better
3175 // than the `LAST` search of this same leaf did -- one candidate
3176 // evaluation standing in for a whole search.
3177 let margin = leaf_second_new_margin();
3178 let mut second_new: Option<(i32, i32)> = None;
3179 if leaf_second_new_mv() {
3180 let skip = margin > 0.0
3181 && searched_new_cost.is_some_and(|last| {
3182 motion::cost_at(
3183 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y,
3184 side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx,
3185 ) * margin
3186 <= last
3187 });
3188 if !skip {
3189 let mut seeds = [(0, 0); 4];
3190 let mut seed_n = 1;
3191 for e in cstack.entries.iter().take(3) {
3192 seeds[seed_n] = e.mv1;
3193 seed_n += 1;
3194 }
3195 let found = motion::search(
3196 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side,
3197 side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1),
3198 );
3199 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
3200 }
3201 }
3202 if let Some(new_mv) = searched_new {
3203 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
3204 ccands.push((
3205 (new_mv, cstack.nearest_mv.1),
3206 mode_bits_of(3) + b0,
3207 InterInfo {
3208 ref_frame: crate::mvstack::LAST_FRAME,
3209 mode: InterMode::NewNearestMv,
3210 mv: new_mv,
3211 mv1: cstack.nearest_mv.1,
3212 ref1: Some(ref1),
3213 ref_mv_idx: 0,
3214 },
3215 ));
3216 }
3217 }
3218 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
3219 // searches this leaf ran, each residual priced against `cbase`.
3220 if let Some(mv1) = second_new {
3221 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
3222 ccands.push((
3223 (cstack.nearest_mv.0, mv1),
3224 mode_bits_of(2) + b1,
3225 InterInfo {
3226 ref_frame: crate::mvstack::LAST_FRAME,
3227 mode: InterMode::NearestNewMv,
3228 mv: cstack.nearest_mv.0,
3229 mv1,
3230 ref1: Some(ref1),
3231 ref_mv_idx: 0,
3232 },
3233 ));
3234 if let Some((new_mv, b0)) =
3235 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
3236 {
3237 ccands.push((
3238 (new_mv, mv1),
3239 mode_bits_of(7) + b0 + b1,
3240 InterInfo {
3241 ref_frame: crate::mvstack::LAST_FRAME,
3242 mode: InterMode::NewNewMv,
3243 mv: new_mv,
3244 mv1,
3245 ref1: Some(ref1),
3246 ref_mv_idx: 0,
3247 },
3248 ));
3249 }
3250 }
3251 }
3252 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
3253 ccands.dedup_by_key(|c| c.0);
3254 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
3255 let g_u = (
3256 g.u.as_slice(),
3257 g.width / 2,
3258 chroma[0].true_width,
3259 chroma[0].true_height,
3260 );
3261 let g_v = (
3262 g.v.as_slice(),
3263 g.width / 2,
3264 chroma[1].true_width,
3265 chroma[1].true_height,
3266 );
3267 for (mvs, bits, info) in ccands {
3268 let luma_c = mc_trial_compound(
3269 luma, x, y, side, mvs, true,
3270 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
3271 search.base_q_idx, search.deadzone, luma_set, fctx,
3272 );
3273 let u_c = mc_trial_compound(
3274 &chroma[0], x / 2, y / 2, side / 2, mvs, false,
3275 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
3276 search.base_q_idx, search.deadzone, chroma_set, fctx,
3277 );
3278 let v_c = mc_trial_compound(
3279 &chroma[1], x / 2, y / 2, side / 2, mvs, false,
3280 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
3281 search.base_q_idx, search.deadzone, chroma_set, fctx,
3282 );
3283 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
3284 && u_c.levels.iter().all(|&l| l == 0)
3285 && v_c.levels.iter().all(|&l| l == 0);
3286 let cost_c = luma_c.sse
3287 + u_c.sse
3288 + v_c.sse
3289 + search.lambda
3290 * (skip_bits(skip_c)
3291 + intra_inter_bits(true)
3292 + bits
3293 + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
3294 if cost_c < best.0 {
3295 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
3296 }
3297 }
3298 }
3299
3300 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
3301 if cost < intra_cost {
3302 // A compound winner commits the flat trial it was priced from:
3303 // `commit_inter_luma`'s var-tx trial set is single-reference
3304 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
3305 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
3306 // predicting each half-side trial from BOTH references, verified
3307 // byte-identical to this when its split is disabled) and MEASURED
3308 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
3309 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
3310 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
3311 // compound block's residual is small enough that the four extra
3312 // per-unit txb_skip/eob symbols cost more ladder bytes than this
3313 // encoder's static-CDF estimate prices them at, so the local RD
3314 // win does not convert. The flat trial stays.
3315 let (levels, tx_depth, dcost) = if info.ref1.is_some() {
3316 luma.commit(x, y, side, &luma_new);
3317 (luma_new.levels.clone(), 0, 0.0)
3318 } else {
3319 commit_inter_luma(
3320 luma, (x, y), side, info.mv,
3321 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
3322 search, &luma_new, skip_new, fctx,
3323 )
3324 };
3325 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
3326 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
3327 return (
3328 BlockCoeffs {
3329 luma: coeffs(&levels, side),
3330 u: coeffs(&u_new.levels, side / 2),
3331 v: coeffs(&v_new.levels, side / 2),
3332 mode: DC_PRED as u8,
3333 uv_mode: DC_PRED,
3334 skip: skip_new,
3335 eight: None,
3336 palette: None,
3337 palette_uv: None,
3338 tx_depth,
3339 inter: Some(info),
3340 },
3341 cost + dcost,
3342 );
3343 }
3344 }
3345
3346 census_add(8, 1);
3347 if skip {
3348 census_add(10, 1);
3349 }
3350 if inter_cost >= intra_cost {
3351 census_add(9, 1);
3352 }
3353 if inter_cost < intra_cost {
3354 let (levels, tx_depth, dcost) = commit_inter_luma(
3355 luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, fctx,
3356 );
3357 chroma[0].commit(x / 2, y / 2, side / 2, &u);
3358 chroma[1].commit(x / 2, y / 2, side / 2, &v);
3359 (BlockCoeffs {
3360 luma: coeffs(&levels, side),
3361 u: coeffs(&u.levels, side / 2),
3362 v: coeffs(&v.levels, side / 2),
3363 mode: DC_PRED as u8,
3364 uv_mode: DC_PRED,
3365 skip,
3366 eight: None,
3367 palette: None,
3368 palette_uv: None,
3369 tx_depth,
3370 inter: Some(InterInfo {
3371 ref1: None,
3372 mv1: (0, 0),
3373 ref_frame: crate::mvstack::LAST_FRAME,
3374 mode: InterMode::NearestMv,
3375 mv,
3376 ref_mv_idx: 0,
3377 }),
3378 }, inter_cost + dcost)
3379 } else {
3380 (intra_block, intra_cost)
3381 }
3382}
3383
3384/// Publishes one coded inter-frame block into the `mi` grid the next block's
3385/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
3386/// block casts no vote but is still a coded cell (see `code_square_inter`'s
3387/// note on `processed_rows`/`processed_cols`).
3388fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: Option<InterInfo>) {
3389 let info = match inter {
3390 Some(info) => MiInfo {
3391 is_inter: true,
3392 ref_frame: info.ref_frame,
3393 // A COMPOUND block votes with BOTH of its references and both of
3394 // its vectors, exactly as the tile writer publishes it: recording
3395 // a compound block as a single-reference one here left the
3396 // encoder's own grid disagreeing with the writer's from the first
3397 // compound block on, so every later stack it searched against was
3398 // not the stack the decoder derives.
3399 ref_frame1: info.ref1.unwrap_or(NO_REF1),
3400 mv1: mv16(info.mv1),
3401 mv: mv16(info.mv),
3402 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
3403 // side, compound modes 2/3/7 on the other.
3404 is_new_mv: matches!(
3405 info.mode,
3406 InterMode::NewMv
3407 | InterMode::NewNewMv
3408 | InterMode::NearestNewMv
3409 | InterMode::NewNearestMv
3410 ),
3411 size,
3412 size_h: size,
3413 is_global_mv0: false,
3414 is_global_mv1: false,
3415 },
3416 None => MiInfo {
3417 is_inter: false,
3418 ref_frame: -1,
3419 ref_frame1: NO_REF1,
3420 mv1: (0, 0),
3421 mv: (0, 0),
3422 is_new_mv: false,
3423 size,
3424 size_h: size,
3425 is_global_mv0: false,
3426 is_global_mv1: false,
3427 },
3428 };
3429 for dr in 0..usize::from(size) {
3430 for dc in 0..usize::from(size) {
3431 grid.set(mi_row + dr, mi_col + dc, info);
3432 }
3433 }
3434}
3435
3436/// The reconstructed samples one 32x32 square covers in all three planes, so
3437/// that a partition trial can be undone.
3438fn snapshot(
3439 luma: &Plane,
3440 chroma: &[Plane; 2],
3441 (x, y): (usize, usize),
3442 side: usize,
3443) -> [Vec<u8>; 3] {
3444 [
3445 luma.snapshot(x, y, side),
3446 chroma[0].snapshot(x / 2, y / 2, side / 2),
3447 chroma[1].snapshot(x / 2, y / 2, side / 2),
3448 ]
3449}
3450
3451/// Puts such a snapshot back.
3452fn restore(
3453 luma: &mut Plane,
3454 chroma: &mut [Plane; 2],
3455 (x, y): (usize, usize),
3456 side: usize,
3457 saved: &[Vec<u8>; 3],
3458) {
3459 luma.restore(x, y, side, &saved[0]);
3460 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
3461 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
3462}
3463
3464/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
3465/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
3466/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
3467/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
3468/// rule shared with the key-frame path, not a second one that could diverge.
3469fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
3470 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
3471 let dc_entry = dc_pos.map(|i| scored.remove(i));
3472 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
3473 scored.truncate(if dc_entry.is_some() {
3474 top_k.saturating_sub(1)
3475 } else {
3476 top_k
3477 });
3478 if let Some(dc_entry) = dc_entry {
3479 scored.push(dc_entry);
3480 }
3481 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
3482 modes.iter().copied().filter(|m| keep.contains(m)).collect()
3483}
3484
3485fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
3486 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
3487 [INTRA_MODE_CTX[usize::from(left_mode)]];
3488 std::array::from_fn(|mode| {
3489 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
3490 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
3491 } else {
3492 0.0
3493 };
3494 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
3495 })
3496}
3497
3498/// What the luma mode search picks between, and under what terms.
3499struct Search<'a> {
3500 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
3501 /// luma search then offers a palette candidate beside the intra modes.
3502 screen: bool,
3503 base_q_idx: u8,
3504 deadzone: f64,
3505 lambda: f64,
3506 modes: &'a [u8],
3507 /// How many of `modes` the full RD trial (forward transform, quantize,
3508 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
3509 /// pre-pass on the prediction residual alone plus DC (always kept, since
3510 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
3511 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
3512 /// mode through full RD, unchanged from before this lever.
3513 top_k: Option<usize>,
3514}
3515
3516/// [`Search::top_k`]'s value: `None` keeps every mode's search unchanged
3517/// (the default, until a lever's quality gate justifies pruning by default);
3518/// `EC_AV1_PRUNE_K` sweeps it in a test build without touching callers.
3519fn prune_top_k() -> Option<usize> {
3520 #[cfg(test)]
3521 {
3522 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
3523 return k;
3524 }
3525 }
3526 let swept = std::env::var("EC_AV1_PRUNE_K")
3527 .ok()
3528 .and_then(|v| v.parse::<usize>().ok());
3529 match swept {
3530 Some(k) if cfg!(test) => Some(k),
3531 _ => PRUNE_TOP_K,
3532 }
3533}
3534
3535// A per-thread override [`prune_top_k`] checks first, so one test can sweep
3536// `top_k` in-process without mutating the environment (forbidden here --
3537// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
3538#[cfg(test)]
3539thread_local! {
3540 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
3541 const { std::cell::Cell::new(None) };
3542}
3543
3544#[cfg(test)]
3545fn set_test_top_k_override(value: Option<usize>) {
3546 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
3547}
3548
3549/// The default: unpruned, thirteen full trials per block, same as before this
3550/// lever. Set from the sweep in the lane report if the quality gate clears it.
3551const PRUNE_TOP_K: Option<usize> = None;
3552
3553/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
3554/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
3555/// quality gates were measured separately and may land on different
3556/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
3557/// [`EC_AV1_PRUNE_K`] or the key-frame path.
3558fn prune_top_k_inter() -> Option<usize> {
3559 #[cfg(test)]
3560 {
3561 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
3562 return k;
3563 }
3564 }
3565 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
3566 .ok()
3567 .and_then(|v| v.parse::<usize>().ok());
3568 match swept {
3569 Some(k) if cfg!(test) => Some(k),
3570 _ => INTER_PRUNE_TOP_K,
3571 }
3572}
3573
3574// A per-thread override [`prune_top_k_inter`] checks first, same reason as
3575// [`TEST_TOP_K_OVERRIDE`].
3576#[cfg(test)]
3577thread_local! {
3578 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
3579 const { std::cell::Cell::new(None) };
3580}
3581
3582#[cfg(test)]
3583fn set_test_top_k_override_inter(value: Option<usize>) {
3584 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
3585}
3586
3587/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
3588/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
3589/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
3590/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
3591/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
3592/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
3593/// pruning them costs less quality here.
3594const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
3595
3596// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
3597// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
3598// inter frame's cost can be attributed to a bucket without changing what
3599// the search actually does. Index: 0 = whole-call time inside
3600// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
3601// [`crate::mc::predict`] (every call, from the motion search's own
3602// candidates and from a committed inter block's final prediction alike),
3603// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
3604#[cfg(test)]
3605thread_local! {
3606 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
3607 std::cell::Cell::new(0),
3608 std::cell::Cell::new(0),
3609 std::cell::Cell::new(0),
3610 std::cell::Cell::new(0),
3611 ];
3612}
3613
3614#[cfg(test)]
3615pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
3616 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
3617}
3618
3619#[cfg(test)]
3620fn stage_reset() {
3621 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
3622}
3623
3624#[cfg(test)]
3625fn stage_read() -> [std::time::Duration; 4] {
3626 STAGE_NS.with(|c| {
3627 c.each_ref()
3628 .map(|cell| std::time::Duration::from_nanos(cell.get()))
3629 })
3630}
3631
3632/// One mode's coding of one block, before it is committed.
3633#[derive(Clone)]
3634struct Trial {
3635 levels: Vec<i32>,
3636 reconstruction: Vec<u8>,
3637 sse: f64,
3638 bits: f64,
3639}
3640
3641/// The non-zero levels of a block, as the tile writer takes them.
3642fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
3643 levels
3644 .iter()
3645 .enumerate()
3646 .filter(|&(_, &level)| level != 0)
3647 .map(|(i, &level)| Coeff {
3648 row: (i / side) as u8,
3649 col: (i % side) as u8,
3650 level,
3651 })
3652 .collect()
3653}
3654
3655thread_local! {
3656 /// The tile grid the next frame is coded with, as `(TileColsLog2,
3657 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
3658 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
3659 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
3660 /// one tile per frame, what every caller that never arms anything gets
3661 /// and what every stream this crate wrote before tiles existed carries.
3662 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
3663}
3664
3665/// Arms this thread's next frame encodes with a tile grid (log2 counts).
3666pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
3667 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
3668}
3669
3670fn armed_tiles() -> (u32, u32) {
3671 let armed = TILE_LOG2.with(std::cell::Cell::get);
3672 if armed != (0, 0) {
3673 return armed;
3674 }
3675 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
3676 // (which codes through `encode_sequence`, not the facade) can measure what
3677 // a tile grid costs without a knob of its own -- same shape as
3678 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
3679 match std::env::var("EC_AV1_TILES").ok() {
3680 Some(v) if cfg!(test) => {
3681 let mut f = v.split(':');
3682 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
3683 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
3684 (cols, rows)
3685 }
3686 _ => armed,
3687 }
3688}
3689
3690/// Codes a frame's `tiles` tiles, each entirely on its own (see
3691/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
3692/// the crate's own pool, and hands back their payloads in tile order plus
3693/// whatever `code` returned for tile `store` -- the CDF state
3694/// `context_update_tile_id` names. The result cannot depend on the thread
3695/// count: each job writes one tile from the frame's own starting tables into
3696/// its own slot.
3697fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
3698where
3699 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
3700{
3701 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
3702 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
3703 let threads = crate::par::tile_threads().min(tiles);
3704 let mut slots: Vec<Slot> = Vec::new();
3705 if threads <= 1 {
3706 for index in 0..tiles {
3707 slots.push(Some(code(index)));
3708 }
3709 } else {
3710 let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
3711 {
3712 let batch = crate::par::Batch::new("ec-av1-tile");
3713 for (from, to) in crate::par::bands(tiles, threads) {
3714 let done = &done;
3715 let code = &code;
3716 batch.submit(move || {
3717 for index in from..to {
3718 let coded = code(index);
3719 done.lock().expect("tile slots")[index] = Some(coded);
3720 }
3721 });
3722 }
3723 }
3724 slots = done.into_inner().expect("tile slots");
3725 }
3726 let mut out = Vec::with_capacity(tiles);
3727 let mut stored = None;
3728 for (index, slot) in slots.into_iter().enumerate() {
3729 let (bytes, cdfs) = slot.expect("every tile was coded")?;
3730 if index == store {
3731 stored = cdfs;
3732 }
3733 out.push(bytes);
3734 }
3735 Ok((out, stored))
3736}
3737
3738/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
3739/// workers, and returns the results in tile order. The counterpart of
3740/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
3741/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
3742/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
3743/// availability is already tile-relative (`clip_planes_to_tile`,
3744/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
3745/// other tiles have run -- gated by
3746/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
3747/// covers the search as well as the write.
3748///
3749/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
3750/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
3751/// does it for the decoder's filter bands.
3752fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
3753where
3754 T: Send,
3755 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
3756{
3757 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
3758 let threads = crate::par::tile_threads().min(tiles);
3759 if threads <= 1 {
3760 return (0..tiles).map(|index| job(index, fctx)).collect();
3761 }
3762 type Slot<T> = Option<Result<T>>;
3763 let done: std::sync::Mutex<Vec<Slot<T>>> =
3764 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
3765 {
3766 let batch = crate::par::Batch::new("ec-av1-tile-search");
3767 for (from, to) in crate::par::bands(tiles, threads) {
3768 let done = &done;
3769 let job = &job;
3770 let ctx = crate::decode::filter_ctx_copy(fctx);
3771 batch.submit(move || {
3772 for index in from..to {
3773 let searched = job(index, &ctx);
3774 done.lock().expect("tile slots")[index] = Some(searched);
3775 }
3776 });
3777 }
3778 }
3779 done.into_inner()
3780 .expect("tile slots")
3781 .into_iter()
3782 .map(|slot| slot.expect("every tile was searched"))
3783 .collect()
3784}
3785
3786/// One tile job's own copy of a plane: the frame's source, a blank
3787/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
3788/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
3789/// of the frame's reconstruction because a tile's prediction never reads a
3790/// sample outside its own rectangle, and every sample inside it is written
3791/// before it is read.
3792fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
3793 Plane {
3794 source,
3795 reconstruction: vec![128; source.len()],
3796 width,
3797 height,
3798 true_width,
3799 true_height,
3800 tile_x0: 0,
3801 tile_y0: 0,
3802 tile_x1: width,
3803 tile_y1: height,
3804 }
3805}
3806
3807/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
3808/// the frame's plane, through the [`crate::par::Shared`] every job holds.
3809///
3810/// corner-cut: the disjointness that makes the aliasing sound is the caller's
3811/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
3812/// rectangles partition it -- checked end-to-end by
3813/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
3814/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
3815/// row-range `split_at_mut` plumbing through `Plane`, which would have to
3816/// thread an origin offset through every prediction and transform call site
3817/// for the same bytes.
3818#[allow(unsafe_code)]
3819fn copy_rect(
3820 dst: crate::par::Shared<'_, Vec<u8>>,
3821 src: &[u8],
3822 stride: usize,
3823 x0: usize,
3824 y0: usize,
3825 x1: usize,
3826 y1: usize,
3827) {
3828 // SAFETY: this job touches only its own tile rectangle (see above).
3829 let dst = unsafe { dst.get() };
3830 for y in y0..y1 {
3831 let (a, b) = (y * stride + x0, y * stride + x1);
3832 dst[a..b].copy_from_slice(&src[a..b]);
3833 }
3834}
3835
3836/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
3837/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
3838/// tables the frame stores (spec 7.20), which is what
3839/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
3840/// below publish.
3841fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
3842 ec_av1_syntax::TileInfo {
3843 uniform_spacing: true,
3844 cols: layout.cols(),
3845 rows: layout.rows(),
3846 cols_log2: layout.cols_log2,
3847 rows_log2: layout.rows_log2,
3848 mi_col_starts: layout.mi_col_starts(),
3849 mi_row_starts: layout.mi_row_starts(),
3850 context_update_tile_id: layout.largest_tile() as u32,
3851 tile_size_bytes,
3852 }
3853}
3854
3855/// Clips the three planes' intra edge reads to `rect`, the tile the
3856/// superblock about to be searched belongs to (the encoder side of the
3857/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
3858/// raster order -- which is a linear extension of every tile's own coding
3859/// order, so a block still only ever predicts from samples already
3860/// reconstructed -- and only availability is tile-relative.
3861fn clip_planes_to_tile(
3862 luma: &mut Plane<'_>,
3863 chroma: &mut [Plane<'_>; 2],
3864 rect: crate::tile::TileRect,
3865) {
3866 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
3867 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
3868 luma.set_tile(x0, y0, x1, y1);
3869 for plane in chroma.iter_mut() {
3870 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
3871 }
3872}
3873
3874/// Encodes one picture as a key frame.
3875///
3876/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
3877/// picks its coefficient CDFs from one of four q contexts by that index.
3878/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
3879/// smaller values trade fidelity for rate.
3880///
3881/// The picture may be any even width and height: the encoder pads it by edge
3882/// replication to a whole number of 32x32 blocks internally, and the frame it
3883/// writes crops back to the picture's own size (`render_width`/
3884/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
3885/// own size, never the padded one.
3886///
3887/// # Errors
3888/// Returns an error when the picture's width or height is zero or odd, or
3889/// when its planes are not 4:2:0 of that size.
3890/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
3891/// stream. The per-frame decode state this needs lives for exactly this call.
3892///
3893/// # Errors
3894/// Returns an error under the same conditions
3895/// [`encode_key_frame_with_modes`] does.
3896pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
3897 encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
3898}
3899
3900/// [`encode_key_frame`] with the per-block intra modes given rather than
3901/// searched.
3902///
3903/// # Errors
3904/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
3905/// is empty, or when a block's coefficients do not fit the coded frame.
3906pub fn encode_key_frame_with_modes(
3907 picture: &Picture,
3908 base_q_idx: u8,
3909 deadzone: f64,
3910 modes: &[u8],
3911) -> Result<Encoded> {
3912 encode_key_frame_with_modes_with_ctx(
3913 picture,
3914 base_q_idx,
3915 deadzone,
3916 modes,
3917 &crate::decode::FrameCtx::new(),
3918 )
3919}
3920
3921/// Codes `pictures` as one key frame followed by inter frames.
3922///
3923/// # Errors
3924/// Returns an error under the same conditions [`encode_key_frame`] and the
3925/// inter frame path do.
3926pub fn encode_sequence(
3927 pictures: &[Picture],
3928 base_q_idx: u8,
3929 deadzone: f64,
3930) -> Result<EncodedSequence> {
3931 encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
3932}
3933
3934pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
3935 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
3936}
3937
3938/// Encodes one picture as a key frame, choosing each block's luma mode from
3939/// `modes` alone.
3940///
3941/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
3942/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
3943/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
3944/// uses.
3945///
3946/// # Errors
3947/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
3948/// names a mode [`crate::intra::predict`] does not predict.
3949pub(crate) fn encode_key_frame_with_modes_with_ctx(
3950 picture: &Picture,
3951 base_q_idx: u8,
3952 deadzone: f64,
3953 modes: &[u8], fctx: &crate::decode::FrameCtx,
3954) -> Result<Encoded> {
3955 picture.check_even()?;
3956 let padded = picture.padded_to(BLOCK);
3957 let encoded = encode_key_frame_inner(
3958 &padded,
3959 base_q_idx,
3960 deadzone,
3961 modes,
3962 split_blocks(),
3963 (picture.width, picture.height),
3964 unspecified_color_config(), fctx,
3965 )?;
3966 Ok(crop_encoded(&encoded, picture.width, picture.height))
3967}
3968
3969/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
3970/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
3971/// already padded to a whole number of 32x32 blocks; `render` is the real
3972/// (pre-pad) size the frame header tells a decoder to crop back to.
3973pub(crate) fn encode_key_frame_inner(
3974 picture: &Picture,
3975 base_q_idx: u8,
3976 deadzone: f64,
3977 modes: &[u8],
3978 split_blocks: bool,
3979 render: (usize, usize),
3980 color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
3981) -> Result<Encoded> {
3982 picture.check()?;
3983 if modes.is_empty() {
3984 return Err(Error::unsupported(
3985 "AV1 encode",
3986 "a mode search needs at least one mode to choose from",
3987 ));
3988 }
3989 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
3990 return Err(Error::unsupported(
3991 "AV1 encode",
3992 format!("intra mode {bad} is not one the encoder predicts"),
3993 ));
3994 }
3995 // The header carries the frame's true (unpadded) size as `frame_width`/
3996 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
3997 // `mi_rows` derived from that same true size (spec `compute_image_size`).
3998 // `render_width`/`render_height` come out equal to it too, so
3999 // `render_and_frame_size_different` is false and no render_size bits are
4000 // written, mirroring libaom/rav1e: the padded `picture` below is only the
4001 // internal coding surface, never what the header names.
4002 // Screen-content detection runs on the SOURCE luma, before any header is
4003 // built: it decides this sequence's `seq_force_screen_content_tools` (and
4004 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
4005 // this frame's own `allow_screen_content_tools`.
4006 let screen = screen_content(
4007 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
4008 picture.width,
4009 (picture.width).min(render.0),
4010 (picture.height).min(render.1),
4011 );
4012 arm_seq_screen(screen);
4013 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
4014 header.allow_screen_content_tools = screen;
4015 header.render_width = render.0 as u32;
4016 header.render_height = render.1 as u32;
4017 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
4018 // its luma transform below its own side (`crate::tile::write_luma_select`).
4019 // Set here rather than in `key_frame_headers_colour` so the header
4020 // builders' other callers -- the hand-built tile writers, which code no
4021 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
4022 let tx_select = tx_select();
4023 if tx_select {
4024 header.tx_mode = TxMode::Select;
4025 }
4026 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
4027
4028 // Prediction reads no further than this, in each plane's own units --
4029 // see `Plane::true_width`/`true_height`.
4030 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
4031 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
4032 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
4033 // design (see `intra_predict_u8`'s doc comment), so narrow the source
4034 // once here.
4035 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
4036 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
4037 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
4038 let mut luma = Plane {
4039 source: &picture_y8,
4040 reconstruction: vec![128; picture_y8.len()],
4041 width: picture.width,
4042 height: picture.height,
4043 true_width,
4044 true_height,
4045 tile_x0: 0,
4046 tile_y0: 0,
4047 tile_x1: picture.width,
4048 tile_y1: picture.height,
4049 };
4050 let mut chroma = [
4051 Plane {
4052 source: &picture_u8,
4053 reconstruction: vec![128; picture_u8.len()],
4054 width: picture.width / 2,
4055 height: picture.height / 2,
4056 true_width: true_width / 2,
4057 true_height: true_height / 2,
4058 tile_x0: 0,
4059 tile_y0: 0,
4060 tile_x1: picture.width / 2,
4061 tile_y1: picture.height / 2,
4062 },
4063 Plane {
4064 source: &picture_v8,
4065 reconstruction: vec![128; picture_v8.len()],
4066 width: picture.width / 2,
4067 height: picture.height / 2,
4068 true_width: true_width / 2,
4069 true_height: true_height / 2,
4070 tile_x0: 0,
4071 tile_y0: 0,
4072 tile_x1: picture.width / 2,
4073 tile_y1: picture.height / 2,
4074 },
4075 ];
4076
4077 // The search trades a bit for the squared error it saves, in the units the
4078 // reconstruction is measured in: one step of the quantizer, squared.
4079 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
4080 let search = Search {
4081 base_q_idx,
4082 deadzone,
4083 lambda: lambda_scale() * step * step,
4084 modes,
4085 top_k: prune_top_k(),
4086 screen,
4087 };
4088
4089 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
4090 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
4091 // which may be fewer columns/rows than the padded picture has room for
4092 // -- a block whose origin sits past the true bound is not coded at all,
4093 // matching what a decoder derives from `frame_width`/`frame_height` and
4094 // so never visits either.
4095 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
4096 let (cols, rows) = (cols as usize, rows as usize);
4097 // The luma mode of the block above and of the block to the left, which is
4098 // what picks the CDF the next block's mode is coded against -- the same
4099 // bookkeeping the tile writer keeps, so that the search is costing the
4100 // symbol the writer will actually write.
4101 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
4102 // because a 32x32 block may be split into four 16x16 ones.
4103 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
4104 // This frame's tile grid (one tile unless the facade armed more).
4105 let layout =
4106 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
4107 header.tile_info = tile_info_of(&layout, 1);
4108 // The filter search re-decodes this frame's tiles; the decoder derives
4109 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
4110 // `mi_row_starts`), which is what makes the writer's rects and the
4111 // reader's the same rects.
4112 let header_tile_info = header.tile_info.clone();
4113 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
4114 // once over the whole frame. Each tile job builds its own reconstruction
4115 // planes and its own `above_mode`/`left_mode` bands, which is also what
4116 // the tile writer reads -- a tile resets its neighbour contexts (spec
4117 // 5.11.1), so a block at a tile's left edge must cost its mode against
4118 // the default context, not against whatever the tile to its west left in
4119 // that row. At one tile the bands are the frame's, exactly as before.
4120 let (frame_width, frame_height) = (picture.width, picture.height);
4121 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
4122 let [cb, cr] = &mut chroma;
4123 let chroma_out = [
4124 crate::par::Shared::new(&mut cb.reconstruction),
4125 crate::par::Shared::new(&mut cr.reconstruction),
4126 ];
4127 let search_tile = |index: usize,
4128 fctx: &crate::decode::FrameCtx|
4129 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
4130 let rect = layout.rect(index);
4131 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
4132 let mut chroma = [
4133 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
4134 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
4135 ];
4136 clip_planes_to_tile(&mut luma, &mut chroma, rect);
4137 let mut above_mode = vec![DC_PRED; cols * 2];
4138 let mut left_mode = vec![DC_PRED; rows * 2];
4139 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
4140 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
4141 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
4142 let mut modes = Vec::with_capacity(4);
4143 // The quadrants of a superblock are coded in the order the decoder
4144 // walks them, which for a 64x64 split into 32x32 blocks is raster
4145 // order among the quadrants that are inside the frame.
4146 let mut blocks = Vec::with_capacity(4);
4147 for quadrant in 0..4 {
4148 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
4149 if col >= cols || row >= rows {
4150 continue;
4151 }
4152 let (x, y) = (col * BLOCK, row * BLOCK);
4153 let (c0, r0) = (col * 2, row * 2);
4154 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
4155
4156 // spec `decode_partition`'s hasRows/hasCols recomputed at this
4157 // 32x32 block's own half (see `crate::tile::has_half`): the
4158 // true frame edge can fall inside a quadrant a superblock-level
4159 // check already let through. A quadrant that fails either may
4160 // not be left whole; a 16x16 sub-block that fails either (once
4161 // split) is a leaf this writer has no rectangular transform
4162 // for, so the search must not pick a split that would need one.
4163 let (has_cols32, has_rows32) = (
4164 crate::tile::has_half(
4165 col as u32 * crate::tile::BLOCK_MI,
4166 crate::tile::BLOCK_MI,
4167 header.mi_cols,
4168 ),
4169 crate::tile::has_half(
4170 row as u32 * crate::tile::BLOCK_MI,
4171 crate::tile::BLOCK_MI,
4172 header.mi_rows,
4173 ),
4174 );
4175 let whole_legal = has_cols32 && has_rows32;
4176 // A 16x16 sub-block's own hasCols/hasRows (spec
4177 // `decode_partition`, recomputed at this leaf's own half): one
4178 // axis false is a straddling leaf this writer codes as two
4179 // 8x8 leaves (`crate::tile::write_leaf8`, lane-av1-rect r7);
4180 // both axes false needs a rectangular transform this writer
4181 // has no size for at all, whether whole or split.
4182 let sub_half = |sr: usize, sc: usize| {
4183 (
4184 crate::tile::has_half(
4185 sc as u32 * crate::tile::SUB_MI,
4186 crate::tile::SUB_MI,
4187 header.mi_cols,
4188 ),
4189 crate::tile::has_half(
4190 sr as u32 * crate::tile::SUB_MI,
4191 crate::tile::SUB_MI,
4192 header.mi_rows,
4193 ),
4194 )
4195 };
4196 let both_axes_cut = (0..4)
4197 .map(|i| (r0 + i / 2, c0 + i % 2))
4198 .filter(|&(sr, sc)| {
4199 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
4200 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
4201 })
4202 .any(|(sr, sc)| {
4203 let (has_cols16, has_rows16) = sub_half(sr, sc);
4204 !has_cols16 && !has_rows16
4205 });
4206 if !whole_legal && both_axes_cut {
4207 return Err(Error::unsupported(
4208 "AV1 encode",
4209 format!(
4210 "the 32x32 block at ({col},{row}) straddles the true frame edge \
4211 in a way that needs a rectangular (HORZ/VERT) transform this \
4212 encoder does not code yet"
4213 ),
4214 ));
4215 }
4216
4217 // What the whole 32x32 costs, including the partition symbol
4218 // that says it is not split.
4219 let (whole, mut cost_whole) = code_square(
4220 &mut luma,
4221 &mut chroma,
4222 (x, y),
4223 BLOCK,
4224 &search,
4225 &mode_bits(above_mode[c0], left_mode[r0]),
4226 tx_select, fctx,
4227 );
4228 cost_whole += search.lambda * partition_bits(BLOCK, false);
4229 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
4230
4231 // What four 16x16 blocks cost instead, each searched against
4232 // the reconstruction the ones before it left.
4233 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
4234 let mut split = Vec::with_capacity(4);
4235 let mut cost_split = search.lambda
4236 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
4237 let mut split_modes = Vec::with_capacity(4);
4238 for sub in 0..4 {
4239 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
4240 // Same filter as the writer's `sub_positions` (spec
4241 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
4242 // return): a sub-block whose own origin sits past the
4243 // true frame is never coded, so it must not be searched
4244 // or pushed onto `split` either, or the writer's block
4245 // count will not match what it is prepared to name.
4246 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
4247 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
4248 {
4249 continue;
4250 }
4251 let (has_cols16, has_rows16) = sub_half(sr, sc);
4252 if has_cols16 && has_rows16 {
4253 let (block, cost) = code_square(
4254 &mut luma,
4255 &mut chroma,
4256 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
4257 SUB,
4258 &search,
4259 &mode_bits(above_mode[sc], left_mode[sr]),
4260 tx_select, fctx,
4261 );
4262 cost_split += cost;
4263 split_modes.push(block.mode);
4264 above_mode[sc] = block.mode;
4265 left_mode[sr] = block.mode;
4266 split.push(block);
4267 } else {
4268 // A straddling 16x16: two (or, at a true corner, one)
4269 // 8x8 leaves, in the raster order `write_leaf8`'s
4270 // caller expects. Both leaves cost against the SAME
4271 // enclosing-slot mode context (see
4272 // `crate::tile::write_leaf8`'s doc), and neither
4273 // updates `above_mode`/`left_mode` at this SUB slot --
4274 // the writer never does either, so the search must
4275 // not diverge from what it will actually read next.
4276 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
4277 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
4278 let mut leaves = Vec::with_capacity(2);
4279 for i in 0..4 {
4280 let leaf_x = x_sub + (i % 2) * 8;
4281 let leaf_y = y_sub + (i / 2) * 8;
4282 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
4283 continue;
4284 }
4285 let (leaf, cost) = code_square(
4286 &mut luma,
4287 &mut chroma,
4288 (leaf_x, leaf_y),
4289 8,
4290 &search,
4291 &leaf_mode_bits,
4292 tx_select, fctx,
4293 );
4294 cost_split += cost;
4295 split_modes.push(leaf.mode);
4296 leaves.push(leaf);
4297 }
4298 split.push(BlockCoeffs {
4299 eight: Some(leaves),
4300 ..BlockCoeffs::default()
4301 });
4302 }
4303 }
4304
4305 // A split whose subs are all whole 16x16 is a real quality
4306 // alternative to `whole`, exactly as before. Through r14, a
4307 // split carrying an 8x8-leaf sub was only ever forced
4308 // (`!whole_legal`), never chosen on cost, because the leaf
4309 // path was not yet proven against a real decoder; r15 proved
4310 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
4311 // the read path (`decode_leaf8`), so leaf8 can now win on
4312 // cost anywhere, same as any other split.
4313 if !whole_legal || (split_blocks && cost_split < cost_whole) {
4314 modes.extend_from_slice(&split_modes);
4315 blocks.push(Quadrant::Split(split));
4316 } else {
4317 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
4318 for cell in 0..2 {
4319 above_mode[c0 + cell] = whole.mode;
4320 left_mode[r0 + cell] = whole.mode;
4321 }
4322 modes.push(whole.mode);
4323 blocks.push(Quadrant::Whole(whole));
4324 }
4325 }
4326 coded.push((sb_row * sb_cols + sb_col, Superblock::Split(blocks), modes));
4327 }
4328 }
4329 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
4330 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
4331 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
4332 for (&out, tile) in chroma_out.iter().zip(&chroma) {
4333 copy_rect(
4334 out,
4335 &tile.reconstruction,
4336 frame_width / 2,
4337 x0 / 2,
4338 y0 / 2,
4339 x1.div_ceil(2),
4340 y1.div_ceil(2),
4341 );
4342 }
4343 Ok(coded)
4344 };
4345 let searched = search_tiles(layout.count(), fctx, search_tile)?;
4346 // Back into frame raster order: the tile writer indexes `superblocks` by
4347 // the frame's own superblock index, and `modes` is the coding order the
4348 // ablation drivers read.
4349 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
4350 for (at, superblock, block_modes) in searched.into_iter().flatten() {
4351 in_order[at] = Some((superblock, block_modes));
4352 }
4353 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
4354 let mut modes = Vec::with_capacity(cols * rows);
4355 for slot in in_order {
4356 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
4357 superblocks.push(superblock);
4358 modes.extend_from_slice(&block_modes);
4359 }
4360
4361 #[cfg(test)]
4362 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
4363 // A key frame always starts from the defaults (`primary_ref_frame` is
4364 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
4365 // set, so what it stores into the slots it refreshes is exactly those
4366 // defaults again (spec 7.20's `started_from` arm) -- the first inter
4367 // frame after it therefore starts from the defaults too.
4368 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
4369 let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
4370 let start_cdfs = CdfSnapshot(cdfs);
4371 // The luma restoration-unit grid this frame's `lr_params` implies
4372 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
4373 // swallowed by the one before it), for the tile writer's own per-unit
4374 // walk.
4375 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
4376 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
4377 // Every tile is coded from this frame's OWN starting tables and leaves
4378 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
4379 // loop-restoration reference and its neighbour contexts), so the tiles
4380 // are independent of each other and of the order they are written in.
4381 let code_tiles = |bits: u8,
4382 sb_cols: usize,
4383 grid: &[u8],
4384 units: &[Option<crate::restoration::WienerInfo>]|
4385 -> Result<Vec<Vec<u8>>> {
4386 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
4387 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
4388 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
4389 let mut cdfs = start_cdfs.0.clone();
4390 crate::tile::arm_screen(screen);
4391 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
4392 mi_cols,
4393 mi_rows,
4394 base_q_idx,
4395 &superblocks,
4396 tx_select,
4397 &mut cdfs,
4398 layout.rect(index),
4399 )?;
4400 Ok((bytes, None))
4401 })?;
4402 Ok(out)
4403 };
4404 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
4405 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
4406 // the tile just coded back to the decoder under each candidate (see
4407 // `crate::filter_search`), and keep the filtered picture that wins as
4408 // the reconstruction -- what a decoder outputs, and what the next
4409 // frame predicts from.
4410 pick_and_apply_filters(
4411 &mut header,
4412 &mut luma,
4413 &mut chroma,
4414 [&picture_y8, &picture_u8, &picture_v8],
4415 true,
4416 &mut tiles,
4417 search.lambda,
4418 fctx,
4419 // Every re-code starts from this frame's OWN starting tables, never
4420 // from where the first write left them: the second tile is the same
4421 // symbol sequence plus new ones, so it must adapt from the same
4422 // point the decoder will.
4423 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
4424 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
4425 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
4426 crate::decode::decode_key_frame_tiles_lr(
4427 &payloads,
4428 &header_tile_info,
4429 h.mi_cols,
4430 h.mi_rows,
4431 base_q_idx,
4432 h.frame_width,
4433 h.frame_height,
4434 seq.enable_filter_intra,
4435 cdef,
4436 lf,
4437 tx_select,
4438 h.reduced_tx_set,
4439 h.allow_screen_content_tools,
4440 h.allow_intrabc,
4441 lr,
4442 fctx,
4443 )
4444 },
4445 )?;
4446 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
4447 header.tile_info.tile_size_bytes = tile_size_bytes;
4448 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
4449 let mut stream = temporal_delimiter();
4450 stream.extend_from_slice(&sequence_header_obu(&seq)?);
4451 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
4452
4453 let [u, v] = chroma;
4454 Ok(Encoded {
4455 stream,
4456 modes,
4457 inter_block_share: 0.0,
4458 reconstruction: Picture {
4459 width: luma.width,
4460 height: luma.height,
4461 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
4462 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
4463 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
4464 },
4465 tile,
4466 mi_cols: header.mi_cols,
4467 mi_rows: header.mi_rows,
4468 base_q_idx,
4469 tx_select,
4470 screen,
4471 next_cdfs: start_cdfs.clone(),
4472 start_cdfs,
4473 loop_filter: header.loop_filter,
4474 cdef: header.cdef,
4475 loop_restoration: header.loop_restoration,
4476 })
4477}
4478
4479/// Chooses this frame's deblocking levels and CDEF strengths, writes them
4480/// into `header` and
4481/// replaces the frame's own region of the encoder's reconstruction with the
4482/// filtered picture the decoder produced under them
4483/// ([`crate::filter_search::pick_deblock`]).
4484///
4485/// `search == false` leaves the header at level 0 (deblocking off) and the
4486/// reconstruction untouched: the caller's stream is one this crate's own
4487/// decoder cannot read back, so there is nothing to search against.
4488///
4489/// # Errors
4490/// The decoder's own error, when it refuses the tile the encoder just wrote
4491/// -- that is an encoder defect, not a filter one, so it is propagated
4492/// rather than swallowed into "no deblocking".
4493fn pick_and_apply_filters(
4494 header: &mut FrameHeader,
4495 luma: &mut Plane<'_>,
4496 chroma: &mut [Plane<'_>; 2],
4497 source: [&[u8]; 3],
4498 search: bool,
4499 // The coded tiles, one payload per tile of the frame's grid, replaced in
4500 // place when the search chooses a per-64x64 `cdef_idx` list
4501 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
4502 // tile is written a second time under `recode` and the winner
4503 // re-decoded from them.
4504 tiles: &mut Vec<Vec<u8>>,
4505 lambda: f64,
4506 fctx: &crate::decode::FrameCtx,
4507 recode: impl Fn(
4508 u8,
4509 usize,
4510 &[u8],
4511 &[Option<crate::restoration::WienerInfo>],
4512 ) -> Result<Vec<Vec<u8>>>,
4513 decode: impl Fn(
4514 &LoopFilterParams,
4515 &CdefParams,
4516 &FrameHeader,
4517 &[Vec<u8>],
4518 &LoopRestorationParams,
4519 ) -> Result<Picture>,
4520) -> Result<()> {
4521 if !search {
4522 return Ok(());
4523 }
4524 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
4525 let hdr = header.clone();
4526 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
4527 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
4528 let damping = 3 + (header.quantization.base_q_idx >> 6);
4529 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
4530 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
4531 let none_lr = LoopRestorationParams::default();
4532 // Every candidate scores the same coded tile: decode it once and re-run
4533 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
4534 // the encoder's profile before this). The per-64x64 error the CDEF
4535 // preset search reads comes off the REPLAYED picture, which is the same
4536 // picture a decode produces -- that is what the replay is pinned on.
4537 crate::decode::clear_filter_replay();
4538 // lane-av1fpar: the per-tile search is over, so every core is idle from
4539 // here to the end of the frame -- band each candidate's deblock/CDEF
4540 // replay, the capture decode's own filter chain and the loop-restoration
4541 // passes across the same workers the search used.
4542 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
4543 let ft = crate::par::timer(crate::par::S_FILTER);
4544 let search_result = crate::filter_search::pick_filters(
4545 |lf, cdef| {
4546 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
4547 return Ok(picture);
4548 }
4549 crate::decode::arm_filter_replay();
4550 let _t = crate::par::timer(crate::par::S_FIRST);
4551 decode(lf, cdef, &hdr, tiles, &none_lr)
4552 },
4553 source,
4554 luma.width,
4555 (fw, fh),
4556 damping,
4557 (sb_cols, sb_rows),
4558 lambda,
4559 );
4560 drop(ft);
4561 crate::decode::clear_filter_replay();
4562 let (lf, cdef, idx_grid, picture) = search_result?;
4563 header.loop_filter = lf;
4564 header.cdef = cdef;
4565 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
4566 // in the frame header, so a re-decode under candidate parameters cannot
4567 // search them the way deblocking and CDEF are searched above. What the
4568 // decoder hands back instead is its own filter chain's intermediates
4569 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
4570 // those, through the decoder's own Wiener kernel.
4571 //
4572 // The capture rides the decode this stage was already going to do: the
4573 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
4574 // decode of the tile as it stands. That decode's header still says
4575 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
4576 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
4577 // an approximation inside the SEARCH only; the reconstruction this
4578 // function ends up splicing is always a real decode of the real tile.
4579 let lr_on = restoration_enabled();
4580 fctx.capture_stages.set(lr_on);
4581 let mut filtered = if idx_grid.is_empty() {
4582 if lr_on {
4583 let _t = crate::par::timer(crate::par::S_CAPTURE);
4584 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
4585 } else {
4586 picture
4587 }
4588 } else {
4589 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
4590 let _t = crate::par::timer(crate::par::S_CAPTURE);
4591 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
4592 *tiles = coded;
4593 picture
4594 };
4595 fctx.capture_stages.set(false);
4596 let mut lr = LoopRestorationParams::default();
4597 if lr_on {
4598 let mut want = LoopRestorationParams {
4599 loop_restoration_size: [64, 64, 64],
4600 uses_lr: true,
4601 ..LoopRestorationParams::default()
4602 };
4603 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
4604 let lrt = crate::par::timer(crate::par::S_LR);
4605 let units = match crate::decode::take_filter_stages(fctx) {
4606 Some(stages) => crate::filter_search::pick_restoration(
4607 &stages,
4608 source[0],
4609 luma.width,
4610 (fw, fh),
4611 &want,
4612 lambda,
4613 fctx,
4614 ),
4615 None => Vec::new(),
4616 };
4617 // A frame no unit restores keeps `RESTORE_NONE` on every plane
4618 // rather than paying ~1 bit per 64x64 for a tile full of
4619 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
4620 // clip whose units never take a filter).
4621 drop(lrt);
4622 if units.iter().any(Option::is_some) {
4623 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
4624 let _t = crate::par::timer(crate::par::S_CAPTURE);
4625 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
4626 *tiles = coded;
4627 lr = want;
4628 }
4629 }
4630 header.loop_restoration = lr;
4631 let dec_cw = filtered.width.div_ceil(2);
4632 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
4633 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
4634 crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
4635 crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
4636 Ok(())
4637}
4638
4639/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
4640/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
4641/// since every block this crate's inter tile writer codes is 32x32.
4642const SIZE_GROUP_32: usize = 3;
4643
4644/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
4645/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
4646/// stack this encoder builds is ever asked to predict against.
4647const LAST_FRAME: i8 = 1;
4648
4649/// What an inter frame's intra branch spends to name each of the thirteen
4650/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
4651/// context, since an inter frame's intra blocks do not read their
4652/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
4653/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
4654/// state, so it is built once per frame.
4655fn inter_mode_bits() -> [f64; 13] {
4656 std::array::from_fn(|mode| {
4657 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
4658 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
4659 } else {
4660 0.0
4661 };
4662 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
4663 + angle
4664 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
4665 })
4666}
4667
4668/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
4669/// [`mc::predict`] takes, in the units of the plane it predicts into.
4670///
4671/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
4672/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
4673/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
4674/// domain. `luma` picks which.
4675fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
4676 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
4677}
4678
4679/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
4680/// that module): the magnitude an `MV_CLASS_n` component's own bits start
4681/// counting from.
4682fn mv_class_base(class: usize) -> i32 {
4683 if class == 0 { 0 } else { 2i32 << (class + 2) }
4684}
4685
4686/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
4687/// `tile::mv_class_of`.
4688fn mv_class_of(z: i32) -> usize {
4689 let mut class = 0;
4690 while class < 10 && mv_class_base(class + 1) <= z {
4691 class += 1;
4692 }
4693 class
4694}
4695
4696/// What [`crate::tile::write_mv_component`] (private to that module) would
4697/// spend coding one non-zero motion vector component, against the same
4698/// static default CDFs the writer starts a frame from — the same
4699/// static-table approximation [`mode_bits`] costs the luma mode symbol
4700/// through, not the tile writer's own adapting state, which this encoder has
4701/// no way to read without duplicating it block for block.
4702///
4703/// Returns `None` when `diff` needs the eighth-pel precision this crate's
4704/// frames never carry (`allow_high_precision_mv` is always off), which is
4705/// what [`round_to_valid_mv`] exists to avoid ever happening.
4706fn mv_component_bits(diff: i32) -> Option<f64> {
4707 let mag = diff.unsigned_abs() as i32;
4708 let z = mag - 1;
4709 if z & 1 == 0 {
4710 return None;
4711 }
4712 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
4713 let class = mv_class_of(z);
4714 bits += symbol_bits(&cdf::MV_CLASS, class);
4715 let local = z - mv_class_base(class);
4716 if class == 0 {
4717 let bit = (local >> 3) & 1;
4718 let fr = (local >> 1) & 3;
4719 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
4720 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
4721 } else {
4722 let d = local >> 3;
4723 let fr = (local >> 1) & 3;
4724 for i in 0..class {
4725 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
4726 }
4727 bits += symbol_bits(&cdf::MV_FR, fr as usize);
4728 }
4729 Some(bits)
4730}
4731
4732/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
4733/// own -- a second motion search per block against that reference's picture,
4734/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
4735/// off in a test build (what the lane measured both arms with).
4736fn extra_ref_new_mv() -> bool {
4737 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
4738 Some(v) if cfg!(test) => v != "0",
4739 _ => EXTRA_REF_NEW_MV,
4740 }
4741}
4742
4743/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
4744/// flat slot plan (`inter_frame_headers_slots`): every reference but
4745/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
4746/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
4747/// frame two back when there is one (otherwise it, too, names the key frame's
4748/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
4749pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
4750 let last = order_hint.wrapping_sub(1) & 0x7f;
4751 let alt = if has_altref {
4752 order_hint.wrapping_sub(2) & 0x7f
4753 } else {
4754 key_hint
4755 };
4756 [last, last, last, key_hint, last, last, alt]
4757}
4758
4759/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
4760/// header bit that lets each block choose between a single and a compound
4761/// reference. Off by default until compound prediction is measured to pay;
4762/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
4763/// runs as), and every block still codes SINGLE, so the only cost is one
4764/// `comp_mode` symbol per inter block.
4765const REFERENCE_SELECT: bool = true;
4766
4767/// [`REFERENCE_SELECT`], with the test-build environment override.
4768pub(crate) fn reference_select() -> bool {
4769 match std::env::var("EC_AV1_COMPOUND").ok() {
4770 Some(v) if cfg!(test) => v != "0",
4771 _ => REFERENCE_SELECT,
4772 }
4773}
4774
4775/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
4776/// per entry past `start`, `1` to advance and `0` to stop, at most two.
4777fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
4778 let mut bits = 0.0;
4779 let mut idx = start;
4780 while idx < start + 2 && stack.entries.len() > idx + 1 {
4781 let advance = idx < target;
4782 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
4783 if !advance {
4784 break;
4785 }
4786 idx += 1;
4787 }
4788 bits
4789}
4790
4791/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
4792/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
4793/// `assign_mv`), so the same vector costs a different residual from each.
4794fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
4795 let mut best: Option<(f64, u8)> = None;
4796 for idx in 0..3usize {
4797 if idx > 0 && stack.entries.len() <= idx {
4798 break;
4799 }
4800 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
4801 if let Some(b) = mv_residual_bits(mv, base) {
4802 let total = b + drl_bits_for(stack, 0, idx);
4803 if best.is_none_or(|(t, _)| total < t) {
4804 best = Some((total, idx as u8));
4805 }
4806 }
4807 }
4808 best
4809}
4810
4811/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
4812/// zero vector and the stack's own candidates. A neighbour block's vector is
4813/// where this block's motion most often already is, which is what pays for
4814/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
4815/// vs libaom for 0.2 s off a 6 s ladder).
4816fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
4817 let mut seeds = [(0, 0); 4];
4818 let mut n = 1;
4819 for e in stack.entries.iter().take(3) {
4820 seeds[n] = e.mv;
4821 n += 1;
4822 }
4823 (seeds, n)
4824}
4825
4826/// What [`crate::tile::write_mv`] (private to that module) would spend
4827/// coding `mv` as a residual against `pred`: the joint symbol naming which
4828/// components differ, then each differing component. `None` under the same
4829/// condition [`mv_component_bits`] returns `None`.
4830/// How many frames back `ref_frame` sits from the frame being coded, off the
4831/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
4832/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
4833/// what [`crate::motion::search`] scales its starting step by.
4834fn ref_distance(ref_frame: i8) -> u32 {
4835 let (bits, order_hint, hints) = crate::tile::order_hints();
4836 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
4837 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
4838 .unsigned_abs()
4839 .max(1);
4840 if crate::envflags::env_flag!("EC_TRACE_DIST") {
4841 eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]);
4842 }
4843 d
4844}
4845
4846fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
4847 let diff = (mv.0 - pred.0, mv.1 - pred.1);
4848 let joint = match (diff.0 != 0, diff.1 != 0) {
4849 (false, false) => 0,
4850 (false, true) => 1,
4851 (true, false) => 2,
4852 (true, true) => 3,
4853 };
4854 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
4855 for d in [diff.0, diff.1] {
4856 if d != 0 {
4857 bits += mv_component_bits(d)?;
4858 }
4859 }
4860 Some(bits)
4861}
4862
4863/// Rounds `mv` so that its residual against `pred` is one
4864/// [`crate::tile::write_mv_component`] can actually code: each component's
4865/// difference is either zero or has an even magnitude (the eighth-pel bit
4866/// `allow_high_precision_mv` off always infers as one forces the coded
4867/// magnitude odd one step further in, which comes out even here since this
4868/// crate's motion search works in whole units of that same step). Rounding
4869/// down keeps every coded MV — and so every `nearest_mv` a later block's
4870/// stack votes with — built from an even displacement from `(0, 0)`, so the
4871/// invariant holds without this function seeing the whole stack.
4872fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
4873 let round = |m: i32, p: i32| {
4874 let diff = m - p;
4875 let mag = diff.unsigned_abs() as i32;
4876 let even = mag - mag % 2;
4877 if even == 0 {
4878 p
4879 } else {
4880 p + even * diff.signum()
4881 }
4882 };
4883 (round(mv.0, pred.0), round(mv.1, pred.1))
4884}
4885
4886/// Predicts one `side`-square block by motion compensation from `reference`
4887/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
4888#[allow(clippy::too_many_arguments)]
4889fn mc_trial(
4890 plane: &Plane,
4891 x: usize,
4892 y: usize,
4893 side: usize,
4894 mv: (i32, i32),
4895 luma: bool,
4896 reference: &[u16],
4897 stride: usize,
4898 ref_width: usize,
4899 ref_height: usize,
4900 skip: bool,
4901 base_q_idx: u8,
4902 deadzone: f64,
4903 set: TxbSet, fctx: &crate::decode::FrameCtx,
4904) -> Trial {
4905 let x_q4 = mv_to_q4(x, mv.1, luma);
4906 let y_q4 = mv_to_q4(y, mv.0, luma);
4907 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
4908 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
4909 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
4910 // lane-av1speed: both buffers are per-candidate scratch on the hottest
4911 // path in the encoder, so they live on the stack -- `side` is at most
4912 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
4913 // per motion-compensated trial otherwise.
4914 let mut prediction16 = [0u16; BLOCK * BLOCK];
4915 let prediction16 = &mut prediction16[..side * side];
4916 mc::predict(
4917 reference,
4918 stride,
4919 ref_width,
4920 ref_height,
4921 x_q4,
4922 y_q4,
4923 side,
4924 side,
4925 prediction16, fctx,
4926 );
4927 let mut prediction = [0u8; BLOCK * BLOCK];
4928 let prediction = &mut prediction[..side * side];
4929 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
4930 *dst = src as u8;
4931 }
4932 plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set)
4933}
4934
4935/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
4936/// references predict into the `CONV_BUF` intermediate domain
4937/// ([`mc::predict_compound_intermediate`]) and are blended by
4938/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
4939/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
4940/// block, so the encoder's reconstruction is the decoder's.
4941#[allow(clippy::too_many_arguments)]
4942fn mc_trial_compound(
4943 plane: &Plane,
4944 x: usize,
4945 y: usize,
4946 side: usize,
4947 (mv0, mv1): ((i32, i32), (i32, i32)),
4948 luma: bool,
4949 ref0: (&[u16], usize, usize, usize),
4950 ref1: (&[u16], usize, usize, usize),
4951 base_q_idx: u8,
4952 deadzone: f64,
4953 set: TxbSet, fctx: &crate::decode::FrameCtx,
4954) -> Trial {
4955 let mut inter0 = [0i32; BLOCK * BLOCK];
4956 let mut inter1 = [0i32; BLOCK * BLOCK];
4957 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
4958 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
4959 mc::predict_compound_intermediate(
4960 r.0,
4961 r.1,
4962 r.2,
4963 r.3,
4964 mv_to_q4(x, mv.1, luma),
4965 mv_to_q4(y, mv.0, luma),
4966 mc::REF_NO_SCALE,
4967 side,
4968 side,
4969 mc::InterpFilterKind::Regular,
4970 mc::InterpFilterKind::Regular,
4971 dst,
4972 );
4973 }
4974 let mut blended16 = [0u16; BLOCK * BLOCK];
4975 let blended16 = &mut blended16[..side * side];
4976 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
4977 let mut prediction = [0u8; BLOCK * BLOCK];
4978 let prediction = &mut prediction[..side * side];
4979 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
4980 *dst = src as u8;
4981 }
4982 plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set)
4983}
4984
4985/// Codes one 32x32 block of an inter frame as whichever costs least of: each
4986/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
4987/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
4988/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
4989/// coding a real residual (`skip: false`) whenever one prices out cheaper
4990/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
4991/// missing inter `tx_type` symbol (the desync this function's candidates
4992/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
4993/// fixed.
4994///
4995/// The symbol costs this ranks candidates by use fixed contexts (0) for
4996/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
4997/// contexts for those come from its own neighbour bookkeeping
4998/// (`tile::Neighbours`), which is private to that module and not worth
4999/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
5000/// `drl_mode` contexts come straight from `stack`, which is exact, because
5001/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
5002/// the tile writer derives from the same grid state.
5003#[allow(clippy::too_many_arguments)]
5004fn search_inter_block(
5005 luma: &mut Plane,
5006 chroma: &mut [Plane; 2],
5007 (x, y): (usize, usize),
5008 search: &Search,
5009 mode_bits: &[f64; 13],
5010 reference: &Picture,
5011 stack: &MvStack,
5012 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
5013 // for the whole GOP, with the stack this block derives against it. Only
5014 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
5015 // second motion search would double the wall of the stage that already
5016 // owns most of it.
5017 extra: &[(i8, &Picture, &MvStack)],
5018 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
5019 // the caller off the same MI grid the tile writer will (empty unless the
5020 // frame carries `reference_select`).
5021 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], fctx: &crate::decode::FrameCtx,
5022) -> (BlockCoeffs, f64) {
5023 // `luma_set` is the INTRA candidates' table; the two inter candidates
5024 // below price their coefficients through `TxbSet::Luma32Inter`, which is
5025 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
5026 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
5027 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
5028 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
5029
5030 // skip / intra_inter symbol costs at a fixed context -- see this
5031 // function's doc comment.
5032 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
5033 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
5034 // `write_single_ref`'s own tree, at the fixed context this pricer uses
5035 // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0 and GOLDEN
5036 // p1=0,p3=1,p5=1.
5037 let single_ref_bits = |ref_frame: i8| {
5038 symbol_bits(&cdf::SINGLE_REF[0][0], 0)
5039 + if ref_frame == crate::mvstack::GOLDEN_FRAME {
5040 symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1)
5041 } else {
5042 symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0)
5043 }
5044 };
5045
5046 struct Candidate {
5047 cost: f64,
5048 luma: Trial,
5049 u: Trial,
5050 v: Trial,
5051 mode: u8,
5052 skip: bool,
5053 inter: Option<InterInfo>,
5054 }
5055 let mut best: Option<Candidate> = None;
5056 let mut consider = |candidate: Candidate| {
5057 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
5058 best = Some(candidate);
5059 }
5060 };
5061
5062 // The chroma trial an intra candidate prices does not depend on `mode`
5063 // at all -- both planes always code `DC_PRED` here (a coding choice this
5064 // search inherited, not this loop's to second-guess) at the same `reach:
5065 // Reach::none()` -- so it is the same call with the same inputs on every
5066 // one of the thirteen iterations below; run it once and reuse the result
5067 // rather than repeat an already-priced transform/quantize/entropy call
5068 // twelve times for nothing (bit-identical: the value each iteration
5069 // reads back is exactly what it used to recompute).
5070 let u_trial = chroma[0].trial(
5071 At {
5072 x: x / 2,
5073 y: y / 2,
5074 side: BLOCK / 2,
5075 reach: Reach::none(),
5076 set: chroma_set,
5077 },
5078 DC_PRED,
5079 search.base_q_idx,
5080 search.deadzone, fctx,
5081 );
5082 let v_trial = chroma[1].trial(
5083 At {
5084 x: x / 2,
5085 y: y / 2,
5086 side: BLOCK / 2,
5087 reach: Reach::none(),
5088 set: chroma_set,
5089 },
5090 DC_PRED,
5091 search.base_q_idx,
5092 search.deadzone, fctx,
5093 );
5094
5095 let intra_modes: Vec<u8> = match search.top_k {
5096 Some(k) if k < search.modes.len() => {
5097 let scored = luma.intra_scores(
5098 At {
5099 x,
5100 y,
5101 side: BLOCK,
5102 reach,
5103 set: luma_set,
5104 },
5105 search.modes,
5106 mode_bits,
5107 search.lambda, fctx,
5108 );
5109 prune_by_sad(search.modes, scored, k)
5110 }
5111 _ => search.modes.to_vec(),
5112 };
5113 census_add(5, 1);
5114 census_add(6, intra_modes.len());
5115 for &mode in &intra_modes {
5116 let luma_trial = luma.trial(
5117 At {
5118 x,
5119 y,
5120 side: BLOCK,
5121 reach,
5122 set: luma_set,
5123 },
5124 mode,
5125 search.base_q_idx,
5126 search.deadzone, fctx,
5127 );
5128 let u = u_trial.clone();
5129 let v = v_trial.clone();
5130 let cost = luma_trial.sse
5131 + u.sse
5132 + v.sse
5133 + search.lambda
5134 * (luma_trial.bits
5135 + u.bits
5136 + v.bits
5137 + mode_bits[usize::from(mode)]
5138 + skip_bits(false)
5139 + intra_inter_bits(false));
5140 consider(Candidate {
5141 cost,
5142 luma: luma_trial,
5143 u,
5144 v,
5145 mode,
5146 skip: false,
5147 inter: None,
5148 });
5149 }
5150
5151 // The reference frame buffer a spec decoder holds is exactly the true
5152 // (unpadded) coded extent -- a superblock whose partition stops early at
5153 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
5154 // beyond it, so those samples are never part of the decoded picture.
5155 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
5156 // reference sample position clamp), not to this crate's own
5157 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
5158 // here would let a fractional-pel read past the true edge pick up this
5159 // encoder's own uncoded padding instead of the true edge's replicated
5160 // value a decoder computes.
5161 let ref_luma = (
5162 &reference.y,
5163 reference.width,
5164 luma.true_width,
5165 luma.true_height,
5166 );
5167 let ref_u = (
5168 &reference.u,
5169 reference.width / 2,
5170 chroma[0].true_width,
5171 chroma[0].true_height,
5172 );
5173 let ref_v = (
5174 &reference.v,
5175 reference.width / 2,
5176 chroma[1].true_width,
5177 chroma[1].true_height,
5178 );
5179 // Every single-reference mode the writer can code (spec 5.11.24's symbol
5180 // chain, mirrored by `tile::write_inter_mode`), priced with the static
5181 // CDFs at this block's own stack contexts. A candidate is a motion
5182 // vector plus the cheapest syntax that reaches it, so two modes landing
5183 // on the same vector share one set of trials: the added modes cost
5184 // mode-bit arithmetic, not another motion compensation.
5185 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
5186 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
5187 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
5188 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
5189 // the loop cannot reach is never offered below -- every candidate's
5190 // index is one this same loop walks to.
5191 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
5192 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME);
5193 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
5194 (
5195 stack.nearest_mv,
5196 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
5197 InterInfo {
5198 ref1: None,
5199 mv1: (0, 0),
5200 ref_frame: crate::mvstack::LAST_FRAME,
5201 mode: InterMode::NearestMv,
5202 mv: stack.nearest_mv,
5203 ref_mv_idx: 0,
5204 },
5205 ),
5206 // GLOBALMV is the identity model's zero vector -- this encoder writes
5207 // no `gm_params` -- and the cheapest syntax of the four on the static
5208 // content where that vector is also the right one.
5209 (
5210 (0, 0),
5211 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
5212 InterInfo {
5213 ref1: None,
5214 mv1: (0, 0),
5215 ref_frame: crate::mvstack::LAST_FRAME,
5216 mode: InterMode::GlobalMv,
5217 mv: (0, 0),
5218 ref_mv_idx: 0,
5219 },
5220 ),
5221 ];
5222 let near_bits =
5223 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
5224 for idx in 1..=2usize {
5225 if let Some(e) = stack.entries.get(idx) {
5226 cands.push((
5227 e.mv,
5228 near_bits + drl_bits(1, idx),
5229 InterInfo {
5230 ref1: None,
5231 mv1: (0, 0),
5232 ref_frame: crate::mvstack::LAST_FRAME,
5233 mode: InterMode::NearMv,
5234 mv: e.mv,
5235 ref_mv_idx: idx as u8,
5236 },
5237 ));
5238 }
5239 }
5240
5241 let source_block = luma.source_block(x, y, BLOCK);
5242 let (seeds, seed_n) = mv_seeds(stack);
5243 #[cfg(test)]
5244 let t = std::time::Instant::now();
5245 let found = motion::search(
5246 ref_luma.0,
5247 ref_luma.1,
5248 ref_luma.2,
5249 ref_luma.3,
5250 &source_block,
5251 x,
5252 y,
5253 BLOCK,
5254 BLOCK,
5255 stack.pred_mv,
5256 &seeds[..seed_n],
5257 search.lambda, fctx,
5258 1,
5259 );
5260 #[cfg(test)]
5261 stage_add(0, t.elapsed());
5262 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
5263 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
5264 // the same vector costs a different residual from each: take the index
5265 // whose residual plus DRL bits is cheapest, not entry 0 by default.
5266 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
5267 cands.push((
5268 mv,
5269 last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,
5270 InterInfo {
5271 ref1: None,
5272 mv1: (0, 0),
5273 ref_frame: crate::mvstack::LAST_FRAME,
5274 mode: InterMode::NewMv,
5275 mv,
5276 ref_mv_idx,
5277 },
5278 ));
5279 }
5280
5281 // Each extra reference's own `NEWMV` vector, for the compound
5282 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
5283 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
5284 for &(ref_frame, g, gstack) in extra {
5285 let g_ref_bits = single_ref_bits(ref_frame);
5286 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
5287 cands.push((
5288 gstack.nearest_mv,
5289 g_ref_bits
5290 + g_not_new
5291 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
5292 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
5293 InterInfo {
5294 ref1: None,
5295 mv1: (0, 0),
5296 ref_frame,
5297 mode: InterMode::NearestMv,
5298 mv: gstack.nearest_mv,
5299 ref_mv_idx: 0,
5300 },
5301 ));
5302 cands.push((
5303 (0, 0),
5304 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
5305 InterInfo {
5306 ref1: None,
5307 mv1: (0, 0),
5308 ref_frame,
5309 mode: InterMode::GlobalMv,
5310 mv: (0, 0),
5311 ref_mv_idx: 0,
5312 },
5313 ));
5314 // A motion search of this reference's own: without it, GOLDEN/ALTREF
5315 // can only be coded at a vector some neighbour already found, which
5316 // is why they carried a third of the inter blocks at their two
5317 // search-free modes alone.
5318 // The search is skipped when this reference's own NEARESTMV already
5319 // prices out `margin` times better than LAST's best vector does --
5320 // one candidate evaluation (`motion::cost_at`) standing in for a
5321 // whole search of ~50.
5322 let margin = extra_new_skip_margin();
5323 let skip_search = extra_ref_new_mv()
5324 && margin > 0.0
5325 && motion::cost_at(
5326 &g.y,
5327 g.width,
5328 luma.true_width,
5329 luma.true_height,
5330 &source_block,
5331 x,
5332 y,
5333 BLOCK,
5334 BLOCK,
5335 gstack.nearest_mv,
5336 gstack.pred_mv,
5337 search.lambda,
5338 fctx,
5339 ) * margin
5340 <= found.cost;
5341 if extra_ref_new_mv() && !skip_search {
5342 let (gseeds, gn) = mv_seeds(gstack);
5343 #[cfg(test)]
5344 let t = std::time::Instant::now();
5345 let gfound = motion::search(
5346 &g.y,
5347 g.width,
5348 luma.true_width,
5349 luma.true_height,
5350 &source_block,
5351 x,
5352 y,
5353 BLOCK,
5354 BLOCK,
5355 gstack.pred_mv,
5356 &gseeds[..gn],
5357 search.lambda, fctx,
5358 ref_distance(ref_frame),
5359 );
5360 #[cfg(test)]
5361 stage_add(0, t.elapsed());
5362 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
5363 extra_new_mvs.push((ref_frame, gmv));
5364 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
5365 cands.push((
5366 gmv,
5367 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
5368 InterInfo {
5369 ref1: None,
5370 mv1: (0, 0),
5371 ref_frame,
5372 mode: InterMode::NewMv,
5373 mv: gmv,
5374 ref_mv_idx,
5375 },
5376 ));
5377 }
5378 }
5379 }
5380
5381 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
5382 // trial set each: both references predict the block and the two
5383 // predictions are averaged, which is what pays on content where neither
5384 // reference alone is right. Priced with the same static-CDF approximation
5385 // the single-reference candidates use, plus the compound-only symbols
5386 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
5387 // The two compound-mode arms, each measured alone on the BD gate before
5388 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
5389 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
5390 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
5391 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
5392 let half_new = true;
5393 for (ref1, g, cstack) in compound {
5394 let (ref1, g) = (*ref1, *g);
5395 let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME)
5396 .contains(&ref1);
5397 let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
5398 + if uni {
5399 // LAST + a backward reference: `comp_ref_type` = bidirectional,
5400 // `comp_ref` LAST, `comp_bwdref` ALTREF.
5401 symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
5402 + symbol_bits(&cdf::COMP_REF[0][0], 0)
5403 + symbol_bits(&cdf::COMP_REF[0][1], 0)
5404 + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
5405 } else {
5406 // LAST + GOLDEN: unidirectional, `uni_comp_ref` p0/p1/p2.
5407 symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
5408 + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
5409 + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
5410 + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
5411 };
5412 let mode_ctx =
5413 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
5414 let mode_bits_of =
5415 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
5416 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
5417 (
5418 cstack.nearest_mv,
5419 mode_bits_of(0),
5420 InterInfo {
5421 ref_frame: crate::mvstack::LAST_FRAME,
5422 mode: InterMode::NearestNearestMv,
5423 mv: cstack.nearest_mv.0,
5424 mv1: cstack.nearest_mv.1,
5425 ref1: Some(ref1),
5426 ref_mv_idx: 0,
5427 },
5428 ),
5429 (
5430 ((0, 0), (0, 0)),
5431 mode_bits_of(6),
5432 InterInfo {
5433 ref_frame: crate::mvstack::LAST_FRAME,
5434 mode: InterMode::GlobalGlobalMv,
5435 mv: (0, 0),
5436 mv1: (0, 0),
5437 ref1: Some(ref1),
5438 ref_mv_idx: 0,
5439 },
5440 ),
5441 ];
5442 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
5443 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
5444 // the stack is deep enough for that walk to read one.
5445 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
5446 let drl = if cstack.entries.len() > 2 {
5447 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
5448 } else {
5449 0.0
5450 };
5451 ccands.push((
5452 (e.mv0, e.mv1),
5453 mode_bits_of(1) + drl,
5454 InterInfo {
5455 ref_frame: crate::mvstack::LAST_FRAME,
5456 mode: InterMode::NearNearMv,
5457 mv: e.mv0,
5458 mv1: e.mv1,
5459 ref1: Some(ref1),
5460 ref_mv_idx: 0,
5461 },
5462 ));
5463 }
5464 // The half-new modes and `NEW_NEWMV`, all seeded from the two
5465 // single-reference searches this block already ran -- no joint search
5466 // of its own. Every residual is priced against stack entry 0, which
5467 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
5468 let cbase = cstack
5469 .entries
5470 .first()
5471 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
5472 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
5473 ccands.push((
5474 (mv, cstack.nearest_mv.1),
5475 mode_bits_of(3) + b0,
5476 InterInfo {
5477 ref_frame: crate::mvstack::LAST_FRAME,
5478 mode: InterMode::NewNearestMv,
5479 mv,
5480 mv1: cstack.nearest_mv.1,
5481 ref1: Some(ref1),
5482 ref_mv_idx: 0,
5483 },
5484 ));
5485 }
5486 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
5487 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
5488 ccands.push((
5489 (cstack.nearest_mv.0, mv1),
5490 mode_bits_of(2) + b1,
5491 InterInfo {
5492 ref_frame: crate::mvstack::LAST_FRAME,
5493 mode: InterMode::NearestNewMv,
5494 mv: cstack.nearest_mv.0,
5495 mv1,
5496 ref1: Some(ref1),
5497 ref_mv_idx: 0,
5498 },
5499 ));
5500 }
5501 let base = cbase;
5502 if let (Some(b0), Some(b1)) = (
5503 mv_residual_bits(mv, base.0),
5504 mv_residual_bits(mv1, base.1),
5505 ) {
5506 ccands.push((
5507 (mv, mv1),
5508 mode_bits_of(7) + b0 + b1,
5509 InterInfo {
5510 ref_frame: crate::mvstack::LAST_FRAME,
5511 mode: InterMode::NewNewMv,
5512 mv,
5513 mv1,
5514 ref1: Some(ref1),
5515 ref_mv_idx: 0,
5516 },
5517 ));
5518 }
5519 }
5520 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
5521 ccands.dedup_by_key(|c| c.0);
5522 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
5523 let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height);
5524 let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height);
5525 for (mvs, bits, info) in ccands {
5526 let luma_trial = mc_trial_compound(
5527 luma, x, y, BLOCK, mvs, true,
5528 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
5529 search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx,
5530 );
5531 let u = mc_trial_compound(
5532 &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false,
5533 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
5534 search.base_q_idx, search.deadzone, chroma_set, fctx,
5535 );
5536 let v = mc_trial_compound(
5537 &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false,
5538 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
5539 search.base_q_idx, search.deadzone, chroma_set, fctx,
5540 );
5541 let skip = luma_trial.levels.iter().all(|&l| l == 0)
5542 && u.levels.iter().all(|&l| l == 0)
5543 && v.levels.iter().all(|&l| l == 0);
5544 let cost = luma_trial.sse
5545 + u.sse
5546 + v.sse
5547 + search.lambda
5548 * (skip_bits(skip)
5549 + intra_inter_bits(true)
5550 + bits
5551 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
5552 consider(Candidate {
5553 cost,
5554 luma: luma_trial,
5555 u,
5556 v,
5557 mode: DC_PRED,
5558 skip,
5559 inter: Some(info),
5560 });
5561 }
5562 }
5563
5564 // One trial set per distinct (reference, vector) pair: sort, cheapest
5565 // syntax first, and drop the rest of each pair's run.
5566 cands.sort_by(|a, b| {
5567 (a.2.ref_frame, a.0)
5568 .cmp(&(b.2.ref_frame, b.0))
5569 .then(a.1.total_cmp(&b.1))
5570 });
5571 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
5572 census_add(7, cands.len());
5573 {
5574 for (mv, mode_bits_inter, info) in cands {
5575 let (ref_luma, ref_u, ref_v) = match extra
5576 .iter()
5577 .find(|(r, _, _)| *r == info.ref_frame)
5578 {
5579 Some(&(_, g, _)) => (
5580 (&g.y, g.width, luma.true_width, luma.true_height),
5581 (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
5582 (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
5583 ),
5584 None => (ref_luma, ref_u, ref_v),
5585 };
5586 let luma_trial = mc_trial(
5587 luma,
5588 x,
5589 y,
5590 BLOCK,
5591 mv,
5592 true,
5593 ref_luma.0,
5594 ref_luma.1,
5595 ref_luma.2,
5596 ref_luma.3,
5597 false,
5598 search.base_q_idx,
5599 search.deadzone,
5600 TxbSet::Luma32Inter, fctx,
5601 );
5602 let u = mc_trial(
5603 &chroma[0],
5604 x / 2,
5605 y / 2,
5606 BLOCK / 2,
5607 mv,
5608 false,
5609 ref_u.0,
5610 ref_u.1,
5611 ref_u.2,
5612 ref_u.3,
5613 false,
5614 search.base_q_idx,
5615 search.deadzone,
5616 chroma_set, fctx,
5617 );
5618 let v = mc_trial(
5619 &chroma[1],
5620 x / 2,
5621 y / 2,
5622 BLOCK / 2,
5623 mv,
5624 false,
5625 ref_v.0,
5626 ref_v.1,
5627 ref_v.2,
5628 ref_v.3,
5629 false,
5630 search.base_q_idx,
5631 search.deadzone,
5632 chroma_set, fctx,
5633 );
5634 let skip = luma_trial.levels.iter().all(|&l| l == 0)
5635 && u.levels.iter().all(|&l| l == 0)
5636 && v.levels.iter().all(|&l| l == 0);
5637 let cost = luma_trial.sse
5638 + u.sse
5639 + v.sse
5640 + search.lambda
5641 * (skip_bits(skip)
5642 + intra_inter_bits(true)
5643 + mode_bits_inter
5644 + if skip {
5645 0.0
5646 } else {
5647 luma_trial.bits + u.bits + v.bits
5648 });
5649 consider(Candidate {
5650 cost,
5651 luma: luma_trial,
5652 u,
5653 v,
5654 mode: DC_PRED,
5655 skip,
5656 inter: Some(info),
5657 });
5658 }
5659 }
5660
5661 let best = best.expect("the search offers at least the intra modes");
5662 luma.commit(x, y, BLOCK, &best.luma);
5663 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
5664 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
5665 (
5666 BlockCoeffs {
5667 luma: coeffs(&best.luma.levels, BLOCK),
5668 u: coeffs(&best.u.levels, BLOCK / 2),
5669 v: coeffs(&best.v.levels, BLOCK / 2),
5670 mode: best.mode,
5671 uv_mode: DC_PRED,
5672 skip: best.skip,
5673 inter: best.inter,
5674 eight: None,
5675 palette: None,
5676 palette_uv: None,
5677 tx_depth: 0,
5678 },
5679 best.cost,
5680 )
5681}
5682
5683/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
5684/// references name, which slot it refreshes, whether it is shown when it is
5685/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
5686/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
5687/// 0/2 alternation, every frame shown, every reference in the past).
5688///
5689/// The sign bias is carried rather than derived here because only the caller
5690/// knows what order hint each slot holds; it is armed onto the tile writer
5691/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
5692/// the writer scans the same stacks the decoder will.
5693#[derive(Debug, Clone, Copy)]
5694pub(crate) struct PyramidFrame {
5695 /// The slot `LAST_FRAME` (and every reference this encoder does not name
5696 /// apart) reads.
5697 pub last_slot: u8,
5698 /// The single slot `refresh_frame_flags` sets.
5699 pub self_slot: u8,
5700 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
5701 /// pyramid, which is what makes `sign_bias`'s last entry true.
5702 pub altref_slot: u8,
5703 /// `show_frame`: false for a hidden frame, output later by a
5704 /// `show_existing_frame` header.
5705 pub show_frame: bool,
5706 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
5707 pub sign_bias: crate::mvstack::SignBiasTable,
5708}
5709
5710/// Encodes one picture as an inter frame predicting from `reference`'s
5711/// reconstruction, which the caller decoded (or, for the frame right after
5712/// the key frame, is the key frame's own reconstruction).
5713pub(crate) fn encode_inter_frame(
5714 picture: &Picture,
5715 reference: &Picture,
5716 base_q_idx: u8,
5717 deadzone: f64,
5718 order_hint: u32,
5719 // The order hint each of the seven `ref_frame_idx` entries names, which a
5720 // decoder reads out of its own reference state -- only spec 5.9.22's
5721 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
5722 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
5723 // callers that follow this crate's own flat slot plan.
5724 order_hints: [u32; 7],
5725 render: (usize, usize),
5726 // The tables this frame's writer starts from: what the previous frame
5727 // stored into the slot this one's `primary_ref_frame` names. `None`
5728 // starts from the defaults, which is right only for the frame straight
5729 // after a key frame.
5730 start_cdfs: Option<&crate::cdf_state::Cdfs>,
5731 // The key frame's own (padded) reconstruction, which every frame of the
5732 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
5733 // with `LAST_FRAME` alone, exactly as before.
5734 golden: Option<&Picture>,
5735 // The frame two back, held in the slot this frame is about to refresh
5736 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
5737 // inter frames of a GOP, where the frame two back IS the key frame.
5738 altref: Option<&Picture>, fctx: &crate::decode::FrameCtx,
5739 // Where this frame sits in the coding-order pyramid; `None` is the flat
5740 // one-shown-frame-per-picture stream this encoder wrote before.
5741 pyramid: Option<PyramidFrame>,
5742) -> Result<Encoded> {
5743 picture.check()?;
5744 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
5745 return Err(Error::unsupported(
5746 "AV1 encode",
5747 "an inter frame is coded only for a picture that is a whole number \
5748 of 64x64 superblocks -- the inter tile writer never splits a \
5749 superblock's partition below that",
5750 ));
5751 }
5752 if reference.width != picture.width || reference.height != picture.height {
5753 return Err(Error::unsupported(
5754 "AV1 encode",
5755 "the reference picture must be the same size as the one being coded",
5756 ));
5757 }
5758
5759 // The single slot this crate's inter frames ever predict from or
5760 // refresh (`inter_frame_headers`'s contract): every frame both reads and
5761 // overwrites slot 0, so the frame just coded is always what the next one
5762 // predicts against.
5763 const LAST_SLOT: u8 = 0;
5764 // Slot 0 and slot 2 alternate so the frame two back survives one more
5765 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
5766 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
5767 // in the very slot it will overwrite.
5768 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
5769 let last_slot = pyramid.map_or(
5770 if order_hint <= 1 {
5771 LAST_SLOT
5772 } else if (order_hint - 1) % 2 == 1 {
5773 0
5774 } else {
5775 2
5776 },
5777 |p| p.last_slot,
5778 );
5779 // `render`, not `picture.width`/`picture.height`: `picture` here is
5780 // already padded to a whole number of superblocks (`encode_sequence`'s
5781 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
5782 // every true-edge clamp downstream) must come from the frame's real,
5783 // unpadded size, same as `key_frame_headers_colour` takes `render` and
5784 // not the padded picture in `encode_key_frame_inner`.
5785 let (seq, mut header) = inter_frame_headers_slots(
5786 render.0,
5787 render.1,
5788 base_q_idx,
5789 order_hint,
5790 last_slot,
5791 self_slot,
5792 match pyramid {
5793 Some(p) => p.altref_slot,
5794 None if altref.is_some() => self_slot,
5795 None => GOLDEN_SLOT,
5796 },
5797 )?;
5798 header.render_width = render.0 as u32;
5799 header.render_height = render.1 as u32;
5800 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
5801 // The order hint behind each `ref_frame_idx` entry. The flat path's own
5802 // slot plan (`inter_frame_headers_slots`) is: every reference but
5803 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
5804 // `ALTREF_FRAME`, which reads the frame two back when there is one;
5805 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
5806 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
5807 header.order_hints = order_hints;
5808 header.reference_select = reference_select();
5809 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
5810 // per-reference order-hint distance is read by the block SEARCH, which
5811 // runs long before the writer arms these (the distance-scaled search step
5812 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
5813 // never reached the tool).
5814 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
5815 if let Some(p) = pyramid {
5816 header.show_frame = p.show_frame;
5817 header.showable_frame = !p.show_frame;
5818 header.ref_frame_sign_bias = p.sign_bias;
5819 }
5820 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
5821 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
5822 // block inside this frame codes and searches its own `tx_depth`, the same
5823 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
5824 let tx_select = tx_select() && tx_select_inter();
5825 if tx_select {
5826 header.tx_mode = TxMode::Select;
5827 }
5828
5829 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
5830 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
5831 // here (see `encode_key_frame_inner`).
5832 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
5833 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
5834 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
5835 // This frame's own `allow_screen_content_tools`. It can only be set when
5836 // the SEQUENCE offers the bit at all, which is the key frame's decision
5837 // ([`SEQ_SCREEN`]): a frame header that contradicts
5838 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
5839 // encode.
5840 let screen = seq_screen()
5841 && screen_content(&picture_y8, picture.width, true_width, true_height);
5842 header.allow_screen_content_tools = screen;
5843 let mut luma = Plane {
5844 source: &picture_y8,
5845 reconstruction: vec![128; picture_y8.len()],
5846 width: picture.width,
5847 height: picture.height,
5848 true_width,
5849 true_height,
5850 tile_x0: 0,
5851 tile_y0: 0,
5852 tile_x1: picture.width,
5853 tile_y1: picture.height,
5854 };
5855 let mut chroma = [
5856 Plane {
5857 source: &picture_u8,
5858 reconstruction: vec![128; picture_u8.len()],
5859 width: picture.width / 2,
5860 height: picture.height / 2,
5861 true_width: true_width / 2,
5862 true_height: true_height / 2,
5863 tile_x0: 0,
5864 tile_y0: 0,
5865 tile_x1: picture.width / 2,
5866 tile_y1: picture.height / 2,
5867 },
5868 Plane {
5869 source: &picture_v8,
5870 reconstruction: vec![128; picture_v8.len()],
5871 width: picture.width / 2,
5872 height: picture.height / 2,
5873 true_width: true_width / 2,
5874 true_height: true_height / 2,
5875 tile_x0: 0,
5876 tile_y0: 0,
5877 tile_x1: picture.width / 2,
5878 tile_y1: picture.height / 2,
5879 },
5880 ];
5881
5882 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
5883 let search = Search {
5884 base_q_idx,
5885 deadzone,
5886 lambda: lambda_scale() * step * step,
5887 modes: &KEY_FRAME_MODES,
5888 top_k: prune_top_k_inter(),
5889 screen,
5890 };
5891 let mode_bits_table = inter_mode_bits();
5892
5893 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
5894 // coding surface's: `blocks` carries one entry per 32x32 block the tile
5895 // writer will actually visit, same count it checks `blocks.len()`
5896 // against, which is fewer than the padded surface's own block count
5897 // whenever the true size is not a 64x64 multiple.
5898 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
5899 let (cols, rows) = (cols as usize, rows as usize);
5900 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
5901 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
5902 // This frame's tile grid, as in `encode_key_frame_inner`.
5903 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
5904 let layout =
5905 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
5906 header.tile_info = tile_info_of(&layout, 1);
5907 let header_tile_info = header.tile_info.clone();
5908 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
5909 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
5910 // once per frame (lane-av1rd2), not once per block, which is a whole
5911 // plane's map per 32x32 block and now per leaf too.
5912 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
5913 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
5914 // availability -- intra edges and the MV stack's scans alike -- already
5915 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
5916 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
5917 // giving each job its own planes and its own `MiGrid` therefore leaves
5918 // every decision, and so every coded bit, exactly where the whole-frame
5919 // loop left it, at any tile count and any thread count.
5920 let (frame_width, frame_height) = (picture.width, picture.height);
5921 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
5922 let [cb, cr] = &mut chroma;
5923 let chroma_out = [
5924 crate::par::Shared::new(&mut cb.reconstruction),
5925 crate::par::Shared::new(&mut cr.reconstruction),
5926 ];
5927 let search_tile = |index: usize,
5928 fctx: &crate::decode::FrameCtx|
5929 -> Result<Vec<(usize, Quadrant)>> {
5930 // Thread-local, and this job may be running on a `search_tiles`
5931 // worker: `ref_distance`'s order-hint distance (the scaled motion
5932 // search step) is read by the SEARCH, so every worker arms it or the
5933 // tile's bits depend on the thread count.
5934 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
5935 let rect = layout.rect(index);
5936 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
5937 let mut chroma = [
5938 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
5939 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
5940 ];
5941 clip_planes_to_tile(&mut luma, &mut chroma, rect);
5942 let mut grid = MiGrid::new(mi_cols, mi_rows);
5943 grid.set_sign_bias(sign_bias);
5944 grid.set_tile_bounds(
5945 rect.mi_row0 as usize,
5946 rect.mi_col0 as usize,
5947 rect.mi_row1 as usize,
5948 rect.mi_col1 as usize,
5949 );
5950 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
5951 for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {
5952 for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {
5953 for quadrant in 0..4 {
5954 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
5955 // Same filter as the tile writer's: a quadrant whose own mi
5956 // origin is not inside the true frame is never coded.
5957 if r32 >= rows || c32 >= cols {
5958 continue;
5959 }
5960 // spec `decode_partition`'s hasRows/hasCols recomputed at this
5961 // 32x32 block's own half (`crate::tile::has_half`), same as
5962 // the key frame search: the true frame edge can fall inside a
5963 // quadrant a superblock-level check already let through, and
5964 // such a quadrant cannot be left whole -- it must split into
5965 // the 16x16 leaves that are actually inside the true frame
5966 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
5967 // arm).
5968 let (has_cols32, has_rows32) = (
5969 crate::tile::has_half(
5970 c32 as u32 * crate::tile::BLOCK_MI,
5971 crate::tile::BLOCK_MI,
5972 header.mi_cols,
5973 ),
5974 crate::tile::has_half(
5975 r32 as u32 * crate::tile::BLOCK_MI,
5976 crate::tile::BLOCK_MI,
5977 header.mi_rows,
5978 ),
5979 );
5980 if has_cols32 && has_rows32 {
5981 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
5982 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
5983 let stack =
5984 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
5985 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
5986 (crate::mvstack::GOLDEN_FRAME, golden),
5987 (crate::mvstack::ALTREF_FRAME, altref),
5988 ]
5989 .into_iter()
5990 .filter_map(|(r, pic)| {
5991 pic.map(|p| {
5992 (
5993 r,
5994 p,
5995 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
5996 )
5997 })
5998 })
5999 .collect();
6000 let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
6001 .iter()
6002 .map(|(r, p, st)| (*r, *p, st))
6003 .collect();
6004 // The COMPOUND stack of each `LAST` + extra pair, off the
6005 // same grid (and the same armed sign bias) the tile writer
6006 // rebuilds it from. Empty unless this frame codes
6007 // `reference_select`, which is what gates the syntax.
6008 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
6009 if header.reference_select {
6010 extra_stacks
6011 .iter()
6012 .map(|&(r, p, _)| {
6013 (
6014 r,
6015 p,
6016 crate::mvstack::find_mv_stack_compound(
6017 &grid,
6018 mi_row,
6019 mi_col,
6020 8,
6021 8,
6022 (crate::mvstack::LAST_FRAME, r),
6023 mi_cols,
6024 mi_rows,
6025 grid.sign_bias_table(),
6026 &[(0, 0); 7],
6027 None,
6028 ),
6029 )
6030 })
6031 .collect()
6032 } else {
6033 Vec::new()
6034 };
6035
6036 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
6037 let (block, mut cost_whole) = search_inter_block(
6038 &mut luma,
6039 &mut chroma,
6040 (x, y),
6041 &search,
6042 &mode_bits_table,
6043 reference,
6044 &stack,
6045 &extra,
6046 &compound, fctx,
6047 );
6048 cost_whole += search.lambda * partition_bits(BLOCK, false);
6049 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
6050
6051 // What four 16x16 leaves cost instead (spec
6052 // PARTITION_SPLIT at BLOCK_32X32, which
6053 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
6054 // already writes for a straddling quadrant). Each leaf is
6055 // searched against the reconstruction -- and the `mi`
6056 // grid -- the ones before it left, exactly as the writer
6057 // and the decoder will read them.
6058 //
6059 // A block the whole-32 search left skipped (no residual
6060 // at all) is not offered the split: libaom prunes the
6061 // same way at cpu-used 6, and it is where the wall would
6062 // otherwise go on static content.
6063 let leaf_positions: Vec<(usize, usize)> = (0..4)
6064 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
6065 .collect();
6066 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
6067 crate::tile::has_half(
6068 sc as u32 * crate::tile::SUB_MI,
6069 crate::tile::SUB_MI,
6070 header.mi_cols,
6071 ) && crate::tile::has_half(
6072 sr as u32 * crate::tile::SUB_MI,
6073 crate::tile::SUB_MI,
6074 header.mi_rows,
6075 )
6076 });
6077 // The breakout above: a 32x32 block that codes almost
6078 // nothing is not offered the split at all.
6079 let breakout = split_breakout_coeffs();
6080 let split = (!block.skip
6081 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
6082 && (breakout == 0 || block.luma.len() > 4 * breakout)
6083 && leaves_legal
6084 && split_inter_blocks())
6085 .then(|| {
6086 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
6087 let mut cost = search.lambda * partition_bits(BLOCK, true);
6088 let mut leaves = Vec::with_capacity(4);
6089 for &(sr, sc) in &leaf_positions {
6090 let (mi_row, mi_col) = (sr * 4, sc * 4);
6091 let (lx, ly) = (sc * SUB, sr * SUB);
6092 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
6093 let stack = find_mv_stack(
6094 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
6095 );
6096 let cstacks: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
6097 if header.reference_select && leaf_compound() {
6098 [
6099 (crate::mvstack::GOLDEN_FRAME, golden),
6100 (crate::mvstack::ALTREF_FRAME, altref),
6101 ]
6102 .into_iter()
6103 .filter_map(|(r, pic)| {
6104 pic.map(|p| {
6105 (
6106 r,
6107 p,
6108 crate::mvstack::find_mv_stack_compound(
6109 &grid, mi_row, mi_col, 4, 4,
6110 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6111 grid.sign_bias_table(), &[(0, 0); 7], None,
6112 ),
6113 )
6114 })
6115 })
6116 .collect()
6117 } else {
6118 Vec::new()
6119 };
6120 let (leaf, leaf_cost) = code_square_inter(
6121 &mut luma,
6122 &mut chroma,
6123 (lx, ly),
6124 SUB,
6125 &search,
6126 &mode_bits_table,
6127 reference,
6128 &stack, &cstacks, fctx,
6129 );
6130 let leaf_cost = leaf_cost
6131 + search.lambda * partition_bits(SUB, false);
6132 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
6133
6134 // And what four 8x8 leaves cost instead --
6135 // the same tree one step further down, which
6136 // the writer codes as a real PARTITION_SPLIT
6137 // at BLOCK_16X16 (lane-av1rd2). Same
6138 // skipped-block prune as the level above.
6139 let eight = (!leaf.skip
6140 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
6141 && (breakout == 0 || leaf.luma.len() > breakout)
6142 && split_inter_8())
6143 .then(|| {
6144 restore(
6145 &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base,
6146 );
6147 let mut cost8 = search.lambda
6148 * (partition_bits(SUB, true)
6149 + 4.0 * partition_bits(8, false));
6150 let mut eight = Vec::with_capacity(4);
6151 for i in 0..4 {
6152 let (mr, mc) =
6153 (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
6154 let stack8 = find_mv_stack(
6155 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
6156 );
6157 let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
6158 if header.reference_select && leaf_compound() {
6159 [
6160 (crate::mvstack::GOLDEN_FRAME, golden),
6161 (crate::mvstack::ALTREF_FRAME, altref),
6162 ]
6163 .into_iter()
6164 .filter_map(|(r, pic)| {
6165 pic.map(|p| {
6166 (
6167 r,
6168 p,
6169 crate::mvstack::find_mv_stack_compound(
6170 &grid, mr, mc, 2, 2,
6171 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6172 grid.sign_bias_table(), &[(0, 0); 7], None,
6173 ),
6174 )
6175 })
6176 })
6177 .collect()
6178 } else {
6179 Vec::new()
6180 };
6181 let (leaf8, cost) = code_square_inter(
6182 &mut luma,
6183 &mut chroma,
6184 (lx + (i % 2) * 8, ly + (i / 2) * 8),
6185 8,
6186 &search,
6187 &mode_bits_table,
6188 reference,
6189 &stack8, &cstacks8, fctx,
6190 );
6191 cost8 += cost;
6192 record_mi(&mut grid, mr, mc, 2, leaf8.inter);
6193 eight.push(leaf8);
6194 }
6195 (eight, cost8)
6196 });
6197 match eight {
6198 Some((eight, cost8)) if cost8 < leaf_cost => {
6199 partition_hit(3);
6200 cost += cost8;
6201 leaves.push(BlockCoeffs {
6202 eight: Some(eight),
6203 ..BlockCoeffs::default()
6204 });
6205 continue;
6206 }
6207 Some(_) => restore(
6208 &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf,
6209 ),
6210 None => {}
6211 }
6212 partition_hit(2);
6213 cost += leaf_cost;
6214 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter);
6215 leaves.push(leaf);
6216 }
6217 (leaves, cost)
6218 });
6219 if let Some((leaves, cost)) = split {
6220 if cost < cost_whole {
6221 // The leaves' own `mi` cells are already in the
6222 // grid, and their reconstruction is what the
6223 // planes hold.
6224 partition_hit(1);
6225 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
6226 continue;
6227 }
6228 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
6229 }
6230 partition_hit(0);
6231 record_mi(&mut grid, mi_row, mi_col, 8, block.inter);
6232 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
6233 } else {
6234 // The sub-positions actually inside the true frame, same
6235 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
6236 let sub_positions: Vec<(usize, usize)> = (0..4)
6237 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
6238 .filter(|&(sr, sc)| {
6239 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
6240 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
6241 })
6242 .collect();
6243 // Each leaf searches intra against its own `NEARESTMV`
6244 // candidate (`code_square_inter`), same real-inter choice
6245 // `search_inter_block` makes for a whole 32x32 block, at
6246 // this leaf's own 4x4-mi mv-stack window -- unless the
6247 // leaf's own half itself straddles the true edge, which
6248 // it codes as two (or one, at a true corner) 8x8 leaves
6249 // (`crate::tile::write_leaf8`'s inter counterpart),
6250 // mirroring the key frame search's straddling-16x16
6251 // handling above (lane-av1inter8).
6252 let mut leaves = Vec::with_capacity(sub_positions.len());
6253 for (sr, sc) in sub_positions {
6254 let (has_cols16, has_rows16) = (
6255 crate::tile::has_half(
6256 sc as u32 * crate::tile::SUB_MI,
6257 crate::tile::SUB_MI,
6258 header.mi_cols,
6259 ),
6260 crate::tile::has_half(
6261 sr as u32 * crate::tile::SUB_MI,
6262 crate::tile::SUB_MI,
6263 header.mi_rows,
6264 ),
6265 );
6266 if !has_cols16 && !has_rows16 {
6267 return Err(Error::unsupported(
6268 "AV1 encode",
6269 format!(
6270 "the 16x16 block at ({sc},{sr}) straddles the true \
6271 frame edge in a way that needs a rectangular \
6272 (HORZ/VERT) transform this encoder does not code yet"
6273 ),
6274 ));
6275 }
6276 if has_cols16 && has_rows16 {
6277 let (x, y) = (sc * SUB, sr * SUB);
6278 let (mi_row, mi_col) = (sr * 4, sc * 4);
6279 let stack = find_mv_stack(
6280 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
6281 );
6282 let (block, _) = code_square_inter(
6283 &mut luma,
6284 &mut chroma,
6285 (x, y),
6286 SUB,
6287 &search,
6288 &mode_bits_table,
6289 reference,
6290 &stack, &[], fctx,
6291 );
6292 // One publication point for every coded leaf
6293 // (`record_mi`): this site used to spell the vote
6294 // out with `ref_frame` pinned to LAST and `mv1`
6295 // to (0,0), which is the encoder-grid-drift class
6296 // -- correct only for as long as a leaf can never
6297 // be compound.
6298 record_mi(&mut grid, mi_row, mi_col, 4, block.inter);
6299 leaves.push(block);
6300 } else {
6301 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
6302 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
6303 let mut eight = Vec::with_capacity(2);
6304 for i in 0..4 {
6305 let leaf_x = x_sub + (i % 2) * 8;
6306 let leaf_y = y_sub + (i / 2) * 8;
6307 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
6308 continue;
6309 }
6310 let (mi_row, mi_col) =
6311 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
6312 let stack = find_mv_stack(
6313 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
6314 );
6315 let (leaf, _) = code_square_inter(
6316 &mut luma,
6317 &mut chroma,
6318 (leaf_x, leaf_y),
6319 8,
6320 &search,
6321 &mode_bits_table,
6322 reference,
6323 &stack, &[], fctx,
6324 );
6325 // Same publication point as the 16x16
6326 // straddling leaf above (`record_mi`).
6327 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter);
6328 eight.push(leaf);
6329 }
6330 leaves.push(BlockCoeffs {
6331 eight: Some(eight),
6332 ..BlockCoeffs::default()
6333 });
6334 }
6335 }
6336 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
6337 }
6338 }
6339 }
6340 }
6341 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
6342 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
6343 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
6344 for (&out, tile) in chroma_out.iter().zip(&chroma) {
6345 copy_rect(
6346 out,
6347 &tile.reconstruction,
6348 frame_width / 2,
6349 x0 / 2,
6350 y0 / 2,
6351 x1.div_ceil(2),
6352 y1.div_ceil(2),
6353 );
6354 }
6355 Ok(blocks)
6356 };
6357 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
6358 .into_iter()
6359 .flatten()
6360 {
6361 blocks[at] = quadrant;
6362 }
6363
6364 let modes = blocks
6365 .iter()
6366 .flat_map(Quadrant::blocks)
6367 .map(|b| b.mode)
6368 .collect::<Vec<_>>();
6369 let inter_block_share = blocks
6370 .iter()
6371 .flat_map(Quadrant::blocks)
6372 .filter(|b| b.inter.is_some())
6373 .count() as f64
6374 / modes.len() as f64;
6375 for block in blocks.iter().flat_map(Quadrant::blocks) {
6376 if let Some(info) = block.inter {
6377 let r = (info.ref_frame as usize).min(7);
6378 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6379 }
6380 }
6381 #[cfg(test)]
6382 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
6383 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
6384 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
6385 // next frame's writer starts from them -- exactly what
6386 // `crate::stream::stored_cdfs_for` hands the decoder.
6387 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
6388 let cdfs = start_cdfs
6389 .cloned()
6390 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
6391 let start_cdfs = CdfSnapshot(cdfs);
6392 let reference_select_bit = header.reference_select;
6393 let order_hint_bits = seq.order_hint_bits;
6394 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
6395 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
6396 // What this frame stores is the LARGEST tile's end-of-tile tables --
6397 // its own header's `context_update_tile_id` (spec 7.20), which
6398 // `tile_info_of` set to exactly that tile.
6399 let store_tile = layout.largest_tile();
6400 let end_cdfs = std::cell::RefCell::new(None);
6401 // As in `encode_key_frame_inner`: every tile starts from this frame's
6402 // own tables, so no tile depends on any other.
6403 let code_tiles = |bits: u8,
6404 sb_cols: usize,
6405 cdef_grid: &[u8],
6406 units: &[Option<crate::restoration::WienerInfo>]|
6407 -> Result<Vec<Vec<u8>>> {
6408 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
6409 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
6410 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
6411 crate::tile::arm_sign_bias(sign_bias);
6412 // Thread-locals: every tile job arms its own worker.
6413 crate::tile::arm_reference_select(reference_select_bit);
6414 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
6415 crate::tile::arm_screen(screen);
6416 let mut cdfs = start_cdfs.0.clone();
6417 // Each tile's own MV grid: a candidate scan never reaches past
6418 // the tile's bounds, so a grid holding only this tile's own
6419 // blocks reads exactly as the decoder's frame-wide one does
6420 // under `MiGrid::set_tile_bounds`.
6421 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
6422 mv_grid.set_sign_bias(sign_bias);
6423 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
6424 mi_cols,
6425 mi_rows,
6426 base_q_idx,
6427 &blocks,
6428 tx_select,
6429 &mut cdfs,
6430 layout.rect(index),
6431 &mut mv_grid,
6432 )?;
6433 Ok((bytes, Some(cdfs)))
6434 })?;
6435 if let Some(cdfs) = stored {
6436 *end_cdfs.borrow_mut() = Some(cdfs);
6437 }
6438 Ok(out)
6439 };
6440 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
6441 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
6442 // this tile against the same single-slot reference this encoder predicted
6443 // from, under each candidate level.
6444 // The reference a DECODER holds is this frame's cropped size, not the
6445 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
6446 // reference whose height is not the header's own `frame_height` (spec
6447 // 7.9's compatible-size rule), and the chained-decode round trips prove
6448 // the two predict identically.
6449 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
6450 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
6451 reference.clone()
6452 } else {
6453 Picture {
6454 width: fw,
6455 height: fh,
6456 y: crop_plane(&reference.y, reference.width, fw, fh),
6457 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
6458 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
6459 }
6460 };
6461 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
6462 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
6463 // blocks may name GOLDEN needs that plane too, cropped the same way.
6464 let trial_golden = golden.map(|g| {
6465 if (g.width, g.height) == (fw, fh) {
6466 g.clone()
6467 } else {
6468 Picture {
6469 width: fw,
6470 height: fh,
6471 y: crop_plane(&g.y, g.width, fw, fh),
6472 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
6473 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
6474 }
6475 }
6476 });
6477 let trial_altref = altref.map(|a| {
6478 if (a.width, a.height) == (fw, fh) {
6479 a.clone()
6480 } else {
6481 Picture {
6482 width: fw,
6483 height: fh,
6484 y: crop_plane(&a.y, a.width, fw, fh),
6485 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
6486 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
6487 }
6488 }
6489 });
6490 let mut refs: [Option<&Picture>; 8] = [None; 8];
6491 refs[1] = Some(&trial_ref);
6492 refs[4] = trial_golden.as_ref();
6493 refs[7] = trial_altref.as_ref();
6494 let refpix = crate::decode::RefPix::ready(refs);
6495 pick_and_apply_filters(
6496 &mut header,
6497 &mut luma,
6498 &mut chroma,
6499 [&picture_y8, &picture_u8, &picture_v8],
6500 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
6501 // this frame's own `tx_select`, so the search runs under inter
6502 // `TxMode::Select` too (it used to skip and leave every inter frame
6503 // unfiltered once Select became the default).
6504 true,
6505 &mut tiles,
6506 search.lambda,
6507 fctx,
6508 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
6509 // are what the NEXT frame writes from, so the winning re-code
6510 // publishes its own into `end_cdfs` -- the first write's are stale
6511 // the moment a second tile is coded.
6512 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
6513 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
6514 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
6515 crate::decode::decode_inter_frame_tiles_lr(
6516 &payloads,
6517 &header_tile_info,
6518 h.mi_cols,
6519 h.mi_rows,
6520 base_q_idx,
6521 h.frame_width,
6522 h.frame_height,
6523 &refpix,
6524 cdef,
6525 lf,
6526 h.allow_high_precision_mv,
6527 h.force_integer_mv,
6528 Some(mc::InterpFilterKind::Regular),
6529 seq.enable_dual_filter,
6530 h.reference_select,
6531 tx_select,
6532 lr,
6533 // The trial decode re-reads the tile the writer just wrote,
6534 // so it starts from the same tables the writer did (this
6535 // frame's `start_cdfs`), not from the defaults.
6536 Some(start_cdfs.0.clone()),
6537 sign_bias,
6538 h.allow_screen_content_tools,
6539 fctx,
6540 )
6541 },
6542 )?;
6543 let mut cdfs = end_cdfs
6544 .into_inner()
6545 .unwrap_or_else(|| start_cdfs.0.clone());
6546 cdfs.reset_counts();
6547 let next_cdfs = CdfSnapshot(cdfs);
6548 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
6549 header.tile_info.tile_size_bytes = tile_size_bytes;
6550 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
6551 let mut stream = temporal_delimiter();
6552 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
6553
6554 let [u, v] = chroma;
6555 Ok(Encoded {
6556 stream,
6557 modes,
6558 inter_block_share,
6559 reconstruction: Picture {
6560 width: luma.width,
6561 height: luma.height,
6562 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
6563 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
6564 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
6565 },
6566 tile,
6567 mi_cols: header.mi_cols,
6568 mi_rows: header.mi_rows,
6569 base_q_idx,
6570 tx_select,
6571 screen,
6572 start_cdfs,
6573 next_cdfs,
6574 loop_filter: header.loop_filter,
6575 cdef: header.cdef,
6576 loop_restoration: header.loop_restoration,
6577 })
6578}
6579
6580/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
6581/// frame's temporal unit followed by one inter frame's temporal unit per
6582/// remaining picture, all sharing the key frame's sequence header -- and
6583/// each frame's own [`Encoded`], in coding order.
6584#[derive(Clone, Debug)]
6585pub struct EncodedSequence {
6586 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
6587 /// sequence header and the key frame) followed by each later frame's
6588 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
6589 /// the sequence header the key frame carried).
6590 pub stream: Vec<u8>,
6591 /// One entry per picture, in coding order.
6592 pub frames: Vec<Encoded>,
6593}
6594
6595/// Encodes a sequence of pictures as a key frame followed by one inter frame
6596/// per remaining picture, each predicting from the previous frame's own
6597/// decoded reconstruction — never from the source, which is what a decoder
6598/// cannot see. Every picture must be the same even size (any even width and
6599/// height — each is padded to a whole number of 64x64 superblocks
6600/// internally, which is what lets an inter frame's reference always match
6601/// the frame being coded against it), and `pictures` must be non-empty.
6602///
6603/// # Errors
6604/// Returns an error when `pictures` is empty, when any picture besides the
6605/// first is not the same size as the first, or under the same conditions
6606/// [`encode_key_frame`] and the inter frame path do.
6607pub(crate) fn encode_sequence_with_ctx(
6608 pictures: &[Picture],
6609 base_q_idx: u8,
6610 deadzone: f64, fctx: &crate::decode::FrameCtx,
6611) -> Result<EncodedSequence> {
6612 let Some((first, rest)) = pictures.split_first() else {
6613 return Err(Error::unsupported(
6614 "AV1 encode",
6615 "a sequence needs at least one picture",
6616 ));
6617 };
6618 first.check_even()?;
6619 let render = (first.width, first.height);
6620 // The key frame and every inter frame after it are coded at the same
6621 // padded size, so the reference each inter frame predicts from -- the
6622 // previous frame's own uncropped reconstruction, at the size a decoder's
6623 // reference buffer actually holds -- always matches the frame being
6624 // coded against it.
6625 let key = encode_key_frame_inner(
6626 &first.padded_to(SUPERBLOCK),
6627 base_q_idx,
6628 deadzone,
6629 &KEY_FRAME_MODES,
6630 split_blocks(),
6631 render,
6632 unspecified_color_config(), fctx,
6633 )?;
6634 let mut stream = key.stream.clone();
6635 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
6636 // key frame refreshes every slot, each inter frame only slot 0), which is
6637 // what `GOLDEN_FRAME` names.
6638 let golden = key.reconstruction.clone();
6639 // The frame two back, once there is one that is not the key frame
6640 // itself (which `GOLDEN_FRAME` already names).
6641 let mut prev2: Option<Picture> = None;
6642 let mut carried = key.next_cdfs.clone();
6643 let mut reference = key.reconstruction.clone();
6644 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
6645 for (i, picture) in rest.iter().enumerate() {
6646 picture.check_even()?;
6647 if (picture.width, picture.height) != render {
6648 return Err(Error::unsupported(
6649 "AV1 encode",
6650 "every picture in a sequence must be the same size as the first",
6651 ));
6652 }
6653 let order_hint = (i + 1) as u32;
6654 let inter = encode_inter_frame(
6655 &picture.padded_to(SUPERBLOCK),
6656 &reference,
6657 base_q_idx,
6658 deadzone,
6659 order_hint,
6660 flat_order_hints(order_hint, 0, prev2.is_some()),
6661 render,
6662 Some(&carried.0),
6663 Some(&golden),
6664 prev2.as_ref(), fctx,
6665 None,
6666 )?;
6667 stream.extend_from_slice(&inter.stream);
6668 carried = inter.next_cdfs.clone();
6669 prev2 = Some(std::mem::replace(
6670 &mut reference,
6671 inter.reconstruction.clone(),
6672 ));
6673 frames.push(crop_encoded(&inter, render.0, render.1));
6674 }
6675 Ok(EncodedSequence { stream, frames })
6676}
6677
6678#[cfg(test)]
6679mod tests {
6680
6681 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
6682 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
6683 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
6684 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
6685 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
6686 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
6687 /// only a quarter of the 16x8 table and read the wrong byte for every
6688 /// block row but the first (silently wrong above-right/below-left
6689 /// availability -- wrong pixels, no error).
6690 #[test]
6691 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
6692 for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
6693 let (bw_log2, bh_log2) =
6694 ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize);
6695 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
6696 for (name, table) in
6697 [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)]
6698 {
6699 assert_eq!(
6700 table.len() * 8,
6701 rows * cols,
6702 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
6703 );
6704 let mut seen = vec![0u32; table.len() * 8];
6705 for blk_row in 0..rows {
6706 for blk_col in 0..cols {
6707 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
6708 assert!(
6709 idx < seen.len(),
6710 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
6711 );
6712 seen[idx] += 1;
6713 }
6714 }
6715 assert!(
6716 seen.iter().all(|&n| n == 1),
6717 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
6718 (row stride is not {cols})"
6719 );
6720 }
6721 }
6722 }
6723 use super::*;
6724 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
6725 use std::io::Write;
6726 use std::process::{Command, Stdio};
6727
6728 /// Every rectangular shape this decoder codes, at every position a block
6729 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
6730 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
6731 /// (`reconintra.c`) answer, whose bodies are ported below.
6732 ///
6733 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
6734 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
6735 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
6736 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
6737 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
6738 /// oracle's own arrays, so a re-routed or truncated table fails here even
6739 /// where the two rows happen to agree.
6740 ///
6741 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
6742 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
6743 /// callers handle by predicting each transform unit as its own block.
6744 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
6745 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
6746 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
6747 /// (the horizontal shapes, which those partitions never produce).
6748 #[test]
6749 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
6750 let fctx = &crate::decode::FrameCtx::new();
6751 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
6752 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
6753 (4, 8, 64, 9280, 64, 550),
6754 (8, 4, 64, 3712, 64, 9630),
6755 (8, 16, 16, 2352, 16, 134),
6756 (16, 8, 16, 960, 16, 2400),
6757 (16, 32, 4, 620, 4, 32),
6758 (32, 16, 4, 32, 4, 184),
6759 (32, 64, 1, 127, 1, 0),
6760 (64, 32, 1, 19, 1, 34),
6761 (4, 16, 32, 5472, 32, 14),
6762 (16, 4, 32, 960, 32, 6464),
6763 (8, 32, 8, 1400, 8, 2),
6764 (32, 8, 8, 32, 8, 1136),
6765 (16, 64, 2, 382, 2, 0),
6766 (64, 16, 2, 4, 2, 84),
6767 ];
6768 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
6769 /// a block whose transform covers it whole (`row_off == col_off == 0`,
6770 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
6771 /// superblock (`sb_mi_size == 16`).
6772 fn libaom_reach(
6773 bw: usize,
6774 bh: usize,
6775 x: usize,
6776 y: usize,
6777 width: usize,
6778 height: usize, _fctx: &crate::decode::FrameCtx,
6779 ) -> (bool, bool) {
6780 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
6781 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
6782 let sb_mi_size = 16usize;
6783 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
6784 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
6785 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
6786 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
6787 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
6788 // has_top_right: top_available && right_available, then row_off == 0.
6789 let top_right = if y == 0 || x + bw >= width {
6790 false
6791 } else if blk_row_in_sb == 0 {
6792 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
6793 // `bw_unit < bw_unit`, false for a whole-block transform.)
6794 true
6795 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
6796 false
6797 } else {
6798 bit(tr_table)
6799 };
6800 // has_bottom_left: bottom_available && left_available, col_off == 0.
6801 let bottom_left = if x == 0 || y + bh >= height {
6802 false
6803 } else if blk_col_in_sb == 0 {
6804 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
6805 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
6806 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
6807 false
6808 } else {
6809 bit(bl_table)
6810 };
6811 (top_right, bottom_left)
6812 }
6813 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
6814 let (tr, bl) = rect_reach_tables(bw, bh);
6815 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
6816 assert_eq!(
6817 (tr.len(), sum(tr), bl.len(), sum(bl)),
6818 (tr_len, tr_sum, bl_len, bl_sum),
6819 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
6820 );
6821 // Two superblocks across and down, so the superblock-relative
6822 // position (and not the frame position) is what decides.
6823 for sb_y in [0usize, 64] {
6824 for sb_x in [0usize, 64] {
6825 for y in (sb_y..sb_y + 64).step_by(bh) {
6826 for x in (sb_x..sb_x + 64).step_by(bw) {
6827 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
6828 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
6829 assert_eq!(
6830 (got.above_right, got.below_left),
6831 want,
6832 "{bw}x{bh} at ({x}, {y})"
6833 );
6834 }
6835 }
6836 }
6837 }
6838 }
6839 }
6840
6841 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
6842 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
6843 /// aomenc gate decodes its stream through ffmpeg and is meaningless
6844 /// without it -- turns it into a hard failure. Without this the require
6845 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
6846 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
6847 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
6848 fn have_ffmpeg() -> bool {
6849 let present = Command::new("ffmpeg")
6850 .arg("-version")
6851 .stdout(Stdio::null())
6852 .stderr(Stdio::null())
6853 .status()
6854 .is_ok_and(|s| s.success());
6855 assert!(
6856 present
6857 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
6858 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
6859 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
6860 );
6861 present
6862 }
6863
6864 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
6865 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
6866 let mut child = Command::new("ffmpeg")
6867 .args([
6868 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
6869 ])
6870 .stdin(Stdio::piped())
6871 .stdout(Stdio::piped())
6872 .stderr(Stdio::piped())
6873 .spawn()
6874 .expect("ffmpeg failed to start");
6875 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
6876 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
6877 // fills before the last input byte is written -- which is exactly what
6878 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
6879 // (measured: 45 min, both processes at 0% CPU). A write error here is
6880 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
6881 // below, are the real diagnosis.
6882 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
6883 let payload = stream.to_vec();
6884 let writer = std::thread::spawn(move || {
6885 let _ = stdin.write_all(&payload);
6886 });
6887 let out = child.wait_with_output().expect("ffmpeg failed to run");
6888 writer.join().expect("ffmpeg stdin writer thread");
6889 assert!(
6890 out.status.success(),
6891 "ffmpeg refused the stream: {}",
6892 String::from_utf8_lossy(&out.stderr)
6893 );
6894 let (luma, chroma) = (width * height, width * height / 4);
6895 assert_eq!(
6896 out.stdout.len(),
6897 luma + 2 * chroma,
6898 "expected one 4:2:0 frame"
6899 );
6900 Picture {
6901 width,
6902 height,
6903 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
6904 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
6905 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
6906 }
6907 }
6908
6909 /// A picture with something of everything in it: a gradient, an edge, a
6910 /// ripple and a block of flat colour, none of them aligned to the block
6911 /// grid.
6912 /// The in-loop filters actually FIRE and the stream still decodes to
6913 /// exactly what the encoder kept as its reconstruction
6914 /// (gate-blind-to-feature: a filter search that always answered "off"
6915 /// would leave every other test just as green, and the BD gate that
6916 /// would notice is `#[ignore]`d).
6917 ///
6918 /// Run:
6919 /// cargo test -p ec-av1 --release --lib -- \
6920 /// encode::tests::the_filter_search_picks_real_filters
6921 #[test]
6922 fn the_filter_search_picks_real_filters() {
6923 let fctx = &crate::decode::FrameCtx::new();
6924 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
6925 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
6926 let fired = encoded
6927 .frames
6928 .iter()
6929 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
6930 .count();
6931 assert!(
6932 fired > 0,
6933 "no frame of this sequence chose any in-loop filtering: {:?}",
6934 encoded
6935 .frames
6936 .iter()
6937 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
6938 .collect::<Vec<_>>()
6939 );
6940 // The reconstruction the encoder predicts from is the FILTERED one,
6941 // and it is what a decoder of the stream produces -- byte for byte,
6942 // frame for frame.
6943 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
6944 assert_eq!(decoded.len(), encoded.frames.len());
6945 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
6946 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
6947 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
6948 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
6949 }
6950 }
6951
6952 fn test_card(width: usize, height: usize) -> Picture {
6953 let mut picture = Picture::grey(width, height);
6954 for y in 0..height {
6955 for x in 0..width {
6956 let gradient = x as f64 * 200.0 / width as f64;
6957 let ripple = 30.0
6958 * (x as f64 * std::f64::consts::PI / 23.0).sin()
6959 * (y as f64 * std::f64::consts::PI / 37.0).cos();
6960 let edge = if x > width * 3 / 7 && y > height / 3 {
6961 40.0
6962 } else {
6963 0.0
6964 };
6965 picture.y[y * width + x] =
6966 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
6967 }
6968 }
6969 for y in 0..height / 2 {
6970 for x in 0..width / 2 {
6971 let i = y * width / 2 + x;
6972 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
6973 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
6974 }
6975 }
6976 picture
6977 }
6978
6979 fn psnr(a: &[u16], b: &[u16]) -> f64 {
6980 let squared: f64 = a
6981 .iter()
6982 .zip(b)
6983 .map(|(&x, &y)| {
6984 let d = f64::from(x) - f64::from(y);
6985 d * d
6986 })
6987 .sum();
6988 if squared == 0.0 {
6989 return f64::INFINITY;
6990 }
6991 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
6992 }
6993
6994 /// The claim the whole encoder rests on: what a decoder produces is what
6995 /// the encoder said it would, sample for sample, on every plane.
6996 ///
6997 /// Prediction reads the reconstruction, so a single sample of drift
6998 /// anywhere would spread into every block below and to the right of it —
6999 /// which is why this is an equality and not a tolerance.
7000 #[test]
7001 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
7002 let fctx = &crate::decode::FrameCtx::new();
7003 if !have_ffmpeg() {
7004 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
7005 return;
7006 }
7007 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] {
7008 let picture = test_card(width, height);
7009 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7010 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7011 assert_eq!(
7012 decoded.y, encoded.reconstruction.y,
7013 "{width}x{height}: luma"
7014 );
7015 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
7016 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
7017 }
7018 // One q index from each of the four coefficient-CDF contexts
7019 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
7020 let (width, height) = (64usize, 64usize);
7021 let picture = test_card(width, height);
7022 let _ = take_tx_depth_hits();
7023 for &q in &[15u8, 45, 100, 200] {
7024 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
7025 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7026 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
7027 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
7028 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
7029 }
7030 // lane-av1tx: the exactness above is only a claim about SPLIT
7031 // transforms if some block actually split one (`gate-blind-to-feature`
7032 // -- with `tx_depth` stuck at 0 every assert here passes on the
7033 // pre-lane stream). The test card's edges split at these four
7034 // quantizers; the counter is per-process (another test encoding in
7035 // parallel can only ADD to it, so this can be masked, never falsely
7036 // failed), so it is read once for the whole q ladder.
7037 let depths = take_tx_depth_hits();
7038 assert!(
7039 depths[1] + depths[2] > 0,
7040 "no block split its transform: depths {depths:?}"
7041 );
7042 }
7043
7044 /// A synthetic screen-content picture -- a few flat colours in a grid of
7045 /// boxes with hard edges and text-like bars, the shape a desktop capture
7046 /// has -- so the palette path is exercised on content it is for.
7047 #[cfg(test)]
7048 fn screen_card(width: usize, height: usize) -> Picture {
7049 const INK: [u16; 4] = [16, 90, 180, 235];
7050 let mut picture = Picture::grey(width, height);
7051 for y in 0..height {
7052 for x in 0..width {
7053 let cell = (x / 24 + y / 24) % 2;
7054 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
7055 picture.y[y * width + x] = INK[cell * 2 + bar];
7056 }
7057 }
7058 // Four chroma colours, not two: a two-colour chroma block only ever
7059 // codes a `PaletteSizeUV` of 2, which leaves
7060 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
7061 // deltas and the neighbour cache flags, exercised only when
7062 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
7063 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
7064 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
7065 for y in 0..height / 2 {
7066 for x in 0..width / 2 {
7067 let cell = (x / 12 + 2 * (y / 12)) % 4;
7068 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
7069 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
7070 }
7071 }
7072 picture
7073 }
7074
7075 /// The lane's own end-to-end check: on screen content the detector fires,
7076 /// blocks really take a palette (fire count, class
7077 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
7078 /// symbol this lane writes -- reconstructs exactly what the encoder did.
7079 /// The film-shaped `test_card` must NOT trip the detector, which is what
7080 /// keeps every non-screen stream byte-identical.
7081 #[test]
7082 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
7083 let fctx = &crate::decode::FrameCtx::new();
7084 let (width, height) = (192usize, 96usize);
7085 let _ = crate::tile::take_palette_hits();
7086 let picture = screen_card(width, height);
7087 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7088 assert!(
7089 encoded.screen,
7090 "the detector did not fire on screen content -- no palette syntax was coded at all"
7091 );
7092 let hits = crate::tile::take_palette_hits();
7093 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
7094 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
7095 // The chroma half is a claim about the plane-1 syntax only if some
7096 // block really took a chroma palette (`gate-blind-to-feature`): every
7097 // exactness assert below passes on a stream that codes
7098 // `palette_uv_mode == 0` everywhere.
7099 let uv_hits = crate::tile::take_palette_uv_hits();
7100 assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
7101 let uv_cached = crate::tile::take_palette_uv_cache_hits();
7102 eprintln!(
7103 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
7104 uv_hits[0],
7105 &uv_hits[2..]
7106 );
7107 assert!(
7108 uv_cached > 0,
7109 "no chroma base colour came out of the neighbour cache -- \
7110 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
7111 );
7112 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
7113 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
7114 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
7115 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
7116 if !have_ffmpeg() {
7117 eprintln!("SKIP the ffmpeg half: no ffmpeg");
7118 return;
7119 }
7120 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7121 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
7122 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
7123 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
7124 // A whole GOP: the inter frames' own intra blocks carry the palette
7125 // syntax too (the three intra arms of the inter writers), which only
7126 // ffmpeg reading the frames back can prove.
7127 let moved: Vec<Picture> = (0..4)
7128 .map(|f| {
7129 let base = screen_card(width, height);
7130 let mut out = Picture::grey(width, height);
7131 for y in 0..height {
7132 for x in 0..width {
7133 let sx = (x + f * 7) % width;
7134 out.y[y * width + x] = base.y[y * width + sx];
7135 }
7136 }
7137 for y in 0..height / 2 {
7138 for x in 0..width / 2 {
7139 let sx = (x + f * 3) % (width / 2);
7140 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
7141 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
7142 }
7143 }
7144 out
7145 })
7146 .collect();
7147 let _ = crate::tile::take_palette_hits();
7148 let _ = crate::tile::take_palette_uv_hits();
7149 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
7150 let gop_hits = crate::tile::take_palette_hits();
7151 let gop_uv_hits = crate::tile::take_palette_uv_hits();
7152 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
7153 eprintln!(
7154 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
7155 {} chroma palette blocks",
7156 inter_screen, gop_hits[0], gop_uv_hits[0]
7157 );
7158 assert!(
7159 gop_uv_hits[0] > 0,
7160 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
7161 );
7162 assert!(
7163 inter_screen > 0,
7164 "no inter frame set allow_screen_content_tools"
7165 );
7166 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
7167 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
7168 assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
7169 }
7170 if have_ffmpeg() {
7171 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
7172 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
7173 assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
7174 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
7175 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
7176 }
7177 }
7178
7179 // The other half of the keep rule: film-shaped content leaves the
7180 // detector (and so the whole sequence header) alone.
7181 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
7182 assert!(!film.screen, "the detector fired on the film-shaped test card");
7183 }
7184
7185 /// The minimal repro that isolated the inter-residual desync: a key frame
7186 /// followed by one inter frame whose single superblock carries one
7187 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
7188 /// coefficient, its three sibling blocks all `skip: true`. Before the
7189 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
7190 /// found when processing input") even though every symbol either block
7191 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
7192 /// same coefficient syntax decodes clean on every intra key-frame gate).
7193 #[test]
7194 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
7195 let fctx = &crate::decode::FrameCtx::new();
7196 if !have_ffmpeg() {
7197 eprintln!(
7198 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
7199 );
7200 return;
7201 }
7202 let (width, height) = (64usize, 64usize);
7203 let picture = Picture::grey(width, height);
7204 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7205
7206 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
7207 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
7208
7209 let residual_block = BlockCoeffs {
7210 luma: vec![Coeff {
7211 row: 0,
7212 col: 0,
7213 level: 4,
7214 }],
7215 u: Vec::new(),
7216 v: Vec::new(),
7217 mode: 0,
7218 uv_mode: 0,
7219 skip: false,
7220 eight: None,
7221 palette: None,
7222 palette_uv: None,
7223 tx_depth: 0,
7224 inter: Some(InterInfo {
7225 ref1: None,
7226 mv1: (0, 0),
7227 ref_frame: crate::mvstack::LAST_FRAME,
7228 mode: InterMode::NearestMv,
7229 mv: (0, 0),
7230 ref_mv_idx: 0,
7231 }),
7232 };
7233 let skipped_block = BlockCoeffs {
7234 skip: true,
7235 inter: Some(InterInfo {
7236 ref1: None,
7237 mv1: (0, 0),
7238 ref_frame: crate::mvstack::LAST_FRAME,
7239 mode: InterMode::NearestMv,
7240 mv: (0, 0),
7241 ref_mv_idx: 0,
7242 }),
7243 ..BlockCoeffs::default()
7244 };
7245 let blocks = vec![
7246 Quadrant::Whole(residual_block),
7247 Quadrant::Whole(skipped_block.clone()),
7248 Quadrant::Whole(skipped_block.clone()),
7249 Quadrant::Whole(skipped_block),
7250 ];
7251 let tile =
7252 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
7253 .unwrap();
7254
7255 // `key.stream` is already a temporal delimiter, the sequence header
7256 // and the key frame's own OBU (`encode_key_frame` built it from the
7257 // same `key_frame_headers(width, height, 100)` this test calls), so
7258 // the inter frame's OBU is appended straight onto it rather than
7259 // re-deriving the key frame's tile bytes.
7260 let mut stream = key.stream.clone();
7261 stream.extend_from_slice(&temporal_delimiter());
7262 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
7263
7264 ffmpeg_decode_sequence(&stream, width, height, 2);
7265 }
7266
7267 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
7268 /// frame size an AV1 decoder allocates, not necessarily the render size
7269 /// (see [`a_frame_round_trips_at_its_own_size`]).
7270 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
7271 // Distinct per call, not per process: the test binary runs callers on
7272 // parallel threads, and a shared name lets one test's cleanup delete
7273 // the stream another test's ffprobe is still reading.
7274 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
7275 let path = std::env::temp_dir().join(format!(
7276 "ec-av1-probe-{}-{}.obu",
7277 std::process::id(),
7278 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7279 ));
7280 let _ = std::fs::remove_file(&path);
7281 std::fs::write(&path, stream).expect("writing the probe stream");
7282 let out = Command::new("ffprobe")
7283 .args([
7284 "-v",
7285 "error",
7286 "-f",
7287 "obu",
7288 "-select_streams",
7289 "v:0",
7290 "-show_entries",
7291 "stream=width,height",
7292 "-of",
7293 "csv=p=0",
7294 ])
7295 .arg(&path)
7296 .output()
7297 .expect("ffprobe failed to run");
7298 let _ = std::fs::remove_file(&path);
7299 assert!(
7300 out.status.success(),
7301 "ffprobe refused the stream: {}",
7302 String::from_utf8_lossy(&out.stderr)
7303 );
7304 let text = String::from_utf8_lossy(&out.stdout);
7305 let mut fields = text.trim().split(',');
7306 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
7307 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
7308 (width, height)
7309 }
7310
7311 /// A key frame at an arbitrary even size round-trips through ffmpeg over
7312 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
7313 /// picture's own size, and what ffmpeg decodes over that same top-left
7314 /// region equals it sample for sample.
7315 ///
7316 /// This does not check that `ffprobe` reports the picture's own size,
7317 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
7318 /// (block-padded) frame size, the same one libaom itself would code for
7319 /// a non-block-aligned picture. `render_width`/`render_height` (which
7320 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
7321 /// decoder is required to crop pixels by, and ffmpeg's does not --
7322 /// checked empirically against ffprobe here and against a real libaom
7323 /// encode separately. So the coded size, not the render size, is what
7324 /// `ffprobe` is asserted to report below.
7325 #[test]
7326 fn a_frame_round_trips_at_its_own_size() {
7327 let fctx = &crate::decode::FrameCtx::new();
7328 if !have_ffmpeg() {
7329 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
7330 return;
7331 }
7332 // 854x480 is covered separately by
7333 // `an_854x480_picture_round_trips_through_its_padding`, which its own
7334 // doc comment explains was worth keeping as its own test.
7335 for &(width, height) in &[
7336 (1920usize, 1080usize),
7337 (640, 352),
7338 (1280, 720),
7339 (64, 56),
7340 (854, 480),
7341 (216, 96),
7342 (192, 120),
7343 ] {
7344 let picture = test_card(width, height);
7345 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7346 assert_eq!(
7347 (encoded.reconstruction.width, encoded.reconstruction.height),
7348 (width, height),
7349 "{width}x{height}: reconstruction is cropped to the picture's own size"
7350 );
7351 assert_eq!(
7352 ffprobe_size(&encoded.stream),
7353 (width as u32, height as u32),
7354 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
7355 );
7356 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7357 assert_eq!(
7358 decoded.y, encoded.reconstruction.y,
7359 "{width}x{height}: luma"
7360 );
7361 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
7362 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
7363 }
7364 }
7365
7366 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
7367 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
7368 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
7369 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
7370 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
7371 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
7372 /// col`) -- different bits of an 8-byte table, one true, one false. The
7373 /// stride libaom indexes by is fixed at its compile-time maximum
7374 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
7375 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
7376 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
7377 /// row/col position within the (correctly 64-relative) superblock stayed
7378 /// right, only the table's own row stride was wrong. Fixed in
7379 /// `Reach::table_stride`; not an arithmetic-coder desync (an
7380 /// EC_RNG-per-symbol trace against the same debug decoder found the
7381 /// bitstream byte-for-byte identical to libaom's across all 51188
7382 /// symbols of this frame before this bug was found).
7383 ///
7384 /// Since the frame header started writing the true (unpadded) display
7385 /// size into `frame_width`/`frame_height` rather than the padded coded
7386 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
7387 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
7388 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
7389 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
7390 /// the header's own size before output).
7391 #[test]
7392 fn an_854x480_picture_round_trips_through_its_padding() {
7393 let fctx = &crate::decode::FrameCtx::new();
7394 if !have_ffmpeg() {
7395 return;
7396 }
7397 let (width, height) = (854usize, 480usize);
7398 let picture = test_card(width, height);
7399 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7400 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7401 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
7402 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
7403 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
7404 }
7405
7406 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
7407 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
7408 /// superblock, both partition tables:
7409 ///
7410 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
7411 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
7412 /// wiring the TU sites onto it changes no existing stream;
7413 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
7414 /// NULL in libaom because that lookup never happens, and reading a
7415 /// 4x4 row out of the three-row vert tables is what crashed a real
7416 /// `--enable-tx-size-search=1` stream (r2);
7417 /// 3. and it must be the BLOCK's vert answer where the two tables
7418 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
7419 /// row 1, column 0 reads its above-right samples from the 8x8 to its
7420 /// upper right, which a vertical AB partition codes AFTER it
7421 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
7422 #[test]
7423 fn of_tu_follows_the_block_row_including_under_vert_ab() {
7424 let fctx = &crate::decode::FrameCtx::new();
7425 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
7426 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
7427 // above-right answer is the BLOCK's, which is the whole reason a unit
7428 // asks the block instead of looking itself up (the
7429 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
7430 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
7431 assert_eq!(
7432 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
7433 plain.above_right,
7434 "ordinary table: the top-right TX4 unit takes the block's row"
7435 );
7436 let guard = Reach::vert_ab_partition();
7437 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
7438 assert_eq!(
7439 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
7440 vert.above_right,
7441 "vert AB: the unit follows the vert row the block just picked"
7442 );
7443 assert_ne!(
7444 plain.above_right, vert.above_right,
7445 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
7446 );
7447 drop(guard);
7448 }
7449
7450 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
7451 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
7452 /// reconintra.c`), for every 16x16 and 32x32 block position across three
7453 /// superblocks square -- interior and every superblock edge (top row,
7454 /// left column, right column, bottom row) both sizes reach. Written to
7455 /// catch the class the `table_stride` bug was: an index stride silently
7456 /// wrong for one block size while looking plausible for the other.
7457 #[test]
7458 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
7459 let fctx = &crate::decode::FrameCtx::new();
7460 // Transcribed from has_top_right/has_bottom_left's row_off==0,
7461 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
7462 // 128px reference grid) pinned as libaom pins it, independent of the
7463 // 64px superblock this crate actually codes.
7464 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
7465 if y == 0 || x + side >= width {
7466 return false;
7467 }
7468 let (row, col, per_side) = (
7469 (y % SUPERBLOCK) / side,
7470 (x % SUPERBLOCK) / side,
7471 SUPERBLOCK / side,
7472 );
7473 if row == 0 {
7474 return true;
7475 }
7476 if col + 1 == per_side {
7477 return false;
7478 }
7479 let stride = 128 / side;
7480 let index = row * stride + col;
7481 let table = if side == BLOCK {
7482 [95u8, 87].to_vec()
7483 } else {
7484 vec![255, 85, 119, 85, 127, 85, 119, 85]
7485 };
7486 (table[index / 8] >> (index % 8)) & 1 != 0
7487 }
7488
7489 fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool {
7490 if x == 0 || y + side >= height {
7491 return false;
7492 }
7493 let (row, col, per_side) = (
7494 (y % SUPERBLOCK) / side,
7495 (x % SUPERBLOCK) / side,
7496 SUPERBLOCK / side,
7497 );
7498 if col == 0 {
7499 return row * side + side < SUPERBLOCK;
7500 }
7501 if row + 1 == per_side {
7502 return false;
7503 }
7504 let stride = 128 / side;
7505 let index = row * stride + col;
7506 let table = if side == BLOCK {
7507 [4u8, 4].to_vec()
7508 } else {
7509 vec![84, 16, 84, 0, 84, 16, 84, 0]
7510 };
7511 (table[index / 8] >> (index % 8)) & 1 != 0
7512 }
7513
7514 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
7515 for side in [16usize, BLOCK] {
7516 for y in (0..height).step_by(side) {
7517 for x in (0..width).step_by(side) {
7518 let reach = Reach::of(side, x, y, width, height, fctx);
7519 assert_eq!(
7520 reach.above_right,
7521 libaom_top_right(side, x, y, width, height),
7522 "side={side} x={x} y={y}: above_right"
7523 );
7524 assert_eq!(
7525 reach.below_left,
7526 libaom_bottom_left(side, x, y, height, fctx),
7527 "side={side} x={x} y={y}: below_left"
7528 );
7529 }
7530 }
7531 }
7532 }
7533
7534 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
7535 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
7536 /// column inside the superblock) may read the below-left samples the
7537 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
7538 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
7539 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
7540 /// stream that partitions that small first hits the still-refused
7541 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
7542 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
7543 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
7544 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
7545 /// pixels -- lane-palette2 r12: the square multi-TU path used the
7546 /// standalone-block tables instead of this rule and granted a 16x16
7547 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
7548 #[test]
7549 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
7550 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
7551 // *_count_unit = tx size / 4.
7552 fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
7553 let (plane_bw_unit, count) = (bw / 4, tx / 4);
7554 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
7555 let _ = bh;
7556 if row_off_u > 0 {
7557 col_off_u + count < plane_bw_unit
7558 } else if col_off_u + count < plane_bw_unit {
7559 true
7560 } else {
7561 blk
7562 }
7563 }
7564 fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
7565 let (plane_bh_unit, count) = (bh / 4, tx / 4);
7566 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
7567 let _ = bw;
7568 if col_off_u > 0 {
7569 false
7570 } else if row_off_u + count < plane_bh_unit {
7571 true
7572 } else {
7573 blk
7574 }
7575 }
7576 for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
7577 for &tx in &[4usize, 8, 16, 32] {
7578 if tx > bw.min(bh) {
7579 continue;
7580 }
7581 for row_off in (0..bh).step_by(tx) {
7582 for col_off in (0..bw).step_by(tx) {
7583 for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] {
7584 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
7585 assert_eq!(
7586 got.above_right,
7587 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
7588 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
7589 );
7590 assert_eq!(
7591 got.below_left,
7592 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
7593 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
7594 );
7595 }
7596 }
7597 }
7598 }
7599 }
7600 }
7601
7602 #[test]
7603 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
7604 let fctx = &crate::decode::FrameCtx::new();
7605 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
7606 // Interior superblock, so neither the frame edge nor the col == 0 /
7607 // last-row early returns answer instead of the table.
7608 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
7609 let mut flipped = 0;
7610 for row in 0..8 {
7611 for col in 1..8 {
7612 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
7613 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
7614 let vert = {
7615 let _guard = Reach::vert_ab_partition();
7616 Reach::of(8, x, y, width, height, fctx).below_left
7617 };
7618 // The TR square of a VERT_A/_B sits at an even row, odd
7619 // column; every other slot must be untouched by the guard.
7620 if row % 2 == 0 && col % 2 == 1 {
7621 assert!(!raster, "raster below_left at row={row} col={col}");
7622 assert!(vert, "vert below_left at row={row} col={col}");
7623 flipped += 1;
7624 } else {
7625 assert_eq!(raster, vert, "guard moved row={row} col={col}");
7626 }
7627 }
7628 }
7629 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
7630 // The guard is scoped: it must not leak past its own block.
7631 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
7632 }
7633
7634 /// An odd width or height is refused by name, not by however the padder
7635 /// or the block coder would happen to fail on it.
7636 #[test]
7637 fn odd_dimensions_are_refused() {
7638 let fctx = &crate::decode::FrameCtx::new();
7639 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
7640 let picture = Picture::grey(width, height);
7641 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
7642 .expect_err(&format!("{width}x{height} is odd and must be refused"));
7643 assert!(
7644 err.to_string().contains("even"),
7645 "{width}x{height}: error was {err}"
7646 );
7647 }
7648 }
7649
7650 /// A sequence at a size that is not a multiple of the block grid decodes
7651 /// to the right frame count and the right size for every frame,
7652 /// including the inter frames whose reference is the previous frame's
7653 /// own (padded) reconstruction.
7654 #[test]
7655 fn sequence_round_trips_at_a_non_multiple_size() {
7656 let fctx = &crate::decode::FrameCtx::new();
7657 if !have_ffmpeg() {
7658 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
7659 return;
7660 }
7661 let (width, height) = (160usize, 96usize);
7662 let pictures: Vec<Picture> = (0..3)
7663 .map(|i| panned_test_card(width, height, i * 3))
7664 .collect();
7665 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
7666 assert_eq!(encoded.frames.len(), 3);
7667 for (i, frame) in encoded.frames.iter().enumerate() {
7668 assert_eq!(
7669 (frame.reconstruction.width, frame.reconstruction.height),
7670 (width, height),
7671 "frame {i}: reconstruction size"
7672 );
7673 }
7674 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
7675 // true (display) size a sequence's frames share, not the padded one.
7676 assert_eq!(
7677 ffprobe_size(&encoded.stream),
7678 (width as u32, height as u32),
7679 "sequence: ffprobe reports the true (display) size"
7680 );
7681 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
7682 assert_eq!(decoded.len(), 3, "decoded frame count");
7683 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
7684 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
7685 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
7686 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
7687 }
7688 }
7689
7690 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
7691 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
7692 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
7693 /// `pos + side_mi / 2 < bound` boundary), which is the case
7694 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
7695 /// refusing. A key frame alone already covered this size; this proves the
7696 /// inter tile writer's parity with it across a real multi-frame export.
7697 #[test]
7698 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
7699 let fctx = &crate::decode::FrameCtx::new();
7700 if !have_ffmpeg() {
7701 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
7702 return;
7703 }
7704 let (width, height) = (1280usize, 720usize);
7705 let pictures: Vec<Picture> = (0..3)
7706 .map(|i| panned_test_card(width, height, i * 3))
7707 .collect();
7708 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
7709 assert_eq!(encoded.frames.len(), 3);
7710 for (i, frame) in encoded.frames.iter().enumerate() {
7711 assert_eq!(
7712 (frame.reconstruction.width, frame.reconstruction.height),
7713 (width, height),
7714 "frame {i}: reconstruction size"
7715 );
7716 }
7717 assert_eq!(
7718 ffprobe_size(&encoded.stream),
7719 (width as u32, height as u32),
7720 "ffprobe reports the true (display) 1280x720 size"
7721 );
7722 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
7723 assert_eq!(decoded.len(), 3, "decoded frame count");
7724 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
7725 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
7726 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
7727 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
7728 }
7729 }
7730
7731 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
7732 /// leaf's own half (`has_half` at the SUB level) itself straddles the
7733 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
7734 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
7735 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
7736 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
7737 /// straddling-16x16 branch), so an inter frame no longer refuses this
7738 /// size either. This only proves the encoder does not error out -- see
7739 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
7740 /// decoder-clean proof (a 3-frame sequence, so the inter path is
7741 /// actually exercised).
7742 #[test]
7743 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
7744 let fctx = &crate::decode::FrameCtx::new();
7745 let (width, height) = (640usize, 360usize);
7746 let picture = Picture::grey(width, height);
7747 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
7748
7749 // `encode_sequence`'s second frame is the inter path: same size, now
7750 // wired the same way.
7751 let pictures = vec![picture.clone(), picture];
7752 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
7753 .expect("inter frame now codes the mod-32==8 straddle too");
7754 }
7755
7756 /// The r15 fix at production size: three 640x360 key frames (inter is
7757 /// still refused at this size, per the test above, so this stands in for
7758 /// the charter's "3-frame sequence" using three independent key frames of
7759 /// shifted content), each proven decoder-clean through ffmpeg rather than
7760 /// only encoder-clean.
7761 #[test]
7762 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
7763 let fctx = &crate::decode::FrameCtx::new();
7764 if !have_ffmpeg() {
7765 eprintln!(
7766 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
7767 no ffmpeg"
7768 );
7769 return;
7770 }
7771 let (width, height) = (640usize, 360usize);
7772 for shift in [0i64, 7, 19] {
7773 let picture = panned_test_card(width, height, shift);
7774 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7775 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7776 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
7777 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
7778 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
7779 }
7780 }
7781
7782 /// The 640x360 straddle class, but through the inter path an actual
7783 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
7784 /// proves the leaf-8 inter stream this round wires up is not just
7785 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
7786 #[test]
7787 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
7788 let fctx = &crate::decode::FrameCtx::new();
7789 if !have_ffmpeg() {
7790 eprintln!(
7791 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
7792 );
7793 return;
7794 }
7795 let (width, height) = (640usize, 360usize);
7796 let pictures: Vec<Picture> = (0..4)
7797 .map(|i| panned_test_card(width, height, i * 3))
7798 .collect();
7799 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
7800 assert_eq!(encoded.frames.len(), 4);
7801 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
7802 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
7803 }
7804 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
7805 assert_eq!(decoded.len(), 4, "decoded frame count");
7806 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
7807 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
7808 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
7809 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
7810 }
7811 }
7812
7813 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
7814 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
7815 let out = Command::new("ffmpeg")
7816 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
7817 .args(["-vf", &format!("scale={width}:{height}")])
7818 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
7819 .output()
7820 .expect("ffmpeg failed to run");
7821 assert!(
7822 out.status.success(),
7823 "ffmpeg: {}",
7824 String::from_utf8_lossy(&out.stderr)
7825 );
7826 let (luma, chroma) = (width * height, width * height / 4);
7827 assert_eq!(
7828 out.stdout.len(),
7829 luma + 2 * chroma,
7830 "expected one 4:2:0 frame"
7831 );
7832 Picture {
7833 width,
7834 height,
7835 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
7836 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
7837 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
7838 }
7839 }
7840
7841 /// Prints what the mode search saves over DC prediction alone, for the
7842 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
7843 /// weight the search puts on rate can be swept.
7844 #[test]
7845 #[ignore = "a sweep, not a gate"]
7846 fn probe_lambda() {
7847 let fctx = &crate::decode::FrameCtx::new();
7848 let mut pictures = vec![
7849 ("test card".to_string(), test_card(160, 96)),
7850 ("stripes".to_string(), stripes(160, 96, true)),
7851 ];
7852 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
7853 for entry in clips.split(':').filter(|e| !e.is_empty()) {
7854 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
7855 let name = path.rsplit('/').next().unwrap_or(path).to_string();
7856 pictures.push((name, clip_frame(path, skip, 640, 352)));
7857 }
7858 }
7859 for (name, picture) in pictures {
7860 let dc = ladder(&picture, &[DC_PRED], fctx);
7861 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
7862 println!(
7863 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
7864 bd_rate(&dc, &searched) * 100.0,
7865 10f64.powf(searched[1].1),
7866 searched[1].0,
7867 10f64.powf(dc[1].1),
7868 dc[1].0,
7869 );
7870 }
7871 }
7872
7873 /// Prints the whole mode-search ladder, so two builds of the search can be
7874 /// compared against each other rather than each against its own baseline.
7875 #[test]
7876 #[ignore = "a sweep, not a gate"]
7877 fn probe_ladder() {
7878 let fctx = &crate::decode::FrameCtx::new();
7879 for (name, picture) in sweep_pictures() {
7880 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
7881 let points = all
7882 .iter()
7883 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
7884 .collect::<Vec<_>>()
7885 .join(" ");
7886 println!("ladder {name}: {points}");
7887 }
7888 }
7889
7890 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
7891 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
7892 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
7893 #[test]
7894 #[ignore = "a sweep, not a gate"]
7895 fn probe_split() {
7896 let fctx = &crate::decode::FrameCtx::new();
7897 for (name, picture) in sweep_pictures() {
7898 let ladder = |split: bool| {
7899 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
7900 .iter()
7901 .map(|&q| {
7902 let encoded = encode_key_frame_inner(
7903 &picture,
7904 q,
7905 0.5,
7906 &KEY_FRAME_MODES,
7907 split,
7908 (picture.width, picture.height),
7909 unspecified_color_config(), fctx,
7910 )
7911 .unwrap();
7912 (
7913 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
7914 (encoded.stream.len() as f64).log10(),
7915 )
7916 })
7917 .collect();
7918 points.sort_by(|a, b| a.0.total_cmp(&b.0));
7919 points
7920 };
7921 let (whole, split) = (ladder(false), ladder(true));
7922 let blocks = encode_key_frame_inner(
7923 &picture,
7924 90,
7925 0.5,
7926 &KEY_FRAME_MODES,
7927 true,
7928 (picture.width, picture.height),
7929 unspecified_color_config(), fctx,
7930 )
7931 .unwrap()
7932 .modes
7933 .len();
7934 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
7935 println!(
7936 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
7937 bd_rate(&whole, &split) * 100.0
7938 );
7939 }
7940 }
7941
7942 /// A striped picture, running one way or the other. The stripes are what
7943 /// separates a vertical predictor from a horizontal one: a mode search
7944 /// reading a transposed edge would pick the wrong one of the pair, which no
7945 /// symmetric picture would show.
7946 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
7947 let mut picture = Picture::grey(width, height);
7948 for y in 0..height {
7949 for x in 0..width {
7950 let along = if vertical { x } else { y };
7951 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
7952 }
7953 }
7954 picture
7955 }
7956
7957 /// Where two planes first disagree, and by how much: a mismatch reported as
7958 /// a position says which block and which sample of it went wrong, which a
7959 /// pair of thousand-sample arrays does not.
7960 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
7961 let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
7962 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
7963 Some(format!(
7964 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
7965 i % width,
7966 i / width,
7967 ours[i],
7968 theirs[i]
7969 ))
7970 }
7971
7972 /// Every mode the encoder offers has to predict what the decoder predicts,
7973 /// not just the ones a particular picture happens to choose: each is forced
7974 /// over a whole picture and the reconstruction gated against ffmpeg.
7975 #[test]
7976 fn every_mode_decodes_to_what_the_encoder_predicted() {
7977 let fctx = &crate::decode::FrameCtx::new();
7978 if !have_ffmpeg() {
7979 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
7980 return;
7981 }
7982 // 128 wide is a whole number of superblocks and 160 is not: the last
7983 // superblock of a 160-wide row is half a one, whose blocks have no
7984 // above-right samples inside the frame at all.
7985 for (width, height) in [(128, 96), (160, 96)] {
7986 let picture = test_card(width, height);
7987 for mode in KEY_FRAME_MODES {
7988 let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap();
7989 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7990 for (plane, ours, theirs, stride) in [
7991 ("luma", &encoded.reconstruction.y, &decoded.y, width),
7992 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
7993 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
7994 ] {
7995 assert!(
7996 first_difference(ours, theirs, stride).is_none(),
7997 "{width}x{height} mode {mode}, {plane}: {}",
7998 first_difference(ours, theirs, stride).unwrap()
7999 );
8000 }
8001 assert!(
8002 encoded.modes.iter().all(|&m| m == mode),
8003 "mode {mode}: the encoder coded something else"
8004 );
8005 }
8006 }
8007 }
8008
8009 /// The search has to follow the picture: vertical stripes are cheapest
8010 /// predicted from the row above, horizontal ones from the column to the
8011 /// left. Reading the edges the other way round would swap the two answers
8012 /// while leaving every fidelity gate intact.
8013 #[test]
8014 fn the_search_picks_the_direction_the_picture_runs() {
8015 let fctx = &crate::decode::FrameCtx::new();
8016 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
8017 let picture = stripes(128, 96, vertical);
8018 // Only the pair, because on stripes a third mode predicts exactly
8019 // what the right one of the pair does -- PAETH reads the corner and
8020 // the left column, which a striped picture makes equal -- and the
8021 // tie then goes to whichever is cheaper to name, which is not what
8022 // this gate is about.
8023 let encoded =
8024 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
8025 // The first block of the picture has neither neighbour, so it
8026 // cannot tell the modes apart; every other one can.
8027 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
8028 assert!(
8029 picked * 2 > encoded.modes.len() - 1,
8030 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
8031 encoded.modes.len() - 1,
8032 encoded.modes
8033 );
8034 }
8035 }
8036
8037 /// What the search is for: the same picture, at the same quantizer, coded
8038 /// smaller and more faithfully than DC alone can manage.
8039 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
8040 /// between the two rate-distortion curves in log-rate against PSNR, as a
8041 /// fraction of the reference's rate. Negative means the second curve costs
8042 /// less for the same picture.
8043 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
8044 let low = reference[0].0.max(other[0].0);
8045 let high = reference[reference.len() - 1]
8046 .0
8047 .min(other[other.len() - 1].0);
8048 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
8049 // the non-directional one on the synthetic diagonals -- every point
8050 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
8051 // to integrate over any more. A curve that dominates that way has
8052 // saved everything the measure can express (the
8053 // `instrument-at-bound` class: the answer is at the instrument's own
8054 // edge, not undefined), so name it rather than panicking; anything
8055 // less clean than strict dominance still is.
8056 if high <= low {
8057 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
8058 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
8059 let dominates = other[0].0 > reference[reference.len() - 1].0
8060 && other_hi_rate <= ref_lo_rate;
8061 assert!(
8062 dominates,
8063 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
8064 );
8065 return -1.0;
8066 }
8067 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
8068 let i = curve
8069 .windows(2)
8070 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
8071 .unwrap_or(0);
8072 let (x0, y0) = curve[i];
8073 let (x1, y1) = curve[i + 1];
8074 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
8075 };
8076 let steps = 64;
8077 let mut area = 0.0;
8078 for step in 0..steps {
8079 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
8080 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
8081 }
8082 10f64.powf(area / f64::from(steps)) - 1.0
8083 }
8084
8085 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
8086 /// fidelity.
8087 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
8088 // A mode ablation measures the MODE search: the palette would code
8089 // these synthetic two-colour pictures losslessly under every arm and
8090 // leave nothing to compare (see [`force_screen`]).
8091 force_screen(Some(false));
8092 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
8093 .iter()
8094 .map(|&q| {
8095 let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
8096 (
8097 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
8098 (encoded.stream.len() as f64).log10(),
8099 )
8100 })
8101 .collect();
8102 points.sort_by(|a, b| a.0.total_cmp(&b.0));
8103 points
8104 }
8105
8106 /// What the search is for: the same pictures cost less to code at the same
8107 /// fidelity than DC prediction alone can manage. A picture that runs one
8108 /// way saves far more than a busy one, which is the shape a working
8109 /// directional pair has.
8110 #[test]
8111 fn the_search_beats_dc_alone() {
8112 let fctx = &crate::decode::FrameCtx::new();
8113 for (name, picture, want) in [
8114 ("test card", test_card(160, 96), -0.05),
8115 ("stripes", stripes(160, 96, true), -0.40),
8116 ] {
8117 let saved = bd_rate(
8118 &ladder(&picture, &[DC_PRED], fctx),
8119 &ladder(&picture, &NON_DIRECTIONAL, fctx),
8120 );
8121 assert!(
8122 saved < want,
8123 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
8124 saved * 100.0,
8125 -want * 100.0
8126 );
8127 }
8128 }
8129
8130 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
8131 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
8132 fn sweep_pictures() -> Vec<(String, Picture)> {
8133 let mut pictures = vec![
8134 ("test card".to_string(), test_card(160, 96)),
8135 ("stripes".to_string(), stripes(160, 96, true)),
8136 ("diagonal".to_string(), diagonal(160, 96, true)),
8137 ];
8138 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
8139 for entry in clips.split(':').filter(|e| !e.is_empty()) {
8140 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
8141 let name = path.rsplit('/').next().unwrap_or(path).to_string();
8142 pictures.push((name, clip_frame(path, skip, 640, 352)));
8143 }
8144 }
8145 pictures
8146 }
8147
8148 /// What the six directional modes are worth, per picture, at whatever
8149 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
8150 /// no further, and how often the search picks one.
8151 #[test]
8152 #[ignore = "a sweep, not a gate"]
8153 fn probe_directional() {
8154 let fctx = &crate::decode::FrameCtx::new();
8155 for (name, picture) in sweep_pictures() {
8156 let dc = ladder(&picture, &[DC_PRED], fctx);
8157 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
8158 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
8159 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
8160 let directional = encoded
8161 .modes
8162 .iter()
8163 .filter(|&&m| (3..=8).contains(&m))
8164 .count();
8165 // A picture whose ladders sit at different fidelities altogether
8166 // has no BD-rate to report -- see the flat-sample-window class.
8167 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
8168 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
8169 };
8170 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
8171 if overlap(a, b) {
8172 format!("{:+.2}%", bd_rate(a, b) * 100.0)
8173 } else {
8174 "no overlap".to_string()
8175 }
8176 };
8177 println!(
8178 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
8179 against(&flat, &all),
8180 against(&dc, &all),
8181 encoded.modes.len(),
8182 );
8183 }
8184 }
8185
8186 /// A picture whose stripes run along a diagonal, one way or the other.
8187 /// This is to the directional modes what [`stripes`] is to the vertical and
8188 /// horizontal pair: a predictor that walked the edge in the wrong direction
8189 /// would answer the two pictures the same way round.
8190 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
8191 let mut picture = Picture::grey(width, height);
8192 for y in 0..height {
8193 for x in 0..width {
8194 let along = if down_right { x + height - y } else { x + y };
8195 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
8196 }
8197 }
8198 picture
8199 }
8200
8201 /// The mode picked by the most blocks of a picture, ignoring the first
8202 /// block, which has no neighbours to tell the modes apart with.
8203 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
8204 // A mode ablation measures the MODE search: the palette would code
8205 // these synthetic two-colour pictures losslessly under every arm and
8206 // leave nothing to compare (see [`force_screen`]).
8207 force_screen(Some(false));
8208 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
8209 let blocks = &encoded.modes[1..];
8210 let mut counts = [0usize; 13];
8211 for &mode in blocks {
8212 counts[usize::from(mode)] += 1;
8213 }
8214 let (mode, count) = counts
8215 .iter()
8216 .enumerate()
8217 .max_by_key(|&(_, count)| *count)
8218 .expect("thirteen modes");
8219 (mode as u8, *count, blocks.len())
8220 }
8221
8222 /// The search has to follow a diagonal the way it runs: stripes down and to
8223 /// the right are cheapest predicted at 135 degrees, stripes down and to the
8224 /// left at 45. A walk that stepped the wrong way along the edge, or read
8225 /// the above row where it should read the left column, would swap these.
8226 #[test]
8227 fn the_search_picks_the_diagonal_the_picture_runs() {
8228 let fctx = &crate::decode::FrameCtx::new();
8229 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
8230 let picture = diagonal(160, 96, down_right);
8231 let (mode, count, blocks) = favourite_mode(&picture, fctx);
8232 assert_eq!(
8233 mode, want,
8234 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
8235 );
8236 }
8237 }
8238
8239 /// What the directional modes are for: a picture that runs along a diagonal
8240 /// costs far less to code with them than the seven that read only their own
8241 /// edges can manage, and a picture that runs no particular way costs no
8242 /// more. The second half is the one that bites: a mode set the search
8243 /// cannot price is a mode set that loses rate on content that does not want
8244 /// it, which is what costing the mode symbol is for.
8245 #[test]
8246 fn the_diagonals_beat_the_modes_that_read_no_further() {
8247 let fctx = &crate::decode::FrameCtx::new();
8248 for (name, picture, want) in [
8249 ("down-right", diagonal(160, 96, true), -0.20),
8250 ("down-left", diagonal(160, 96, false), -0.20),
8251 ("test card", test_card(160, 96), 0.01),
8252 ] {
8253 let saved = bd_rate(
8254 &ladder(&picture, &NON_DIRECTIONAL, fctx),
8255 &ladder(&picture, &KEY_FRAME_MODES, fctx),
8256 );
8257 assert!(
8258 saved < want,
8259 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
8260 saved * 100.0,
8261 -want * 100.0
8262 );
8263 }
8264 }
8265
8266 /// A mode the encoder cannot predict must be refused rather than coded as
8267 /// something else, and a search with nothing to choose from likewise.
8268 #[test]
8269 fn a_mode_the_encoder_cannot_predict_is_refused() {
8270 let fctx = &crate::decode::FrameCtx::new();
8271 let picture = test_card(64, 64);
8272 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
8273 .unwrap_err()
8274 .to_string();
8275 assert!(
8276 message.contains("intra mode 13"),
8277 "the refusal must name the mode, got {message}"
8278 );
8279 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
8280 }
8281
8282 /// The picture that comes back is the picture that went in, to within the
8283 /// quantizer. A prediction that read the wrong neighbours, or a block
8284 /// written into the wrong place, would still decode to what the encoder
8285 /// reconstructed — it is this gate that says the reconstruction is of the
8286 /// right picture.
8287 #[test]
8288 fn the_encoded_picture_is_the_one_that_went_in() {
8289 let fctx = &crate::decode::FrameCtx::new();
8290 let picture = test_card(160, 96);
8291 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8292 let luma = psnr(&encoded.reconstruction.y, &picture.y);
8293 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
8294 for (plane, (got, want)) in [
8295 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
8296 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
8297 ]
8298 .iter()
8299 .enumerate()
8300 {
8301 let chroma = psnr(got, want);
8302 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
8303 }
8304 }
8305
8306 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
8307 /// does the opposite. Both are monotone, which is what a rate-distortion
8308 /// loop above this will assume.
8309 #[test]
8310 fn fidelity_and_rate_move_with_the_quantizer() {
8311 let fctx = &crate::decode::FrameCtx::new();
8312 let picture = test_card(128, 128);
8313 let mut previous: Option<(usize, f64)> = None;
8314 for &q in &[70u8, 90, 110] {
8315 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
8316 let quality = psnr(&encoded.reconstruction.y, &picture.y);
8317 if let Some((bytes, better)) = previous {
8318 assert!(
8319 encoded.stream.len() < bytes,
8320 "q {q}: {} bytes",
8321 encoded.stream.len()
8322 );
8323 assert!(quality < better, "q {q}: PSNR {quality}");
8324 }
8325 previous = Some((encoded.stream.len(), quality));
8326 }
8327
8328 let mut previous = None;
8329 for &deadzone in &[0.5f64, 0.3, 0.15] {
8330 let encoded = encode_key_frame_with_ctx(&picture, 100, deadzone, fctx).unwrap();
8331 let quality = psnr(&encoded.reconstruction.y, &picture.y);
8332 if let Some((bytes, better)) = previous {
8333 assert!(
8334 encoded.stream.len() < bytes,
8335 "deadzone {deadzone}: {} bytes",
8336 encoded.stream.len()
8337 );
8338 assert!(quality < better, "deadzone {deadzone}: PSNR {quality}");
8339 }
8340 previous = Some((encoded.stream.len(), quality));
8341 }
8342
8343 // Bytes must not jump up across a q-context boundary: a wrong CDF
8344 // table for the far side would show up as a rate discontinuity here,
8345 // even though a coarser quantizer always codes no more than a finer
8346 // one on the same picture.
8347 //
8348 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
8349 // chroma searches its own mode, a coarser quantizer can pick a
8350 // *different* uv_mode on a block whose modes now cost nearly the
8351 // same, and the search prices that symbol against the static default
8352 // CDF while the writer codes it against an adapted one -- 311 -> 319
8353 // bytes at q 120->121 on this picture. The table this gate is really
8354 // watching would move the rate by far more than the mode churn does.
8355 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
8356 // same block can also change transform DEPTH between two neighbouring
8357 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
8358 // symbol is priced off the static CDF row 0 for the same reason the
8359 // uv_mode one is.
8360 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
8361 // path is pricing through the adapting CDF state (what
8362 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
8363 // drift of), after which the exact bound comes back.
8364 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
8365 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
8366 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
8367 assert!(
8368 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
8369 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
8370 );
8371 }
8372 }
8373
8374 /// A flat picture is a flat stream: every block predicts its neighbours'
8375 /// average, which is the picture's own value, and codes nothing.
8376 #[test]
8377 fn a_flat_picture_costs_almost_nothing() {
8378 let fctx = &crate::decode::FrameCtx::new();
8379 let mut picture = Picture::grey(128, 128);
8380 picture.y.fill(97);
8381 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8382 // The first block has no neighbour and predicts 128, so it carries a
8383 // DC; every block after it predicts 97 and carries nothing.
8384 assert!(
8385 encoded.stream.len() < 100,
8386 "{} bytes for a flat picture",
8387 encoded.stream.len()
8388 );
8389 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
8390 assert_eq!(s, 97, "sample {i} of a flat picture");
8391 }
8392 }
8393
8394 /// The sizes the encoder refuses, refused for a reason rather than by
8395 /// panicking somewhere below. Most sizes off the 32x32 block grid encode
8396 /// fine now (see `a_frame_round_trips_at_its_own_size`) -- the true frame
8397 /// edge lands past the halfway point of whichever block it falls in, so
8398 /// `PARTITION_NONE` or a single gathered split flag still says everything
8399 /// the spec needs. lane-av1-rect r7 wires the 8x8-leaf path live, so a
8400 /// 16x16 leaf straddling on exactly one axis (e.g. 40x32, cols mod 32 ==
8401 /// 8) now encodes too (see `a_frame_round_trips_at_its_own_size`'s
8402 /// sibling below). Only a leaf whose true edge cuts *both* axes (e.g.
8403 /// 40x40, both dims mod 32 == 8) needs the rectangular transform neither
8404 /// writer has, so that class is still refused, by name rather than by
8405 /// corrupting the stream.
8406 #[test]
8407 fn a_picture_off_the_block_grid_is_refused() {
8408 let fctx = &crate::decode::FrameCtx::new();
8409 let msg = encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
8410 .expect_err("40x40 straddles both axes of a 16x16 leaf, needs a rectangular transform")
8411 .to_string();
8412 assert!(msg.contains("rectangular"), "refusal: {msg}");
8413
8414 let mut short = Picture::grey(64, 64);
8415 short.u.truncate(10);
8416 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
8417 }
8418
8419 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
8420 /// column half only (`has_half` false on cols, true on rows) -- exactly
8421 /// the single-axis straddle lane-av1-rect r7 wires through
8422 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
8423 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
8424 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
8425 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
8426 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
8427 /// `partition_context_lookup` entry this writer ever produces (no 4x4
8428 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
8429 /// leaf regardless of neighbour state -- our writer already agreed with
8430 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
8431 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
8432 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
8433 /// it does not regress the gate. r11 tell-for-tell traced two further,
8434 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
8435 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
8436 /// leaves, when the second leaf's true above (or left) neighbour is the
8437 /// first leaf itself -- fixed by threading the first leaf's mode into the
8438 /// second leaf's context, mi-precise, like `record_mi` already does for
8439 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
8440 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
8441 /// `reduced_tx_set` is false), but this crate's key frames set
8442 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
8443 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
8444 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
8445 /// symbol bits to desync everything after it. Fixed with a new
8446 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
8447 /// eset/size slot). Both fixes are provably correct against libaom
8448 /// source and each closed part of the gap (leaf0's `eob` went from a
8449 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
8450 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
8451 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
8452 /// (do not reuse r11's committed logs, which predate its own fixes) and
8453 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
8454 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
8455 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
8456 /// every other `write_block` caller at 16x16 and up already passes
8457 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
8458 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
8459 /// different amount of arithmetic range and derailed everything after
8460 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
8461 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
8462 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
8463 /// never updating those coarse arrays itself -- so a *second* straddling
8464 /// 16x16 quadrant stacked above or left of the first (never covered by
8465 /// r11's same-call `prev_leaf` override, which only threads state
8466 /// between the two leaves of one shared quadrant) read whatever stale
8467 /// mode sat in that slot before either leaf ran. Fixed by writing the
8468 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
8469 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
8470 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
8471 /// offset of a single unit; fixing (3)+(4) together still leaves a
8472 /// residual divergence one leaf further in -- the decoder now reads
8473 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
8474 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
8475 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
8476 /// desyncs the stream by exactly the width of one earlier symbol -- not
8477 /// yet isolated to a single named symbol. r15 found the last bug: the
8478 /// header fix from r14 explained the rng skew fully, and the remaining
8479 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
8480 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
8481 /// loop, once per leaf, so the first leaf's write clobbered the true
8482 /// external neighbour mode the second leaf of the *same* straddling
8483 /// quadrant still needed for its non-adjacency axis (a column-straddle
8484 /// case: two leaves share one `outer_at` column index, so leaf 1's
8485 /// write to `left_mode[r]` overwrote the real western neighbour before
8486 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
8487 /// doing it once, after the whole leaf loop, from the last (bottom/
8488 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
8489 #[test]
8490 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
8491 let fctx = &crate::decode::FrameCtx::new();
8492 if !have_ffmpeg() {
8493 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
8494 return;
8495 }
8496 let (width, height) = (40usize, 32usize);
8497 let picture = test_card(width, height);
8498 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8499 assert_eq!(
8500 (encoded.reconstruction.width, encoded.reconstruction.height),
8501 (width, height)
8502 );
8503 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
8504 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
8505 }
8506 let decoded = ffmpeg_decode(&encoded.stream, width, height);
8507 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
8508 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
8509 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
8510 }
8511
8512 /// A frame of real video, rather than a picture built to be easy.
8513 ///
8514 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
8515 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
8516 /// encoder's reconstruction has to survive the same equality gate as the
8517 /// synthetic pictures — real video reaches contexts a test card does not.
8518 #[test]
8519 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
8520 let fctx = &crate::decode::FrameCtx::new();
8521 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
8522 eprintln!(
8523 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
8524 set EC_AV1_CLIP to a clip"
8525 );
8526 return;
8527 };
8528 if !have_ffmpeg() {
8529 eprintln!(
8530 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
8531 );
8532 return;
8533 }
8534 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
8535 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
8536 // test quick while still spanning many superblocks.
8537 let (width, height) = (640usize, 352usize);
8538 let picture = clip_frame(&clip, &skip, width, height);
8539
8540 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8541 let decoded = ffmpeg_decode(&encoded.stream, width, height);
8542 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
8543 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
8544 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
8545 eprintln!(
8546 "{} bytes, luma PSNR {:.2} dB",
8547 encoded.stream.len(),
8548 psnr(&decoded.y, &picture.y)
8549 );
8550 }
8551
8552 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
8553 /// sequence of these is a translation a motion search can actually find
8554 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
8555 /// inter frame's rate against the key frame's is measuring the same
8556 /// picture moving, not two different pictures.
8557 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
8558 let mut picture = Picture::grey(width, height);
8559 for y in 0..height {
8560 for x in 0..width {
8561 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
8562 let gradient = sx * 200.0 / width as f64;
8563 let ripple = 30.0
8564 * (sx * std::f64::consts::PI / 23.0).sin()
8565 * (y as f64 * std::f64::consts::PI / 37.0).cos();
8566 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
8567 40.0
8568 } else {
8569 0.0
8570 };
8571 picture.y[y * width + x] =
8572 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
8573 }
8574 }
8575 for y in 0..height / 2 {
8576 for x in 0..width / 2 {
8577 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
8578 let i = y * width / 2 + x;
8579 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
8580 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
8581 }
8582 }
8583 picture
8584 }
8585
8586 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
8587 fn ffmpeg_decode_sequence(
8588 stream: &[u8],
8589 width: usize,
8590 height: usize,
8591 frames: usize,
8592 ) -> Vec<Picture> {
8593 let mut child = Command::new("ffmpeg")
8594 .args([
8595 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
8596 ])
8597 .stdin(Stdio::piped())
8598 .stdout(Stdio::piped())
8599 .stderr(Stdio::piped())
8600 .spawn()
8601 .expect("ffmpeg failed to start");
8602 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
8603 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
8604 // fills before the last input byte is written -- which is exactly what
8605 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
8606 // (measured: 45 min, both processes at 0% CPU). A write error here is
8607 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
8608 // below, are the real diagnosis.
8609 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
8610 let payload = stream.to_vec();
8611 let writer = std::thread::spawn(move || {
8612 let _ = stdin.write_all(&payload);
8613 });
8614 let out = child.wait_with_output().expect("ffmpeg failed to run");
8615 writer.join().expect("ffmpeg stdin writer thread");
8616 assert!(
8617 out.status.success(),
8618 "ffmpeg refused the stream: {}",
8619 String::from_utf8_lossy(&out.stderr)
8620 );
8621 let (luma, chroma) = (width * height, width * height / 4);
8622 let frame_bytes = luma + 2 * chroma;
8623 assert_eq!(
8624 out.stdout.len(),
8625 frame_bytes * frames,
8626 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
8627 String::from_utf8_lossy(&out.stderr)
8628 );
8629 (0..frames)
8630 .map(|i| {
8631 let base = i * frame_bytes;
8632 Picture {
8633 width,
8634 height,
8635 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
8636 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
8637 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
8638 }
8639 })
8640 .collect()
8641 }
8642
8643 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
8644 /// makes for a key frame, extended down the reference chain: each inter
8645 /// frame's reconstruction predicts from the previous frame's own decoded
8646 /// reconstruction, so a single sample of drift anywhere would propagate
8647 /// into every frame after it -- which is why every frame is checked, not
8648 /// just the last one, and why this is an equality and not a tolerance.
8649 #[test]
8650 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
8651 let fctx = &crate::decode::FrameCtx::new();
8652 if !have_ffmpeg() {
8653 eprintln!(
8654 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
8655 );
8656 return;
8657 }
8658 let (width, height) = (128usize, 64usize);
8659 let pictures: Vec<Picture> = (0..5)
8660 .map(|i| panned_test_card(width, height, i * 3))
8661 .collect();
8662 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
8663 assert_eq!(encoded.frames.len(), 5);
8664
8665 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
8666 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
8667 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
8668 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
8669 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
8670 }
8671
8672 eprintln!("frame bytes luma PSNR (dB) inter share");
8673 for (i, frame) in encoded.frames.iter().enumerate() {
8674 eprintln!(
8675 "{i:5} {:5} {:14.2} {:11.2}",
8676 frame.stream.len(),
8677 psnr(&frame.reconstruction.y, &pictures[i].y),
8678 frame.inter_block_share
8679 );
8680 }
8681 }
8682
8683 /// The same sequence through OUR OWN decoder, sample-exact against the
8684 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
8685 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
8686 /// divergence point at all, while our decoder can be traced symbol by
8687 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
8688 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
8689 /// names the first differing frame, plane and position.
8690 #[test]
8691 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
8692 let fctx = &crate::decode::FrameCtx::new();
8693 let (width, height) = (128usize, 64usize);
8694 let pictures: Vec<Picture> =
8695 (0..5).map(|i| panned_test_card(width, height, i * 3)).collect();
8696 let _ = take_inter_tx_split_hits();
8697 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
8698 let split = take_inter_tx_split_hits();
8699 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
8700 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
8701 // content splits -- a green round trip in which the split never fires
8702 // would prove only the flat path.
8703 if tx_select() && tx_select_inter() {
8704 assert!(split[1] > 0, "the inter var-tx split never fired");
8705 }
8706 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
8707 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
8708 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
8709 let recon = &frame.reconstruction;
8710 for (plane, got, want, stride) in [
8711 ("luma", &dec.y, &recon.y, width),
8712 ("U", &dec.u, &recon.u, width / 2),
8713 ("V", &dec.v, &recon.v, width / 2),
8714 ] {
8715 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
8716 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
8717 panic!(
8718 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
8719 reconstruction {} ({} of {} samples differ)",
8720 at % stride,
8721 at / stride,
8722 got[at],
8723 want[at],
8724 got.iter().zip(want).filter(|(a, b)| a != b).count(),
8725 got.len(),
8726 );
8727 }
8728 }
8729 }
8730 }
8731
8732 /// The rate term the mode search ranks every decision by has to be the
8733 /// rate the writer then spends. The search prices a block's coefficients
8734 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
8735 /// against the default CDFs a tile starts from and the contexts of a
8736 /// block whose neighbours coded nothing -- while the tile writer codes
8737 /// them against a state that has been adapting all frame (the
8738 /// price-the-narrowing class). This measures that drift: the sum of what
8739 /// the search paid for the coefficients it kept, against the bytes the
8740 /// writer actually emitted for the whole tile (which also carries the
8741 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
8742 /// expected to be the larger of the two).
8743 #[test]
8744 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
8745 let fctx = &crate::decode::FrameCtx::new();
8746 let (width, height) = (256usize, 128usize);
8747 let pictures: Vec<Picture> = (0..5)
8748 .map(|i| panned_test_card(width, height, i * 2))
8749 .collect();
8750 let _ = take_predicted_bits();
8751 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
8752 let predicted = take_predicted_bits();
8753 assert_eq!(predicted.len(), encoded.frames.len());
8754
8755 eprintln!("frame predicted bits written bits drift");
8756 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
8757 // defect this gate exists to catch), a positive one is the written
8758 // side carrying syntax the coefficient sum leaves out -- and since
8759 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
8760 // on that side, so the two directions no longer share a bound.
8761 let mut worst_over: f64 = 0.0;
8762 let mut worst_under: f64 = 0.0;
8763 for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() {
8764 let written = frame.tile.len() as f64 * 8.0;
8765 let drift = (written - bits) / written;
8766 worst_over = worst_over.max(-drift);
8767 worst_under = worst_under.max(drift);
8768 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
8769 }
8770 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
8771 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
8772 // over-prices every frame but the last (its sum EXCLUDES the
8773 // partition/mode/skip/mv syntax the written side carries, so the true
8774 // coefficient over-price is larger still): the writer's CDFs adapt to
8775 // the content while the search's stay at the defaults. The bound is
8776 // set just above the worst measured point -- a widening drift is the
8777 // thing this gate exists to catch.
8778 assert!(
8779 worst_over <= 0.16,
8780 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
8781 worst_over * 100.0
8782 );
8783 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
8784 // the worst inter frame, where nearly every block now codes an MV
8785 // residual and a reference the coefficient sum never counts. Re-measured
8786 // at +29.6% once the encoder's grid published compound blocks properly
8787 // (compound share 8.8% -> 11.5%): a compound block carries a second
8788 // reference tree, a compound mode symbol and -- for the half-new modes
8789 // -- an MV residual, none of which the coefficient sum counts.
8790 assert!(
8791 worst_under <= 0.32,
8792 "the writer spent {:.2}% more than the search priced -- more than \
8793 the mode/mv syntax outside the coefficient sum explains",
8794 worst_under * 100.0
8795 );
8796 }
8797
8798 /// Low motion has to actually buy something: at least one inter frame of
8799 /// a panning sequence has to cost fewer bytes than the key frame that
8800 /// starts it, and the inter-block share it prints has to be non-zero --
8801 /// a search that never picks an inter mode would still pass a rate gate
8802 /// on a picture with no motion in it (the class this repo calls
8803 /// gate-blind-to-feature), so the share is printed even though it is not
8804 /// asserted on beyond being reachable at all.
8805 #[test]
8806 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
8807 let fctx = &crate::decode::FrameCtx::new();
8808 let (width, height) = (256usize, 128usize);
8809 let pictures: Vec<Picture> = (0..5)
8810 .map(|i| panned_test_card(width, height, i * 2))
8811 .collect();
8812 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
8813
8814 let key_bytes = encoded.frames[0].stream.len();
8815 eprintln!("frame bytes inter share");
8816 for (i, frame) in encoded.frames.iter().enumerate() {
8817 eprintln!(
8818 "{i:5} {:5} {:11.2}",
8819 frame.stream.len(),
8820 frame.inter_block_share
8821 );
8822 }
8823 assert!(
8824 encoded.frames[1..]
8825 .iter()
8826 .any(|f| f.stream.len() < key_bytes),
8827 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
8828 );
8829 assert!(
8830 encoded.frames[1..]
8831 .iter()
8832 .any(|f| f.inter_block_share > 0.0),
8833 "no inter frame coded a single inter block -- the search never fired"
8834 );
8835 }
8836
8837 /// A manual perf probe, not a gate: prints where a key frame's and an
8838 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
8839 /// measures before it optimizes rather than guessing. Run with
8840 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
8841 #[test]
8842 #[ignore = "a perf probe, not a gate"]
8843 fn stage_timing_breakdown() {
8844 let fctx = &crate::decode::FrameCtx::new();
8845 use std::time::Instant;
8846
8847 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
8848 let picture = test_card(width, height);
8849
8850 let t = Instant::now();
8851 let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
8852 let dc_only_t = t.elapsed();
8853
8854 let t = Instant::now();
8855 let non_directional =
8856 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
8857 let non_directional_t = t.elapsed();
8858
8859 let t = Instant::now();
8860 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8861 let all_modes_t = t.elapsed();
8862
8863 eprintln!(
8864 "\n=== key frame {width}x{height} ===\n\
8865 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
8866 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
8867 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
8868 dc_only.stream.len(),
8869 non_directional.stream.len(),
8870 all_modes.stream.len(),
8871 );
8872
8873 // One inter frame predicting off the key frame's own
8874 // reconstruction, the (256, 256)-padded surface encode_sequence
8875 // itself would hand encode_inter_frame.
8876 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
8877 let padded_pic = picture.padded_to(SUPERBLOCK);
8878 let t = Instant::now();
8879 let inter =
8880 encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None).unwrap();
8881 let inter_t = t.elapsed();
8882 eprintln!(
8883 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
8884 {:.2})",
8885 inter.stream.len(),
8886 inter.inter_block_share
8887 );
8888 }
8889
8890 // Isolated per-call cost of the trial pipeline's own stages, at both
8891 // transform sizes the search runs, averaged over enough calls to
8892 // rise above `Instant::now`'s own noise.
8893 for side in [16usize, 32] {
8894 const N: u32 = 20_000;
8895 let residual: Vec<i32> = (0..side * side)
8896 .map(|i| ((i * 37 % 61) as i32) - 30)
8897 .collect();
8898
8899 let t = Instant::now();
8900 let mut levels = Vec::new();
8901 for _ in 0..N {
8902 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
8903 }
8904 let forward_t = t.elapsed() / N;
8905
8906 let t = Instant::now();
8907 for _ in 0..N {
8908 std::hint::black_box(dequant_and_inverse(&levels, side, 8, 100));
8909 }
8910 let inverse_t = t.elapsed() / N;
8911
8912 let set = if side == 32 {
8913 crate::cdf_state::TxbSet::Luma32
8914 } else {
8915 crate::cdf_state::TxbSet::Luma16
8916 };
8917 let t = Instant::now();
8918 for _ in 0..N {
8919 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2));
8920 }
8921 let entropy_t = t.elapsed() / N;
8922
8923 let above = vec![128u8; side * 2];
8924 let left = vec![128u8; side * 2];
8925 let mut prediction = vec![0u8; side * side];
8926 let t = Instant::now();
8927 for _ in 0..N {
8928 intra_predict_u8(
8929 D45_PRED,
8930 0,
8931 Some(&above),
8932 Some(&left),
8933 Some(128),
8934 side,
8935 side,
8936 false,
8937 false,
8938 &mut prediction, fctx,
8939 );
8940 }
8941 let predict_t = t.elapsed() / N;
8942
8943 eprintln!(
8944 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
8945 predict (1 directional mode): {predict_t:>9.2?}\n\
8946 forward_and_quantize: {forward_t:>9.2?}\n\
8947 dequant_and_inverse: {inverse_t:>9.2?}\n\
8948 coeff_bits: {entropy_t:>9.2?}"
8949 );
8950 }
8951 }
8952
8953 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
8954 /// (motion search, [`crate::mc::predict`], transform+quantize,
8955 /// `coeff_bits`), plus what is left over once those are subtracted --
8956 /// the thirteen-mode intra-candidate loop `search_inter_block` still
8957 /// runs on every inter block (its own transform/quant/entropy calls are
8958 /// already inside buckets 2/3, so "left over" here is everything NOT
8959 /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
8960 /// symbol-cost lookups outside `coeff_bits`).
8961 ///
8962 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
8963 #[test]
8964 #[ignore = "a perf probe, not a gate"]
8965 fn stage_timing_breakdown_inter() {
8966 let fctx = &crate::decode::FrameCtx::new();
8967 use std::time::Instant;
8968
8969 let (width, height) = (1280usize, 720);
8970 let picture = test_card(width, height);
8971 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8972 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
8973 let padded_pic = picture.padded_to(SUPERBLOCK);
8974
8975 stage_reset();
8976 let t = Instant::now();
8977 let inter =
8978 encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, flat_order_hints(1, 0, false), (width, height), None, None, None, fctx, None).unwrap();
8979 let total_t = t.elapsed();
8980 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
8981 let accounted = motion_search + transform_quant + entropy;
8982 // motion_search already contains interpolation's own time (every
8983 // candidate the search costs calls crate::mc::predict), so it is not
8984 // added again here -- interpolation is reported alongside as "of
8985 // which interpolation", not as a fifth additive bucket.
8986 let other = total_t.saturating_sub(accounted);
8987
8988 eprintln!(
8989 "\n=== inter frame {width}x{height}, one frame ===\n\
8990 total: {total_t:>9.2?} ({} bytes)\n\
8991 motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
8992 {interpolation:>9.2?})\n\
8993 transform + quantize: {transform_quant:>9.2?}\n\
8994 coeff_bits (entropy pricing): {entropy:>9.2?}\n\
8995 everything else (13-mode intra {other:>9.2?}\n\
8996 candidate loop's own predict/bookkeeping, NEARESTMV's own \
8997 predict, RD glue):",
8998 inter.stream.len(),
8999 );
9000 }
9001
9002 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
9003 /// frames (a dark/flat one, a detailed one, a normal film one) at two
9004 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
9005 /// None`, the baseline this same build produces without
9006 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
9007 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
9008 /// go in the lane report, which is where "ship as default" is decided --
9009 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
9010 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
9011 #[test]
9012 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
9013 fn prune_k_quality_sweep() {
9014 let fctx = &crate::decode::FrameCtx::new();
9015 if !have_ffmpeg() {
9016 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
9017 return;
9018 }
9019 let (width, height) = (640usize, 352usize);
9020 let frames: &[(&str, &str, &str)] = &[
9021 // (label, clip, seek) -- a near-black scene, a busy one, and an
9022 // ordinary film frame, each from a different real file.
9023 (
9024 "dark/flat",
9025 "/home/user/Videos/reela.mp4",
9026 "3",
9027 ),
9028 (
9029 "detailed",
9030 "/home/user/Downloads/reelb.mkv",
9031 "1200",
9032 ),
9033 (
9034 "film",
9035 "/home/user/Videos/Films/reelc.mkv",
9036 "600",
9037 ),
9038 ];
9039 for &(label, clip, skip) in frames {
9040 if !std::path::Path::new(clip).exists() {
9041 eprintln!("SKIP {label}: {clip} not present on this machine");
9042 continue;
9043 }
9044 let picture = clip_frame(clip, skip, width, height);
9045 for &q in &[60u8, 150] {
9046 // SAFETY (not literally unsafe, just process-global): this is
9047 // a single-threaded #[ignore] probe, run by hand, never
9048 // alongside other tests that read Search::top_k.
9049 set_test_top_k_override(None);
9050 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
9051 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
9052 eprint!(
9053 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
9054 baseline.stream.len(),
9055 baseline_psnr
9056 );
9057 for &k in &[3usize, 4, 6] {
9058 set_test_top_k_override(Some(k));
9059 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
9060 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
9061 eprint!(
9062 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
9063 pruned.stream.len(),
9064 pruned_psnr,
9065 pruned_psnr - baseline_psnr
9066 );
9067 }
9068 eprintln!();
9069 }
9070 }
9071 set_test_top_k_override(None);
9072 }
9073
9074 /// Two consecutive decoded frames from one clip, for an inter-frame
9075 /// sweep -- [`clip_frame`] alone only ever gives one.
9076 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
9077 let out = Command::new("ffmpeg")
9078 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
9079 .args(["-vf", &format!("scale={width}:{height}")])
9080 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
9081 .output()
9082 .expect("ffmpeg failed to run");
9083 assert!(
9084 out.status.success(),
9085 "ffmpeg: {}",
9086 String::from_utf8_lossy(&out.stderr)
9087 );
9088 let (luma, chroma) = (width * height, width * height / 4);
9089 let frame_len = luma + 2 * chroma;
9090 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
9091 std::array::from_fn(|i| {
9092 let bytes = &out.stdout[i * frame_len..][..frame_len];
9093 Picture {
9094 width,
9095 height,
9096 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
9097 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
9098 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
9099 }
9100 })
9101 }
9102
9103 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
9104 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
9105 /// then one inter frame off it (`search_inter_block`'s own intra
9106 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
9107 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
9108 /// padding step complicates the comparison. Prints bytes and luma PSNR
9109 /// for the inter frame alone, unpruned vs each `K`.
9110 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
9111 #[test]
9112 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
9113 fn prune_k_quality_sweep_inter() {
9114 let fctx = &crate::decode::FrameCtx::new();
9115 if !have_ffmpeg() {
9116 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
9117 return;
9118 }
9119 let (width, height) = (1280usize, 704usize);
9120 let frames: &[(&str, &str, &str)] = &[
9121 (
9122 "dark/flat",
9123 "/home/user/Videos/reela.mp4",
9124 "3",
9125 ),
9126 (
9127 "detailed",
9128 "/home/user/Downloads/reelb.mkv",
9129 "1200",
9130 ),
9131 (
9132 "film",
9133 "/home/user/Videos/Films/reelc.mkv",
9134 "600",
9135 ),
9136 ];
9137 for &(label, clip, skip) in frames {
9138 if !std::path::Path::new(clip).exists() {
9139 eprintln!("SKIP {label}: {clip} not present on this machine");
9140 continue;
9141 }
9142 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
9143 for &q in &[60u8, 150] {
9144 // SAFETY (not literally unsafe, just process-global): a
9145 // single-threaded #[ignore] probe, run by hand, never
9146 // alongside other tests that read Search::top_k.
9147 set_test_top_k_override_inter(None);
9148 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
9149 let baseline = encode_inter_frame(
9150 &inter_source,
9151 &key.reconstruction,
9152 q,
9153 0.5,
9154 1,
9155 flat_order_hints(1, 0, false),
9156 (width, height), None, None, None, fctx, None,
9157 )
9158 .unwrap();
9159 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
9160 eprint!(
9161 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
9162 baseline.stream.len(),
9163 baseline_psnr
9164 );
9165 for &k in &[3usize, 4, 6] {
9166 set_test_top_k_override_inter(Some(k));
9167 let pruned = encode_inter_frame(
9168 &inter_source,
9169 &key.reconstruction,
9170 q,
9171 0.5,
9172 1,
9173 flat_order_hints(1, 0, false),
9174 (width, height), None, None, None, fctx, None,
9175 )
9176 .unwrap();
9177 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
9178 eprint!(
9179 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
9180 pruned.stream.len(),
9181 pruned_psnr,
9182 pruned_psnr - baseline_psnr
9183 );
9184 }
9185 eprintln!();
9186 }
9187 }
9188 set_test_top_k_override_inter(None);
9189 }
9190
9191 /// `frames` consecutive pictures out of a real clip, scaled to a whole
9192 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
9193 /// to an arbitrary count for the fixture regression gate below.
9194 fn clip_frames(
9195 clip: &str,
9196 skip: &str,
9197 width: usize,
9198 height: usize,
9199 frames: usize,
9200 ) -> Vec<Picture> {
9201 let out = Command::new("ffmpeg")
9202 .args(["-v", "error", "-ss", skip, "-i", clip])
9203 .args(["-frames:v", &frames.to_string()])
9204 .args(["-vf", &format!("scale={width}:{height}")])
9205 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
9206 .output()
9207 .expect("ffmpeg failed to run");
9208 assert!(
9209 out.status.success(),
9210 "ffmpeg: {}",
9211 String::from_utf8_lossy(&out.stderr)
9212 );
9213 let (luma, chroma) = (width * height, width * height / 4);
9214 let frame_len = luma + 2 * chroma;
9215 assert_eq!(
9216 out.stdout.len(),
9217 frame_len * frames,
9218 "expected {frames} 4:2:0 frames"
9219 );
9220 (0..frames)
9221 .map(|i| {
9222 let bytes = &out.stdout[i * frame_len..][..frame_len];
9223 Picture {
9224 width,
9225 height,
9226 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
9227 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
9228 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
9229 }
9230 })
9231 .collect()
9232 }
9233
9234 /// The standing regression gate on real content: 12 frames of a real
9235 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
9236 /// this crate's own input regardless of its own source codec), encoded
9237 /// as an AV1 GOP and checked against three numeric floors so a
9238 /// compatibility or quality regression fails the suite instead of
9239 /// waiting for a downstream repo's gate to catch it (as happened for a
9240 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
9241 /// refusal, both caught only that way).
9242 ///
9243 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
9244 /// that geometry is already covered elsewhere), chosen only so encode
9245 /// time and gate numbers are not muddied by an edge-block class this
9246 /// test is not about.
9247 ///
9248 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
9249 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
9250 /// below carry a margin off those measured numbers (PSNR floor =
9251 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
9252 #[test]
9253 fn real_clip_encodes_within_its_quality_and_size_budget() {
9254 let fctx = &crate::decode::FrameCtx::new();
9255 if !have_ffmpeg() {
9256 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
9257 return;
9258 }
9259 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9260 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
9261 if !clip.exists() {
9262 eprintln!(
9263 "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing",
9264 clip.display()
9265 );
9266 return;
9267 }
9268 let (width, height, frame_count) = (640usize, 384usize, 12usize);
9269 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
9270 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
9271 assert_eq!(encoded.frames.len(), frame_count);
9272
9273 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
9274 // stream and hands back every frame -- a stream a downstream
9275 // decoder refuses is the exact class of regression this gate
9276 // exists for.
9277 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
9278 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
9279
9280 // Gate 2: quality vs the source did not silently collapse.
9281 let mean_psnr: f64 = decoded
9282 .iter()
9283 .zip(&source)
9284 .map(|(d, s)| psnr(&d.y, &s.y))
9285 .sum::<f64>()
9286 / frame_count as f64;
9287 assert!(
9288 mean_psnr >= 44.91,
9289 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
9290 );
9291
9292 // Gate 3: the stream did not silently bloat.
9293 assert!(
9294 encoded.stream.len() <= 80_340,
9295 "stream grew to {} bytes, over the 80340-byte ceiling",
9296 encoded.stream.len()
9297 );
9298 }
9299
9300 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
9301 /// straddle size: 640x384 is exact on both axes (32-aligned), so
9302 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
9303 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
9304 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
9305 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
9306 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
9307 /// card; this one is the real-clip gate, same three floors.
9308 ///
9309 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
9310 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
9311 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
9312 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
9313 #[test]
9314 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
9315 let fctx = &crate::decode::FrameCtx::new();
9316 if !have_ffmpeg() {
9317 eprintln!(
9318 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
9319 no ffmpeg"
9320 );
9321 return;
9322 }
9323 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9324 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
9325 if !clip.exists() {
9326 eprintln!(
9327 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
9328 {} missing",
9329 clip.display()
9330 );
9331 return;
9332 }
9333 let (width, height, frame_count) = (704usize, 400usize, 8usize);
9334 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
9335 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
9336 assert_eq!(encoded.frames.len(), frame_count);
9337
9338 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
9339 // stream and hands back every frame.
9340 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
9341 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
9342
9343 // Gate 2: quality vs the source did not silently collapse.
9344 let mean_psnr: f64 = decoded
9345 .iter()
9346 .zip(&source)
9347 .map(|(d, s)| psnr(&d.y, &s.y))
9348 .sum::<f64>()
9349 / frame_count as f64;
9350 assert!(
9351 mean_psnr >= 44.98,
9352 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
9353 );
9354
9355 // Gate 3: the stream did not silently bloat.
9356 assert!(
9357 encoded.stream.len() <= 62_703,
9358 "stream grew to {} bytes, over the 62703-byte ceiling",
9359 encoded.stream.len()
9360 );
9361 }
9362
9363 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
9364 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
9365 /// facade -- timed end to end, so the edith export-time projection is a
9366 /// real number rather than a guess from the isolated key/inter numbers
9367 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
9368 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
9369 #[test]
9370 #[ignore = "a perf probe, not a gate"]
9371 fn sequence_bench_sanity() {
9372 let fctx = &crate::decode::FrameCtx::new();
9373 use std::time::Instant;
9374 let (width, height) = (1280usize, 720usize);
9375 let pictures: Vec<Picture> = (0..24)
9376 .map(|i| panned_test_card(width, height, i * 3))
9377 .collect();
9378 let t = Instant::now();
9379 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
9380 let elapsed = t.elapsed();
9381 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
9382 eprintln!(
9383 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
9384 elapsed / 24
9385 );
9386 }
9387
9388 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
9389 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
9390 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
9391 /// -- --ignored --nocapture`.
9392 #[test]
9393 #[ignore = "a calibration probe, not a gate"]
9394 fn calibration_sweep_base_q_idx() {
9395 let fctx = &crate::decode::FrameCtx::new();
9396 if !have_ffmpeg() {
9397 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
9398 return;
9399 }
9400 let (width, height, frames) = (640usize, 384usize, 12usize);
9401 for clip in [
9402 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
9403 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
9404 ] {
9405 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9406 .join("../../fixtures/video")
9407 .join(clip);
9408 if !path.exists() {
9409 eprintln!("SKIP {clip}: fixture missing");
9410 continue;
9411 }
9412 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
9413 eprintln!("--- {clip} ---");
9414 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
9415 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
9416 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
9417 let mean_psnr: f64 = decoded
9418 .iter()
9419 .zip(&source)
9420 .map(|(d, s)| psnr(&d.y, &s.y))
9421 .sum::<f64>()
9422 / frames as f64;
9423 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
9424 eprintln!(
9425 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
9426 encoded.stream.len()
9427 );
9428 }
9429 }
9430 }
9431
9432 // -----------------------------------------------------------------------
9433 // The encoder's standing BD-rate baseline against libaom and rav1e.
9434 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
9435 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
9436 // agreeing with our encoder proves nothing about the bitstream.
9437 // -----------------------------------------------------------------------
9438
9439 /// All-plane PSNR of a decoded picture against its source, on the same
9440 /// 8-bit scale [`psnr`] uses.
9441 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
9442 let cat = |p: &Picture| {
9443 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
9444 v.extend_from_slice(&p.y);
9445 v.extend_from_slice(&p.u);
9446 v.extend_from_slice(&p.v);
9447 v
9448 };
9449 psnr(&cat(decoded), &cat(source))
9450 }
9451
9452 /// The pictures back as the planar 8-bit bytes an encoder reads.
9453 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
9454 let mut raw = Vec::new();
9455 for p in source {
9456 for plane in [&p.y, &p.u, &p.v] {
9457 raw.extend(plane.iter().map(|&s| s as u8));
9458 }
9459 }
9460 raw
9461 }
9462
9463 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
9464 /// through ffmpeg: one point per entry of `points`, each a quality flag
9465 /// set. Returns the ladder ordered by fidelity and the total encode wall
9466 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
9467 /// so both curves are measured by the same decoder.
9468 fn external_ladder(
9469 source: &[Picture],
9470 width: usize,
9471 height: usize,
9472 encoder: &str,
9473 points: &[Vec<String>],
9474 ) -> (Vec<(f64, f64)>, f64) {
9475 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
9476 let dir = std::env::temp_dir();
9477 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
9478 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
9479 let mut ladder = Vec::new();
9480 let mut wall = 0.0;
9481 for (i, params) in points.iter().enumerate() {
9482 let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id()));
9483 let start = std::time::Instant::now();
9484 let out = Command::new("ffmpeg")
9485 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
9486 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
9487 .arg(&raw_path)
9488 .args(["-an", "-threads", "1"])
9489 .args(["-g", &source.len().to_string(), "-c:v", encoder])
9490 .args(params)
9491 .args(["-f", "obu"])
9492 .arg(&obu)
9493 .output()
9494 .expect("ffmpeg failed to run");
9495 wall += start.elapsed().as_secs_f64();
9496 assert!(
9497 out.status.success(),
9498 "{encoder} {params:?}: {}",
9499 String::from_utf8_lossy(&out.stderr)
9500 );
9501 let stream = std::fs::read(&obu).expect("reference stream");
9502 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
9503 let mean: f64 = decoded
9504 .iter()
9505 .zip(source)
9506 .map(|(d, s)| psnr_all(d, s))
9507 .sum::<f64>()
9508 / source.len() as f64;
9509 ladder.push((mean, (stream.len() as f64).log10()));
9510 let _ = std::fs::remove_file(&obu);
9511 }
9512 let _ = std::fs::remove_file(&raw_path);
9513 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
9514 (ladder, wall)
9515 }
9516
9517 /// First differing sample between two pictures, as
9518 /// `(plane, index, left, right)` -- so a gate failure names the plane and
9519 /// the sample instead of just "differs". A length difference counts as a
9520 /// mismatch of that plane at the first index past the shorter one.
9521 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
9522 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
9523 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
9524 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
9525 }
9526 if l.len() != r.len() {
9527 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
9528 }
9529 }
9530 None
9531 }
9532
9533 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
9534 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
9535 /// stream is decoded twice -- by ffmpeg and by our own
9536 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
9537 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
9538 /// in Y, U and V over every shown frame in display order. That is itself
9539 /// a gate: it proves the bitstream says what the encoder thinks, in the
9540 /// only two decoders that read it.
9541 fn our_ladder(
9542 name: &str,
9543 source: &[Picture],
9544 width: usize,
9545 height: usize,
9546 fctx: &crate::decode::FrameCtx,
9547 ) -> (Vec<(f64, f64)>, f64) {
9548 let mut ladder = Vec::new();
9549 let mut wall = 0.0;
9550 for &q in &[150u8, 120, 90, 60] {
9551 let start = std::time::Instant::now();
9552 let encoded = encode_sequence_with_ctx(source, q, 0.5, fctx).unwrap();
9553 wall += start.elapsed().as_secs_f64();
9554 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
9555 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
9556 assert_eq!(
9557 ours.len(),
9558 source.len(),
9559 "{name} q={q}: our decoder's display-order frame count"
9560 );
9561 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
9562 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
9563 panic!(
9564 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
9565 {got}, the encoder reconstructed {want}"
9566 );
9567 }
9568 }
9569 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
9570 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
9571 panic!(
9572 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
9573 {got}, the encoder reconstructed {want}"
9574 );
9575 }
9576 }
9577 let mean: f64 = decoded
9578 .iter()
9579 .zip(source)
9580 .map(|(d, s)| psnr_all(d, s))
9581 .sum::<f64>()
9582 / source.len() as f64;
9583 ladder.push((mean, (encoded.stream.len() as f64).log10()));
9584 }
9585 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
9586 (ladder, wall)
9587 }
9588
9589 /// The [`crate::encoder::Pyramid`] this run's ladder is coded under, from
9590 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]`. Unset
9591 /// keeps the flat one-key-then-all-inter ladder the baseline was measured
9592 /// on, so the gate's default recipe is unchanged.
9593 fn pyramid_from_env() -> Option<crate::encoder::Pyramid> {
9594 let spec = std::env::var("EC_AV1_PYRAMID").ok()?;
9595 let mut f = spec.split(':');
9596 let mini_gop = f.next()?.parse().ok()?;
9597 let d = crate::encoder::Pyramid::default();
9598 Some(crate::encoder::Pyramid {
9599 mini_gop,
9600 arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset),
9601 leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset),
9602 })
9603 }
9604
9605 /// [`our_ladder`] through the streaming facade with a coding pyramid: the
9606 /// four points are the same `base_q_idx` ladder, but each stream is
9607 /// reordered (hidden `ALTREF` first, `show_existing_frame` last per
9608 /// group) and each level is coded at its own quantizer offset. Returns
9609 /// the ladder, the wall, and — per pyramid level over the whole ladder —
9610 /// how many frames and how many bytes it spent.
9611 fn our_ladder_pyramid(
9612 name: &str,
9613 source: &[Picture],
9614 width: usize,
9615 height: usize,
9616 pyramid: crate::encoder::Pyramid,
9617 ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4]) {
9618 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
9619 let slot = |l: Level| match l {
9620 Level::Key => 0,
9621 Level::Arf => 1,
9622 Level::Leaf => 2,
9623 Level::ShowExisting => 3,
9624 };
9625 let mut ladder = Vec::new();
9626 let mut wall = 0.0;
9627 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
9628 for &q in &[150u8, 120, 90, 60] {
9629 let config = EncoderConfig {
9630 width,
9631 height,
9632 base_q_idx: q,
9633 gop: source.len(),
9634 colour: Colour::Unspecified,
9635 tile_cols_log2: 0,
9636 tile_rows_log2: 0,
9637 };
9638 let start = std::time::Instant::now();
9639 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
9640 let mut packets = Vec::new();
9641 for picture in source {
9642 packets.extend(enc.encode_frames(picture).unwrap());
9643 }
9644 packets.extend(enc.flush().unwrap());
9645 wall += start.elapsed().as_secs_f64();
9646 let mut stream = Vec::new();
9647 for p in &packets {
9648 counts[slot(p.level)] += 1;
9649 bytes[slot(p.level)] += p.data.len();
9650 stream.extend_from_slice(&p.data);
9651 }
9652 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
9653 // correct if the DISPLAY-order output still has one frame per
9654 // source picture, in the right order -- checked against our own
9655 // decoder as well as ffmpeg's, both below.
9656 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
9657 assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count");
9658 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
9659 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
9660 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
9661 panic!(
9662 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
9663 decoded {got}, our decoder decoded {want}"
9664 );
9665 }
9666 }
9667 let mean: f64 = decoded
9668 .iter()
9669 .zip(source)
9670 .map(|(d, s)| psnr_all(d, s))
9671 .sum::<f64>()
9672 / source.len() as f64;
9673 ladder.push((mean, (stream.len() as f64).log10()));
9674 }
9675 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
9676 (ladder, wall, counts, bytes)
9677 }
9678
9679 /// Byte-exactness gate for encoder work that is meant to change only
9680 /// how long the encoder takes.
9681 ///
9682 /// The BD gate above measures quality, which a speed lane can move by a
9683 /// hair without failing anything; this pins the streams themselves.
9684 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
9685 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
9686 /// in the tile) and again on lane-av1mv's merge of it: an extra
9687 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
9688 /// above, not by this pin.
9689 #[test]
9690 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
9691 if !have_ffmpeg() {
9692 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
9693 return;
9694 }
9695 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9696 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
9697 if !clip.exists() {
9698 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip");
9699 return;
9700 }
9701 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
9702 // FNV-1a over the stream: a witness that every coded bit is where it
9703 // was, which a byte count alone is not.
9704 let fnv = |b: &[u8]| {
9705 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
9706 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
9707 })
9708 };
9709 let pins: [(u8, usize, u64); 2] =
9710 [(150, 7084, 0xe6a9_2f62_3855_0eee), (60, 26116, 0xa831_9866_b799_80fc)];
9711 for (q, bytes, hash) in pins {
9712 let encoded = encode_sequence(&source, q, 0.5).unwrap();
9713 assert_eq!(
9714 (encoded.stream.len(), fnv(&encoded.stream)),
9715 (bytes, hash),
9716 "q={q}: the encoder's stream moved"
9717 );
9718 }
9719 }
9720
9721 /// A ladder is only a ladder if both axes rise together.
9722 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
9723 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
9724 for w in ladder.windows(2) {
9725 assert!(
9726 w[1].0 > w[0].0 && w[1].1 > w[0].1,
9727 "{name}: not monotone, {ladder:?}"
9728 );
9729 }
9730 }
9731
9732 /// The sweep behind [`screen_content`]'s two constants
9733 /// (`unswept-decision-constants`): the share of 16x16 luma blocks with at
9734 /// most N distinct colours, per gate clip, at the size the gate codes.
9735 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
9736 #[test]
9737 #[ignore = "reads the real library"]
9738 fn probe_screen_detect() {
9739 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
9740 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
9741 for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] {
9742 let path = fixtures.join("video").join(name);
9743 if path.exists() {
9744 clips.push((name.to_string(), path));
9745 }
9746 }
9747 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
9748 && let Some(p) = manifest
9749 .lines()
9750 .skip(1)
9751 .filter_map(|l| l.split('\t').next())
9752 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
9753 {
9754 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
9755 }
9756 let (width, height) = (640usize, 384usize);
9757 for (name, path) in &clips {
9758 let frames = clip_frames(path.to_str().unwrap(), "0", width, height, 4);
9759 for (f, picture) in frames.iter().enumerate() {
9760 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
9761 let mut hist = [0usize; 257];
9762 let mut blocks = 0usize;
9763 for by in (0..height).step_by(16) {
9764 for bx in (0..width).step_by(16) {
9765 let mut seen = [false; 256];
9766 let mut colors = 0usize;
9767 for row in 0..16 {
9768 for col in 0..16 {
9769 let v = usize::from(y[(by + row) * width + bx + col]);
9770 if !seen[v] {
9771 seen[v] = true;
9772 colors += 1;
9773 }
9774 }
9775 }
9776 hist[colors] += 1;
9777 blocks += 1;
9778 }
9779 }
9780 let share = |limit: usize| {
9781 100.0 * hist[2..=limit.min(256)].iter().sum::<usize>() as f64
9782 / blocks.max(1) as f64
9783 };
9784 eprintln!(
9785 "{name} frame {f}: <=4 {:.1}% <=8 {:.1}% <=16 {:.1}% <=32 {:.1}% <=64 {:.1}% <=128 {:.1}%",
9786 share(4),
9787 share(8),
9788 share(16),
9789 share(32),
9790 share(64),
9791 share(128),
9792 );
9793 }
9794 }
9795 }
9796
9797 /// The missing instrument: what this encoder costs against libaom and
9798 /// rav1e at matched fidelity, and how long it takes to get there.
9799 ///
9800 /// Recipe, identical on all three sides: 12 consecutive frames of each
9801 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
9802 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
9803 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
9804 /// it by default), 4:2:0 8-bit in and out. Reference points:
9805 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
9806 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
9807 /// tile_cols=1:tile_rows=1:threads=1`
9808 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
9809 /// ffmpeg-decoded frames of each encoder's own stream.
9810 ///
9811 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
9812 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
9813 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
9814 /// four encodes of that ladder together):
9815 ///
9816 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
9817 /// |---|---|---|---|---|
9818 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
9819 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
9820 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
9821 ///
9822 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
9823 /// the encoder takes -- every stream it writes is byte-identical, so the
9824 /// BD columns are this box's own re-run of the same recipe rather than a
9825 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
9826 /// rav1e). What moved is the wall of the four encodes:
9827 ///
9828 /// | clip | wall ours before | after | instructions:u before -> after |
9829 /// |---|---|---|---|
9830 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
9831 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
9832 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
9833 ///
9834 /// Three exact steps, none of which touches a coded bit: the coefficient
9835 /// rate pricer stopped rebuilding every CDF table per candidate
9836 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
9837 /// tile once per candidate (`decode::FilterReplay`), and the forward
9838 /// transform stopped transforming the all-zero residual that 70% of its
9839 /// calls carry.
9840 ///
9841 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
9842 ///
9843 /// | step | 1080p | 2160p | screen |
9844 /// |---|---|---|---|
9845 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
9846 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
9847 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
9848 ///
9849 /// Loop restoration is NOT in yet: it is the one filter whose parameters
9850 /// are per restoration UNIT inside the tile payload, so it needs both
9851 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
9852 /// buffer to solve against -- neither of which this frame-header-level
9853 /// search reaches.
9854 ///
9855 /// The baseline it replaced, before an inter frame's blocks chose their
9856 /// own partition, was +501.4/+504.4/+440.9 against libaom and
9857 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
9858 ///
9859 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
9860 /// fidelity, while spending far more time than either (the partition
9861 /// search's own cost, uncut: see the two intra-pruning variants measured
9862 /// and rejected in the lane report). No
9863 /// threshold is asserted yet -- this run sets the baseline; the gate
9864 /// asserts four monotone points per ladder, and at EVERY ladder point of
9865 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
9866 /// `crate::stream::decode_stream` -- and asserts the encoder's
9867 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
9868 /// and V over every shown frame in display order. A failure names the
9869 /// clip, the q, the frame, the plane and the first differing sample.
9870 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
9871 /// which exposes no per-packet reconstruction, so that path asserts the
9872 /// two decoders against each other on all three planes.)
9873 ///
9874 /// Run:
9875 /// cargo test -p ec-av1 --release --lib -- --ignored \
9876 /// bd_rate_vs_libaom_and_rav1e --nocapture
9877 #[test]
9878 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
9879 fn bd_rate_vs_libaom_and_rav1e() {
9880 if !have_ffmpeg() {
9881 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
9882 return;
9883 }
9884 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
9885 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
9886 for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] {
9887 let path = fixtures.join("video").join(name);
9888 if path.exists() {
9889 clips.push((name.to_string(), path));
9890 } else {
9891 eprintln!("SKIP clip {name}: missing");
9892 }
9893 }
9894 // Screen capture: the repo carries no screen-capture fixture, so take
9895 // the first OBS recording the real-library manifest names.
9896 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
9897 Ok(manifest) => {
9898 let screen = manifest
9899 .lines()
9900 .skip(1)
9901 .filter_map(|l| l.split('\t').next())
9902 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists());
9903 match screen {
9904 Some(p) => clips.push((
9905 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
9906 std::path::PathBuf::from(p),
9907 )),
9908 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
9909 }
9910 }
9911 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
9912 }
9913 assert!(!clips.is_empty(), "no source clip available");
9914
9915 let (width, height, frames) = (640usize, 384usize, 12usize);
9916 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
9917 .iter()
9918 .map(|q| {
9919 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
9920 .map(String::from)
9921 .to_vec()
9922 })
9923 .collect();
9924 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
9925 .iter()
9926 .map(|q| {
9927 vec![
9928 "-rav1e-params".to_string(),
9929 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
9930 ]
9931 })
9932 .collect();
9933 println!(
9934 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
9935 );
9936 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |");
9937 println!("|---|---|---|---|---|");
9938 for (name, path) in &clips {
9939 let fctx = &crate::decode::FrameCtx::new();
9940 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
9941 let _ = take_partition_hits();
9942 let _ = crate::tile::take_palette_hits();
9943 SCREEN_FRAMES.iter().for_each(|c| {
9944 c.store(0, std::sync::atomic::Ordering::Relaxed);
9945 });
9946 let _ = take_uv_mode_hits();
9947 let _ = crate::tile::take_inter_mode_hits();
9948 let _ = crate::tile::take_drl_hits();
9949 let _ = crate::tile::take_ref_hits();
9950 let _ = crate::tile::take_compound_mode_hits();
9951 let _ = crate::tile::take_compound_pair_hits();
9952 let _ = crate::tile::take_compound_size_hits();
9953 let _ = crate::motion::take_census();
9954 let (ours, ours_wall) = match pyramid_from_env() {
9955 None => our_ladder(name, &source, width, height, fctx),
9956 Some(pyramid) => {
9957 let (ladder, wall, counts, bytes) =
9958 our_ladder_pyramid(name, &source, width, height, pyramid);
9959 eprintln!(
9960 "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \
9961 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
9962 counts[0], counts[1], counts[2], counts[3],
9963 bytes[0], bytes[1], bytes[2], bytes[3],
9964 );
9965 (ladder, wall)
9966 }
9967 };
9968 // How often the inter split actually fired over this clip's four
9969 // encodes, against the whole 32x32 that was the only outcome
9970 // before (gate-blind-to-feature).
9971 let [whole32, split32, whole16, split16] = take_partition_hits();
9972 // Which inter modes actually fired over this clip's four encodes,
9973 // and at which DRL index -- a mode nobody picks is a mode the BD
9974 // number cannot be crediting (gate-blind-to-feature).
9975 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
9976 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
9977 let refs = crate::tile::take_ref_hits();
9978 let modes_total = (nearest + near + global + new).max(1);
9979 eprintln!(
9980 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
9981 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
9982 {drl0}/{drl1}/{drl2}/{drl3}",
9983 100.0 * nearest as f64 / modes_total as f64,
9984 100.0 * near as f64 / modes_total as f64,
9985 100.0 * global as f64 / modes_total as f64,
9986 100.0 * new as f64 / modes_total as f64,
9987 );
9988 // The compound census: what share of the coded inter blocks took
9989 // a compound reference at all, which compound mode they took, and
9990 // which pair (gate-blind-to-feature -- a compound mode nobody
9991 // picks cannot be what a BD number credits).
9992 let comp_modes = crate::tile::take_compound_mode_hits();
9993 let comp_pairs = crate::tile::take_compound_pair_hits();
9994 let comp_sizes = crate::tile::take_compound_size_hits();
9995 let comp_total: usize = comp_modes.iter().sum();
9996 eprintln!(
9997 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
9998 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
9999 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
10000 modes_total + comp_total,
10001 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
10002 comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3],
10003 comp_modes[6], comp_modes[7],
10004 comp_pairs[3], comp_pairs[6],
10005 );
10006 eprintln!(
10007 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
10008 comp_sizes[1], comp_sizes[2], comp_sizes[3],
10009 );
10010 // Where the wall-owning stage actually goes: how many candidate
10011 // evaluations (one `mc::predict` + SAD each) a search spends, how
10012 // many of them are subpel, and how often the winner is the seed
10013 // it started from -- the census the seeded search is judged by.
10014 let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census();
10015 let per = |n: u64| n as f64 / calls.max(1) as f64;
10016 eprintln!(
10017 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
10018 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
10019 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
10020 per(evals),
10021 100.0 * subpel as f64 / evals.max(1) as f64,
10022 per(rounds),
10023 100.0 * near_pred as f64 / calls.max(1) as f64,
10024 100.0 * unmoved as f64 / calls.max(1) as f64,
10025 );
10026 eprintln!(
10027 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
10028 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
10029 );
10030 eprintln!(
10031 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
10032 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
10033 whole32 + split32,
10034 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
10035 whole16 + split16,
10036 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
10037 );
10038 // The deblocking level each of this clip's frames chose
10039 // (lane-av1filt): 0 everywhere would mean the filter never fires.
10040 let levels = crate::filter_search::take_chosen_levels();
10041 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
10042 let mean = |f: fn(&Chosen) -> u8| {
10043 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
10044 };
10045 eprintln!(
10046 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
10047 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
10048 levels.len(),
10049 mean(|l| l.0.0),
10050 mean(|l| l.0.1),
10051 mean(|l| l.1.0),
10052 mean(|l| l.1.1),
10053 mean(|l| l.2.0),
10054 mean(|l| l.2.1),
10055 );
10056 // How many strength presets each frame's CDEF list carried and
10057 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
10058 // everywhere would mean the per-unit choice never fires.
10059 let presets = crate::filter_search::take_cdef_presets();
10060 let mut by_bits = [0usize; 4];
10061 for (b, _) in &presets {
10062 by_bits[usize::from(*b)] += 1;
10063 }
10064 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
10065 let on_extra: usize = presets
10066 .iter()
10067 .flat_map(|(_, c)| c.iter().skip(1))
10068 .sum();
10069 eprintln!(
10070 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
10071 on a non-default preset ({:.1}%)",
10072 by_bits[0],
10073 by_bits[1],
10074 by_bits[2],
10075 by_bits[3],
10076 on_extra,
10077 units,
10078 100.0 * on_extra as f64 / units.max(1) as f64
10079 );
10080 // How the 64x64 luma restoration units split between
10081 // RESTORE_NONE and Wiener (lane-av1lr).
10082 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
10083 eprintln!(
10084 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
10085 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
10086 );
10087 // Which chroma modes the search actually wins with, against the
10088 // unconditional DC_PRED that was the only outcome before
10089 // (gate-blind-to-feature).
10090 // Screen-content detection and the palette it turns on
10091 // (gate-blind-to-feature): how many frames set
10092 // `allow_screen_content_tools`, how many blocks took a palette,
10093 // and of what size. A film clip must print `screen frames on=0`.
10094 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
10095 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
10096 let palette = crate::tile::take_palette_hits();
10097 eprintln!(
10098 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
10099 palette[0],
10100 (2..=8)
10101 .filter(|&n| palette[n] > 0)
10102 .map(|n| format!("{n}={}", palette[n]))
10103 .collect::<Vec<_>>()
10104 .join(" ")
10105 );
10106 let palette_uv = crate::tile::take_palette_uv_hits();
10107 eprintln!(
10108 "{name}: chroma palette blocks {} sizes {}",
10109 palette_uv[0],
10110 (2..=8)
10111 .filter(|&n| palette_uv[n] > 0)
10112 .map(|n| format!("{n}={}", palette_uv[n]))
10113 .collect::<Vec<_>>()
10114 .join(" ")
10115 );
10116 let uv = take_uv_mode_hits();
10117 let uv_total: usize = uv.iter().sum();
10118 eprintln!(
10119 "{name}: uv modes {}",
10120 uv.iter()
10121 .enumerate()
10122 .filter(|&(_, &n)| n > 0)
10123 .map(|(m, &n)| format!(
10124 "{}={n} ({:.1}%)",
10125 UV_MODE_NAMES[m],
10126 100.0 * n as f64 / uv_total.max(1) as f64
10127 ))
10128 .collect::<Vec<_>>()
10129 .join(" ")
10130 );
10131 // Which transform depth the intra blocks of this clip's key
10132 // frames resolved to (lane-av1tx): depth 0 is one transform over
10133 // the whole block, 1 and 2 its halvings.
10134 let depths = take_tx_depth_hits();
10135 let depth_total: usize = depths.iter().sum();
10136 eprintln!(
10137 "{name}: intra tx depths {}",
10138 depths
10139 .iter()
10140 .enumerate()
10141 .map(|(d, &n)| format!(
10142 "{d}={n} ({:.1}%)",
10143 100.0 * n as f64 / depth_total.max(1) as f64
10144 ))
10145 .collect::<Vec<_>>()
10146 .join(" ")
10147 );
10148 // And which var-tx depth this clip's INTER blocks resolved to
10149 // (lane-av1tx2): 0 is one transform over the whole block, 1 its
10150 // four halves.
10151 let splits = take_inter_tx_split_hits();
10152 let split_total: usize = splits.iter().sum();
10153 eprintln!(
10154 "{name}: inter var-tx depths {}",
10155 splits
10156 .iter()
10157 .enumerate()
10158 .map(|(d, &n)| format!(
10159 "{d}={n} ({:.1}%)",
10160 100.0 * n as f64 / split_total.max(1) as f64
10161 ))
10162 .collect::<Vec<_>>()
10163 .join(" ")
10164 );
10165 let (aom, aom_wall) =
10166 external_ladder(&source, width, height, "libaom-av1", &aom_points);
10167 let (rav1e, rav1e_wall) =
10168 external_ladder(&source, width, height, "librav1e", &rav1e_points);
10169 assert_monotone(&format!("{name}: ours"), &ours);
10170 assert_monotone(&format!("{name}: libaom"), &aom);
10171 assert_monotone(&format!("{name}: rav1e"), &rav1e);
10172 let points = ours
10173 .iter()
10174 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
10175 .collect::<Vec<_>>()
10176 .join(", ");
10177 println!(
10178 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
10179 bd_rate(&aom, &ours) * 100.0,
10180 bd_rate(&rav1e, &ours) * 100.0,
10181 );
10182 println!(
10183 "| references | libaom {} | rav1e {} | | |",
10184 aom.iter()
10185 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
10186 .collect::<Vec<_>>()
10187 .join(", "),
10188 rav1e
10189 .iter()
10190 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
10191 .collect::<Vec<_>>()
10192 .join(", "),
10193 );
10194 }
10195 }
10196}