forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

encode.rs10697 lines, 468.2 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/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
194/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
195/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
196/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
197/// was missing was the encoder ever forming one below 32x32.
198const LEAF_COMPOUND: bool = true;
199
200/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
201fn leaf_compound() -> bool {
202 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
203 Some(v) => v != "0",
204 None => LEAF_COMPOUND,
205 }
206}
207
208/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
209fn leaf_new_mv() -> bool {
210 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
211 Some(v) if cfg!(test) => v != "0",
212 _ => LEAF_NEW_MV,
213 }
214}
215
216/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
217/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
218/// the true frame edge cut through was ever split there; inside the frame
219/// every block was coded whole, which left the partition decision the key
220/// frame already makes unmade for eleven frames out of twelve.
221const SPLIT_INTER_BLOCKS: bool = true;
222
223/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
224/// measurement that keeps it is running (test builds only, like
225/// [`lambda_scale`]).
226fn split_inter_blocks() -> bool {
227 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
228 Some(v) if cfg!(test) => v != "0",
229 _ => SPLIT_INTER_BLOCKS,
230 }
231}
232
233/// Whether the encoder searches loop restoration at all (spec 7.17): one
234/// Wiener filter per 64x64 luma restoration unit, picked from
235/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
236/// test build, like [`lambda_scale`].
237const RESTORATION: bool = true;
238
239/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
240fn restoration_enabled() -> bool {
241 match std::env::var("EC_AV1_LR").ok() {
242 Some(v) if cfg!(test) => v != "0",
243 _ => RESTORATION,
244 }
245}
246
247/// libaom's `partition_search_breakout` shape: how many non-zero luma
248/// coefficients per 256 luma samples a block may code and still be judged
249/// well enough predicted that the split below it is not worth trying. `0`
250/// disables the breakout (only the existing all-skip prune applies), which
251/// is the default until the sweep below justifies otherwise.
252///
253/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
254/// is where this lane's wall would have gone: 1 cuts the three clips'
255/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
256/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
257/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
258/// encoder's inter quality lives, so `0` ships and the knob stays for a
259/// future explicit speed preset.
260const SPLIT_BREAKOUT_COEFFS: usize = 0;
261
262/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
263/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
264/// out under `threshold * lambda` is not offered the split at all, and a
265/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
266/// always, as before this lever.
267///
268/// The census is what points here: the split trial runs on nearly every
269/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
270/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
271/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
272/// points, so the gate has to read the block's own RD cost, not its levels.
273///
274/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
275/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
276/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
277/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
278/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
279/// the largest threshold whose BD stays inside the +0.3 keep rule on every
280/// clip.
281const SPLIT_RD_THRESHOLD: f64 = 0.125;
282
283/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
284fn split_rd_threshold() -> f64 {
285 static T: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
286 *T.get_or_init(|| {
287 std::env::var("EC_AV1_SPLIT_RD")
288 .ok()
289 .and_then(|v| v.parse().ok())
290 .unwrap_or(SPLIT_RD_THRESHOLD)
291 })
292}
293
294/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
295/// [`split_rd_threshold`] withholds the split trial.
296fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
297 let t = split_rd_threshold();
298 t > 0.0 && cost < t * lambda * (side * side) as f64
299}
300
301/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
302/// build.
303fn split_breakout_coeffs() -> usize {
304 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
305 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
306 _ => SPLIT_BREAKOUT_COEFFS,
307 }
308}
309
310/// How often each partition decision was taken since the last
311/// [`take_partition_hits`], so a gate can report how often a new partition
312/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
313/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
314/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
315static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
316 std::sync::atomic::AtomicUsize::new(0),
317 std::sync::atomic::AtomicUsize::new(0),
318 std::sync::atomic::AtomicUsize::new(0),
319 std::sync::atomic::AtomicUsize::new(0),
320];
321
322/// Records one such decision.
323fn partition_hit(which: usize) {
324 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
325}
326
327/// Takes (and clears) the counts.
328#[cfg(test)]
329pub(crate) fn take_partition_hits() -> [usize; 4] {
330 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
331}
332
333/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
334/// rate-distortion trials the block search actually runs, by kind, and where
335/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
336/// default, and a measurement build rather than a speed one -- the census
337/// runs the SAD pre-pass the unpruned search otherwise skips.
338pub fn census_on() -> bool {
339 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
340 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
341}
342
343/// What each [`CENSUS`] counter counts.
344pub const CENSUS_KINDS: [&str; 11] = [
345 "intra blocks searched (key frame + inter leaves)",
346 "intra luma mode trials",
347 "chroma searches",
348 "chroma mode trials (each = 2 plane trials)",
349 "tx-depth trials (transform units, depth >= 1)",
350 "inter 32x32 blocks searched",
351 "inter block intra-mode trials",
352 "inter mv candidates (each = 3 mc trials)",
353 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
354 " of those, intra won",
355 " of those, the NEARESTMV trial coded no residual",
356];
357
358/// The census counters themselves, indexed by [`CENSUS_KINDS`].
359static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
360 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
361
362/// Where the RD winner sat in the SAD ranking, for the luma intra search and
363/// the chroma mode search -- what says whether a top-N prune would have kept
364/// the block the search actually chose.
365static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
366 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
367static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
368 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
369
370fn census_add(kind: usize, n: usize) {
371 if census_on() {
372 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
373 }
374}
375
376/// Reads (and clears) the census, so a driver can attribute it to its own encode.
377pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
378 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
379 (
380 std::array::from_fn(|i| take(&CENSUS[i])),
381 std::array::from_fn(|i| take(&LUMA_RANK[i])),
382 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
383 )
384}
385
386/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
387/// first -- the census's one shared rule, so the luma and chroma histograms
388/// mean the same thing.
389fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
390 scored
391 .iter()
392 .filter(|&&(score, mode)| {
393 mode != winner
394 && score
395 < scored
396 .iter()
397 .find(|&&(_, m)| m == winner)
398 .map_or(f64::INFINITY, |&(s, _)| s)
399 })
400 .count()
401}
402
403/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
404/// four cost less. Set from the measurement in the lane report.
405const SPLIT_BLOCKS: bool = true;
406
407/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
408/// by calling [`encode_key_frame_inner`] both ways.
409pub(crate) fn split_blocks() -> bool {
410 SPLIT_BLOCKS
411}
412
413/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
414/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
415/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
416/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
417/// stream's decode output actually carries 10-bit precision instead of
418/// silently losing its low 2 bits). The encoder only ever produces values in
419/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
420/// decision); `Plane::source` narrows right back to `u8` at its two
421/// construction sites, a lossless round trip for that range.
422#[derive(Clone, Debug, PartialEq, Eq)]
423pub struct Picture {
424 /// The picture's width in luma samples.
425 pub width: usize,
426 /// Its height in luma samples.
427 pub height: usize,
428 /// The luma plane, `width * height` samples in raster order.
429 pub y: Vec<u16>,
430 /// The U plane, at half the width and half the height.
431 pub u: Vec<u16>,
432 /// The V plane, the same shape as U.
433 pub v: Vec<u16>,
434}
435
436impl Picture {
437 /// A mid-grey picture of the given size.
438 #[must_use]
439 pub fn grey(width: usize, height: usize) -> Self {
440 Self {
441 width,
442 height,
443 y: vec![128; width * height],
444 u: vec![128; width * height / 4],
445 v: vec![128; width * height / 4],
446 }
447 }
448
449 pub(crate) fn check(&self) -> Result<()> {
450 if self.width == 0
451 || !self.width.is_multiple_of(BLOCK)
452 || !self.height.is_multiple_of(BLOCK)
453 || !self.height.is_multiple_of(BLOCK)
454 {
455 return Err(Error::unsupported(
456 "AV1 encode",
457 "the picture must be a whole number of 32x32 blocks in each direction",
458 ));
459 }
460 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
461 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
462 return Err(Error::unsupported(
463 "AV1 encode",
464 "each plane must carry one sample per position at 4:2:0",
465 ));
466 }
467 Ok(())
468 }
469
470 /// What the public entry points require of the picture they are handed,
471 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
472 /// needs a whole chroma sample per two luma ones) and one sample per
473 /// position on each plane.
474 pub(crate) fn check_even(&self) -> Result<()> {
475 if self.width == 0
476 || self.height == 0
477 || !self.width.is_multiple_of(2)
478 || !self.height.is_multiple_of(2)
479 {
480 return Err(Error::unsupported(
481 "AV1 encode",
482 "the picture's width and height must each be even and nonzero",
483 ));
484 }
485 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
486 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
487 return Err(Error::unsupported(
488 "AV1 encode",
489 "each plane must carry one sample per position at 4:2:0",
490 ));
491 }
492 Ok(())
493 }
494
495 /// This picture, padded by edge replication to the next whole number of
496 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
497 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
498 /// sequence (what the inter tile writer's partition needs on top of
499 /// that). Identity (a plain clone, not a copy through the replication
500 /// loop) when the picture is already that size — the multiple-of-32 (or
501 /// -64) fast path is unchanged.
502 pub(crate) fn padded_to(&self, align: usize) -> Picture {
503 let padded_width = self.width.next_multiple_of(align);
504 let padded_height = self.height.next_multiple_of(align);
505 if padded_width == self.width && padded_height == self.height {
506 return self.clone();
507 }
508 Picture {
509 width: padded_width,
510 height: padded_height,
511 y: pad_plane(
512 &self.y,
513 self.width,
514 self.height,
515 padded_width,
516 padded_height,
517 ),
518 u: pad_plane(
519 &self.u,
520 self.width / 2,
521 self.height / 2,
522 padded_width / 2,
523 padded_height / 2,
524 ),
525 v: pad_plane(
526 &self.v,
527 self.width / 2,
528 self.height / 2,
529 padded_width / 2,
530 padded_height / 2,
531 ),
532 }
533 }
534}
535
536/// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8`
537/// (8-bit only, unchanged this round -- widening the encoder is out of this
538/// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that
539/// lets it keep calling [`crate::intra::predict`] now that shape is `u16`
540/// in and out. A block-sized round-trip through `u16` is exact for 8-bit
541/// content (every value fits both ways), so this changes no encoder output.
542#[allow(clippy::too_many_arguments)]
543fn intra_predict_u8(
544 mode: u8,
545 angle_delta: i32,
546 above: Option<&[u8]>,
547 left: Option<&[u8]>,
548 corner: Option<u8>,
549 bw: usize,
550 bh: usize,
551 enable_edge_filter: bool,
552 smooth_neighbor: bool,
553 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
554) {
555 let above16: Option<Vec<u16>> = above.map(|s| s.iter().map(|&v| u16::from(v)).collect());
556 let left16: Option<Vec<u16>> = left.map(|s| s.iter().map(|&v| u16::from(v)).collect());
557 let mut dst16 = vec![0u16; dst.len()];
558 crate::intra::predict(
559 mode,
560 angle_delta,
561 above16.as_deref(),
562 left16.as_deref(),
563 corner.map(u16::from),
564 bw,
565 bh,
566 enable_edge_filter,
567 smooth_neighbor,
568 &mut dst16, fctx,
569 );
570 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
571 *d = s as u8;
572 }
573}
574
575/// Pads one plane to `(padded_width, padded_height)` by repeating its last
576/// row and column, so the block coder always sees a whole number of blocks.
577/// [`crop_plane`] undoes this on the way back out.
578fn pad_plane<T: Copy + Default>(
579 source: &[T],
580 width: usize,
581 height: usize,
582 padded_width: usize,
583 padded_height: usize,
584) -> Vec<T> {
585 let mut out = vec![T::default(); padded_width * padded_height];
586 for row in 0..padded_height {
587 let src = source[row.min(height - 1) * width..][..width].as_ref();
588 let dst = &mut out[row * padded_width..][..padded_width];
589 dst[..width].copy_from_slice(src);
590 dst[width..].fill(src[width - 1]);
591 }
592 out
593}
594
595/// The top-left `width` x `height` region of a plane that is `padded_width`
596/// wide, which is the render-size crop [`Picture::padded`]'s replication
597/// exists to let a decoder undo.
598fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
599 let mut out = Vec::with_capacity(width * height);
600 for row in 0..height {
601 out.extend_from_slice(&source[row * padded_width..][..width]);
602 }
603 out
604}
605
606/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
607/// region a decoder produces, which is the public contract for what a caller
608/// sees back — the padded planes the encoder coded against never leave this
609/// module. Identity when the reconstruction is already that size.
610pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
611 let reconstruction = &encoded.reconstruction;
612 let cropped = if reconstruction.width == width && reconstruction.height == height {
613 reconstruction.clone()
614 } else {
615 Picture {
616 width,
617 height,
618 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
619 u: crop_plane(
620 &reconstruction.u,
621 reconstruction.width / 2,
622 width / 2,
623 height / 2,
624 ),
625 v: crop_plane(
626 &reconstruction.v,
627 reconstruction.width / 2,
628 width / 2,
629 height / 2,
630 ),
631 }
632 };
633 Encoded {
634 stream: encoded.stream.clone(),
635 modes: encoded.modes.clone(),
636 inter_block_share: encoded.inter_block_share,
637 reconstruction: cropped,
638 tile: encoded.tile.clone(),
639 mi_cols: encoded.mi_cols,
640 mi_rows: encoded.mi_rows,
641 base_q_idx: encoded.base_q_idx,
642 tx_select: encoded.tx_select,
643 screen: encoded.screen,
644 start_cdfs: encoded.start_cdfs.clone(),
645 next_cdfs: encoded.next_cdfs.clone(),
646 loop_filter: encoded.loop_filter,
647 loop_restoration: encoded.loop_restoration,
648 allow_intrabc: encoded.allow_intrabc,
649 cdef: encoded.cdef,
650 }
651}
652
653/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
654/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
655#[derive(Clone)]
656pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
657
658impl std::fmt::Debug for CdfSnapshot {
659 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
660 f.write_str("CdfSnapshot")
661 }
662}
663
664/// What one call to [`encode_key_frame`] produced.
665#[derive(Clone, Debug)]
666pub struct Encoded {
667 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
668 /// OBU carrying one tile.
669 pub stream: Vec<u8>,
670 /// What a decoder will produce from `stream` — the encoder's own
671 /// reconstruction, which its prediction was built on.
672 pub reconstruction: Picture,
673 /// The luma intra mode each block was coded under, in the order the blocks
674 /// are coded — raster order among the quadrants of each superblock, and
675 /// among the four 16x16 blocks of a quadrant that was split.
676 pub modes: Vec<u8>,
677 /// The fraction of this frame's 32x32 blocks that were coded inter (any
678 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
679 /// for a key frame, which has no such choice — so a caller can tell a
680 /// frame with no motion worth coding from one that never got the chance.
681 pub inter_block_share: f64,
682 /// The tile payload alone, undecorated by any OBU framing, and the frame
683 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
684 /// `crate::decode`'s tests are the only reader; a real decoder gets these
685 /// off the wire by parsing `stream`'s OBUs instead.
686 pub(crate) tile: Vec<u8>,
687 pub(crate) mi_cols: u32,
688 pub(crate) mi_rows: u32,
689 pub(crate) base_q_idx: u8,
690 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
691 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
692 /// and reading it off `stream`'s header is what `decode_stream` does. A
693 /// test that decodes `tile` directly must pass this one along, or it reads
694 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
695 /// block.
696 pub(crate) tx_select: bool,
697 /// The CDF state this frame's tile writer started from -- the defaults
698 /// for a key frame and for the first inter frame, and the previous
699 /// frame's stored tables after that. A test that decodes `tile` directly
700 /// must feed the decoder this, exactly as `decode_stream` feeds it what
701 /// the frame's `primary_ref_frame` slot holds (same class as
702 /// `tx_select`: a header bit a raw tile decode cannot guess).
703 pub(crate) start_cdfs: CdfSnapshot,
704 /// What this frame stores into the slots it refreshes (spec 7.20,
705 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
706 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
707 /// started from when it is on.
708 pub(crate) next_cdfs: CdfSnapshot,
709 /// This frame header's chosen deblocking parameters
710 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
711 /// picture the decoder produces UNDER them, so a test that decodes
712 /// `tile` directly must pass these along, exactly as it must `tx_select`
713 /// (class: test asserts against a stale header).
714 pub(crate) loop_filter: LoopFilterParams,
715 /// This frame header's chosen CDEF parameters, threaded for the same
716 /// reason as `loop_filter`.
717 pub(crate) cdef: CdefParams,
718 /// This frame header's `allow_screen_content_tools`
719 /// ([`screen_content`]) -- every intra block of the tile carries the two
720 /// palette-mode symbols under it, so a raw tile decode that guessed
721 /// `false` would desync at the first block (same class as `tx_select`).
722 pub(crate) screen: bool,
723 /// This frame header's chosen loop restoration parameters, threaded for
724 /// the same reason as `loop_filter` -- and doubly so: the per-unit
725 /// filters themselves are coded in `tile`, so a decode of it under a
726 /// stale `RESTORE_NONE` header desyncs at the first superblock.
727 pub(crate) loop_restoration: LoopRestorationParams,
728 /// This frame header's `allow_intrabc` -- every intra block of the tile
729 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
730 /// guessed `false` would desync at the first block (same class as
731 /// `screen`/`tx_select`).
732 pub(crate) allow_intrabc: bool,
733}
734
735thread_local! {
736 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
737 /// for on the last key frame encoded on this thread -- read by the gates,
738 /// which print it beside the block counts (class `gate-blind-to-feature`).
739 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
740}
741
742/// [`IBC_SHARE`] for the last key frame encoded on this thread.
743#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
744pub(crate) fn intrabc_source_share() -> f64 {
745 IBC_SHARE.with(std::cell::Cell::get)
746}
747
748thread_local! {
749 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
750 /// header offers the per-frame `allow_screen_content_tools` bit at all.
751 /// Armed once by the key frame ([`encode_key_frame_inner`], from
752 /// [`screen_content`]) and read by every header builder after it, so that
753 /// the inter frames of a screen sequence lay their headers out the same
754 /// way the sequence header the key frame wrote says they do -- a per-call
755 /// parameter would have to thread through `inter_frame_headers`' four
756 /// public entry points and every hand-built-stream test that calls them.
757 /// A sequence with no screen content leaves this false and writes exactly
758 /// the bits it wrote before this lane.
759 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
760}
761
762thread_local! {
763 /// Overrides [`screen_content`] for the calling thread, which is what the
764 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
765 /// codes every block losslessly, so both arms of a mode ablation reach
766 /// infinite PSNR and the ablation measures nothing at all (the
767 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
768 /// variable cannot do this -- the tests run in one process, in parallel.
769 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
770}
771
772#[cfg(test)]
773pub(crate) fn force_screen(value: Option<bool>) {
774 SCREEN_FORCE.with(|c| c.set(value));
775}
776
777pub(crate) fn arm_seq_screen(on: bool) {
778 SEQ_SCREEN.with(|c| c.set(on));
779}
780
781fn seq_screen() -> bool {
782 SEQ_SCREEN.with(std::cell::Cell::get)
783}
784
785/// How many distinct colours a 16x16 luma block may hold and still count as
786/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
787/// `av1_set_screen_content_options` bound is 4, which separates NOTHING on a
788/// real (lossily coded, so noisy) desktop capture: `probe_screen_detect`
789/// measures the share of 16x16 blocks under each bound on the gate's own
790/// three clips, and only at 32 do the populations part -- film 20.3..21.9%,
791/// his OBS capture 51.1..51.5%.
792fn screen_colors() -> usize {
793 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
794 *N.get_or_init(|| {
795 std::env::var("EC_AV1_SCREEN_COLORS")
796 .ok()
797 .and_then(|v| v.parse().ok())
798 .unwrap_or(32)
799 })
800}
801
802/// The reciprocal of the frame area those blocks must cover, in tenths --
803/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is 10 (one
804/// tenth). 3 (a third) is the midpoint of the two populations
805/// `probe_screen_detect` measured at the colour bound above.
806/// `EC_AV1_SCREEN_PCT`.
807fn screen_pct() -> usize {
808 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
809 *N.get_or_init(|| {
810 std::env::var("EC_AV1_SCREEN_PCT")
811 .ok()
812 .and_then(|v| v.parse().ok())
813 .unwrap_or(3)
814 })
815}
816
817/// How many frames [`screen_content`] said yes/no to, so a gate can print
818/// whether the detector fired at all (class `gate-blind-to-feature`).
819pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
820 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
821
822/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
823/// the distinct colours of every 16x16 block and turn the screen-content
824/// tools on when the blocks holding between 2 and [`screen_colors`] of them
825/// cover more than a [`screen_pct`]th of the frame. `width` is the plane's
826/// stride, `true_*` the frame's real (decodable) extent.
827fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
828 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
829 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
830 return forced;
831 }
832 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
833 let on = v != "0";
834 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
835 return on;
836 }
837 let (blk, limit) = (16usize, screen_colors());
838 let mut counted = 0usize;
839 for by in (0..true_height).step_by(blk) {
840 for bx in (0..true_width).step_by(blk) {
841 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
842 let mut seen = [false; 256];
843 let mut colors = 0usize;
844 for row in 0..h {
845 for col in 0..w {
846 let v = usize::from(y[(by + row) * width + bx + col]);
847 if !seen[v] {
848 seen[v] = true;
849 colors += 1;
850 }
851 }
852 }
853 if colors > 1 && colors <= limit {
854 counted += 1;
855 }
856 }
857 }
858 let on = counted * blk * blk * screen_pct() > true_width * true_height;
859 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
860 on
861}
862
863/// The sequence and frame headers a picture of this size is coded under: one
864/// tile, one transform size per block, no in-loop filter parameters yet
865/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
866/// CDEF strengths in once the tile is coded), no CDF adaptation
867/// and no tool the tile writer does not code.
868///
869/// # Errors
870/// Returns an error when the picture is larger than the 16-bit frame size the
871/// sequence header carries.
872pub fn key_frame_headers(
873 width: usize,
874 height: usize,
875 base_q_idx: u8,
876) -> Result<(SequenceHeader, FrameHeader)> {
877 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
878}
879
880/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
881/// studio (limited) range: what this crate's sequence header carried before
882/// [`crate::encoder`]'s facade could configure it, and what
883/// [`key_frame_headers`] still asks for.
884fn unspecified_color_config() -> ColorConfig {
885 ColorConfig {
886 bit_depth: 8,
887 mono_chrome: false,
888 num_planes: 3,
889 color_primaries: 2,
890 transfer_characteristics: 2,
891 matrix_coefficients: 2,
892 color_range: false,
893 subsampling_x: 1,
894 subsampling_y: 1,
895 chroma_sample_position: ChromaSamplePosition::Unknown,
896 separate_uv_delta_q: false,
897 }
898}
899
900/// [`key_frame_headers`] with the sequence header's colour config named
901/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
902/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
903/// which is all a player picks a colour transform from and which
904/// [`crate::encoder::Colour`] is the facade's own name for.
905///
906/// # Errors
907/// The same as [`key_frame_headers`].
908pub(crate) fn key_frame_headers_colour(
909 width: usize,
910 height: usize,
911 base_q_idx: u8,
912 color_config: ColorConfig,
913) -> Result<(SequenceHeader, FrameHeader)> {
914 let bits = |n: usize| -> Result<u32> {
915 let n = u32::try_from(n).map_err(|_| too_large())?;
916 if n == 0 || n > 1 << 16 {
917 return Err(too_large());
918 }
919 Ok((32 - (n - 1).leading_zeros()).max(1))
920 };
921 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
922 let (w, h) = (width as u32, height as u32);
923 let seq = SequenceHeader {
924 seq_profile: 0,
925 operating_points: vec![OperatingPoint {
926 seq_level_idx: 8,
927 ..OperatingPoint::default()
928 }],
929 frame_width_bits,
930 frame_height_bits,
931 max_frame_width: w,
932 max_frame_height: h,
933 use_128x128_superblock: false,
934 enable_filter_intra: false,
935 enable_intra_edge_filter: false,
936 enable_order_hint: true,
937 order_hint_bits: 7,
938 enable_superres: false,
939 // spec 5.9.19: with the sequence bit set every frame header carries
940 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
941 // pair for the whole frame, chosen by `crate::filter_search` -- so no
942 // `cdef_idx` literal is coded in the tile and a frame that wants no
943 // CDEF simply carries zero strengths.
944 enable_cdef: true,
945 enable_restoration: true,
946 // SELECT (2) when this sequence's key frame detected screen content
947 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
948 // is then coded in every frame header, and only the frames that want
949 // the palette syntax set it. 0 -- the forced-off form, no bit at all
950 // -- otherwise, which is what every non-screen stream this encoder
951 // writes still carries.
952 seq_force_screen_content_tools: if seq_screen() {
953 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
954 } else {
955 0
956 },
957 seq_force_integer_mv: 0,
958 color_config,
959 still_picture: false,
960 reduced_still_picture_header: false,
961 timing_info: None,
962 decoder_model_info: None,
963 initial_display_delay_present_flag: false,
964 operating_point: 0,
965 operating_point_idc: 0,
966 frame_id_numbers_present_flag: false,
967 delta_frame_id_length: 0,
968 additional_frame_id_length: 0,
969 enable_interintra_compound: false,
970 enable_masked_compound: false,
971 enable_warped_motion: false,
972 enable_dual_filter: false,
973 enable_jnt_comp: false,
974 enable_ref_frame_mvs: false,
975 film_grain_params_present: false,
976 };
977 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
978 // own (true, unpadded) width and height, not from any block-grid
979 // alignment — a decoder derives these straight from `frame_width`/
980 // `frame_height` below, so this must match it exactly.
981 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
982 let header = FrameHeader {
983 frame_type: FrameType::Key,
984 frame_is_intra: true,
985 show_frame: true,
986 error_resilient_mode: true,
987 // The tile writer keeps the same CDF state the decoder does and
988 // updates it in the same order, so the frame lets the decoder adapt.
989 disable_cdf_update: false,
990 // Nothing reads the state this frame leaves behind: a key frame always
991 // starts from the defaults, and this encoder emits one frame.
992 disable_frame_end_update_cdf: true,
993 force_integer_mv: true,
994 refresh_frame_flags: 0xFF,
995 primary_ref_frame: PRIMARY_REF_NONE,
996 frame_width: w,
997 frame_height: h,
998 upscaled_width: w,
999 render_width: w,
1000 render_height: h,
1001 mi_cols,
1002 mi_rows,
1003 tile_info: TileInfo {
1004 uniform_spacing: true,
1005 cols: 1,
1006 rows: 1,
1007 mi_col_starts: vec![0, mi_cols],
1008 mi_row_starts: vec![0, mi_rows],
1009 tile_size_bytes: 1,
1010 ..TileInfo::default()
1011 },
1012 quantization: QuantizationParams {
1013 base_q_idx,
1014 ..QuantizationParams::default()
1015 },
1016 tx_mode: TxMode::Largest,
1017 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
1018 // intra transform below 32x32, not only 16x16 -- the set this crate
1019 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
1020 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
1021 // so a decoder honouring the header picks the same CDF the writer
1022 // used only if this is set here too, not only on the inter variant
1023 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
1024 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
1025 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
1026 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
1027 // the arithmetic coder's `rng` register from the very first 8x8-leaf
1028 // luma transform onward with no symbol value ever differing.
1029 reduced_tx_set: true,
1030 ..FrameHeader::default()
1031 };
1032 Ok((seq, header))
1033}
1034
1035/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
1036/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
1037/// 1 still holds the key frame however long the GOP runs.
1038pub const GOLDEN_SLOT: u8 = 1;
1039
1040/// The frame header for a shown inter frame that predicts from the single
1041/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
1042/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
1043/// reused verbatim: an inter frame never changes the sequence.
1044///
1045/// # Errors
1046/// Returns an error under the same conditions as [`key_frame_headers`].
1047pub fn inter_frame_headers(
1048 width: usize,
1049 height: usize,
1050 base_q_idx: u8,
1051 order_hint: u32,
1052 last_slot: u8,
1053) -> Result<(SequenceHeader, FrameHeader)> {
1054 inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
1055}
1056
1057/// [`inter_frame_headers`] with the three slots named apart: the one read as
1058/// `LAST_FRAME`, the one this frame refreshes, and the one read as
1059/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
1060/// so that the frame two back is still intact in the slot this one is about
1061/// to overwrite -- read before write, spec 7.20's decode order.
1062///
1063/// # Errors
1064/// As [`inter_frame_headers`].
1065pub fn inter_frame_headers_slots(
1066 width: usize,
1067 height: usize,
1068 base_q_idx: u8,
1069 order_hint: u32,
1070 last_slot: u8,
1071 self_slot: u8,
1072 altref_slot: u8,
1073) -> Result<(SequenceHeader, FrameHeader)> {
1074 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
1075 let header = FrameHeader {
1076 frame_type: FrameType::Inter,
1077 frame_is_intra: false,
1078 show_frame: true,
1079 error_resilient_mode: false,
1080 disable_cdf_update: false,
1081 // The tile writer hands its end-of-tile tables to the next frame
1082 // (`encode_sequence_with_ctx`), so the frame stores them the way the
1083 // decoder will load them (spec 7.20).
1084 disable_frame_end_update_cdf: false,
1085 force_integer_mv: false,
1086 order_hint,
1087 primary_ref_frame: 0,
1088 refresh_frame_flags: 1 << self_slot,
1089 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
1090 // names the slot this frame both predicts from and refreshes;
1091 // GOLDEN names slot 1, which the key frame wrote when it refreshed
1092 // all eight and which no inter frame ever overwrites, so it holds
1093 // the key frame's own picture for the whole GOP.
1094 ref_frame_idx: {
1095 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
1096 idx[3] = GOLDEN_SLOT;
1097 idx[6] = altref_slot;
1098 idx
1099 },
1100 allow_high_precision_mv: false,
1101 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
1102 is_motion_mode_switchable: false,
1103 use_ref_frame_mvs: false,
1104 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
1105 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
1106 // set this crate carries a table for at 16x16 (see
1107 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
1108 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
1109 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
1110 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
1111 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
1112 // path) -- with this flag set, `get_tx_set`'s intra branch returns
1113 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
1114 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
1115 reduced_tx_set: true,
1116 ..key
1117 };
1118 Ok((seq, header))
1119}
1120
1121fn too_large() -> Error {
1122 Error::unsupported(
1123 "AV1 encode",
1124 "the picture is larger than a frame size can carry",
1125 )
1126}
1127
1128/// One plane of the picture being coded, and the reconstruction being built
1129/// beside it.
1130struct Plane<'a> {
1131 source: &'a [u8],
1132 reconstruction: Vec<u8>,
1133 width: usize,
1134 height: usize,
1135 /// The frame's true, decodable extent in this plane's own units --
1136 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
1137 /// not `width`/`height` above, which is the padded coding-surface size.
1138 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
1139 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
1140 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
1141 /// this bound, even though the padded reconstruction buffer holds real
1142 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
1143 /// those instead of stopping here is what desyncs prediction at the true
1144 /// edge.
1145 true_width: usize,
1146 true_height: usize,
1147 /// This plane's own tile's pixel bounds, in this plane's units -- the
1148 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
1149 /// prediction never reaches across a tile edge even though the
1150 /// neighbouring tile's real samples sit right there in the shared
1151 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
1152 /// leaves every edge exactly as it was before tiles existed.
1153 tile_x0: usize,
1154 tile_y0: usize,
1155 tile_x1: usize,
1156 tile_y1: usize,
1157}
1158
1159impl Plane<'_> {
1160 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
1161 /// called at every superblock of the frame-raster search with the rect
1162 /// of the tile that superblock belongs to.
1163 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
1164 self.tile_x0 = x0;
1165 self.tile_y0 = y0;
1166 self.tile_x1 = x1.min(self.width);
1167 self.tile_y1 = y1.min(self.height);
1168 }
1169 /// The reconstructed samples a block at `(x, y)` predicts from: the row
1170 /// above it, the column to its left and the sample between them, each
1171 /// missing where the block sits against an edge of the frame.
1172 ///
1173 /// `reach` says whether the samples above the block's right and below its
1174 /// left are decoded, which is what a directional mode reads into; where
1175 /// they are not, or where the frame ends first, the edge is shorter and
1176 /// the predictor repeats its last sample, exactly as the decoder's clamp
1177 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
1178 fn edges(
1179 &self,
1180 x: usize,
1181 y: usize,
1182 side: usize,
1183 reach: Reach,
1184 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
1185 // Even a block's *own* edge is clamped to the true frame bound, not
1186 // just a `reach` extension: libaom's `av1_predict_intra_block`
1187 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
1188 // this block's own right/bottom to the frame edge -- from
1189 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
1190 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
1191 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
1192 // samples the row/column above/left holds before the decoder starts
1193 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
1194 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
1195 // extent straddles that edge legally (`has_half`) -- the transform
1196 // still covers the whole block, but prediction does not get to read
1197 // real reconstructed pixels past the true edge for its own row/column,
1198 // only for the padded tail it invents.
1199 let own_across = x + side.min(self.true_width.saturating_sub(x));
1200 let across = if reach.above_right {
1201 own_across + side.min(self.true_width.saturating_sub(own_across))
1202 } else {
1203 own_across
1204 }
1205 .min(self.width);
1206 let own_down = y + side.min(self.true_height.saturating_sub(y));
1207 let down = if reach.below_left {
1208 own_down + side.min(self.true_height.saturating_sub(own_down))
1209 } else {
1210 own_down
1211 }
1212 .min(self.height);
1213 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
1214 // whose own origin already sits past the true edge -- only reachable
1215 // through a partition trial priced for comparison on a split this
1216 // frame's straddling quadrant will go on to refuse (see
1217 // `a_picture_off_the_block_grid_is_refused`), never through a block
1218 // this encoder actually commits. Such a block has no true-edge
1219 // samples above or left of it at all, same as `y == 0`/`x == 0`.
1220 let across = across.min(self.tile_x1);
1221 let down = down.min(self.tile_y1);
1222 let above = (y > self.tile_y0 && across > x)
1223 .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec());
1224 let left = (x > self.tile_x0 && down > y).then(|| {
1225 (y..down)
1226 .map(|row| self.reconstruction[row * self.width + x - 1])
1227 .collect::<Vec<_>>()
1228 });
1229 let corner = (x > self.tile_x0 && y > self.tile_y0)
1230 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
1231 (above, left, corner)
1232 }
1233
1234 /// Codes one block under one mode without committing it: hands back the
1235 /// levels, the block the decoder would reconstruct, the squared error
1236 /// against the source and an estimate of what the levels cost in bits.
1237 fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
1238 self.trial_typed(at, mode, base_q_idx, deadzone, TxType::DctDct, fctx)
1239 }
1240
1241 /// [`Self::trial`] under a named transform type -- what an intra chroma
1242 /// block gets, since chroma codes no `tx_type` symbol and the decoder
1243 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
1244 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
1245 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
1246 #[allow(clippy::too_many_arguments)]
1247 fn trial_typed(
1248 &self,
1249 at: At,
1250 mode: u8,
1251 base_q_idx: u8,
1252 deadzone: f64,
1253 tx_type: TxType,
1254 fctx: &crate::decode::FrameCtx,
1255 ) -> Trial {
1256 let At {
1257 x, y, side, reach, ..
1258 } = at;
1259 let (above, left, corner) = self.edges(x, y, side, reach);
1260 // Per-candidate scratch on the search's hottest path, so both buffers
1261 // live on the stack -- `side` is at most `BLOCK` -- rather than
1262 // costing a malloc/free pair per trial (`mc_trial` already does this).
1263 let mut prediction = [0u8; BLOCK * BLOCK];
1264 let prediction = &mut prediction[..side * side];
1265 intra_predict_u8(
1266 mode,
1267 0,
1268 above.as_deref(),
1269 left.as_deref(),
1270 corner,
1271 side,
1272 side,
1273 false,
1274 false,
1275 prediction, fctx,
1276 );
1277
1278 let mut residual = [0i32; BLOCK * BLOCK];
1279 let residual = &mut residual[..side * side];
1280 for row in 0..side {
1281 for col in 0..side {
1282 residual[row * side + col] =
1283 i32::from(self.source[(y + row) * self.width + x + col])
1284 - i32::from(prediction[row * side + col]);
1285 }
1286 }
1287 #[cfg(test)]
1288 let t = std::time::Instant::now();
1289 let levels =
1290 forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type);
1291 let coded =
1292 dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type);
1293 #[cfg(test)]
1294 stage_add(2, t.elapsed());
1295
1296 let mut reconstruction = vec![0u8; side * side];
1297 let mut sse = 0.0;
1298 for row in 0..side {
1299 for col in 0..side {
1300 let i = row * side + col;
1301 let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;
1302 reconstruction[i] = sample;
1303 let error = f64::from(
1304 i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample),
1305 );
1306 sse += error * error;
1307 }
1308 }
1309 // What the levels cost is priced through the same CDFs the tile writer
1310 // will code them with, so the search ranks modes -- and the partition
1311 // trial ranks trees -- by the bits they actually spend.
1312 #[cfg(test)]
1313 let t = std::time::Instant::now();
1314 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
1315 // What the search used before it could price a block exactly: a
1316 // level costs its magnitude's width plus a sign and a run. Kept
1317 // reachable from the sweep so the two rate terms can be compared
1318 // on one build.
1319 levels
1320 .iter()
1321 .filter(|&&level| level != 0)
1322 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
1323 .sum()
1324 } else {
1325 crate::tile::coeff_bits(&levels, at.set, crate::decode::q_ctx_of(base_q_idx))
1326 };
1327 #[cfg(test)]
1328 stage_add(3, t.elapsed());
1329 Trial {
1330 levels,
1331 reconstruction,
1332 sse,
1333 bits,
1334 }
1335 }
1336
1337 /// [`Self::trial`] with the prediction already built, so that an inter
1338 /// block's motion-compensated prediction can go through the same
1339 /// residual/quantize/reconstruct path an intra block's does. `skip`
1340 /// takes the prediction as the reconstruction outright, coding no
1341 /// residual at all — what a `NEARESTMV` block that names no coefficients
1342 /// codes.
1343 #[allow(clippy::too_many_arguments)]
1344 fn code_from_prediction(
1345 &self,
1346 x: usize,
1347 y: usize,
1348 side: usize,
1349 prediction: &[u8],
1350 skip: bool,
1351 base_q_idx: u8,
1352 deadzone: f64,
1353 set: TxbSet,
1354 ) -> Trial {
1355 if skip {
1356 let mut sse = 0.0;
1357 for row in 0..side {
1358 for col in 0..side {
1359 let error = f64::from(
1360 i32::from(self.source[(y + row) * self.width + x + col])
1361 - i32::from(prediction[row * side + col]),
1362 );
1363 sse += error * error;
1364 }
1365 }
1366 return Trial {
1367 levels: vec![0i32; side * side],
1368 reconstruction: prediction.to_vec(),
1369 sse,
1370 bits: 0.0,
1371 };
1372 }
1373 let mut residual = [0i32; BLOCK * BLOCK];
1374 let residual = &mut residual[..side * side];
1375 for row in 0..side {
1376 for col in 0..side {
1377 residual[row * side + col] =
1378 i32::from(self.source[(y + row) * self.width + x + col])
1379 - i32::from(prediction[row * side + col]);
1380 }
1381 }
1382 #[cfg(test)]
1383 let t = std::time::Instant::now();
1384 let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone);
1385 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
1386 #[cfg(test)]
1387 stage_add(2, t.elapsed());
1388 let mut reconstruction = vec![0u8; side * side];
1389 let mut sse = 0.0;
1390 for row in 0..side {
1391 for col in 0..side {
1392 let i = row * side + col;
1393 let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;
1394 reconstruction[i] = sample;
1395 let error = f64::from(
1396 i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample),
1397 );
1398 sse += error * error;
1399 }
1400 }
1401 #[cfg(test)]
1402 let t = std::time::Instant::now();
1403 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
1404 levels
1405 .iter()
1406 .filter(|&&level| level != 0)
1407 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
1408 .sum()
1409 } else {
1410 crate::tile::coeff_bits(&levels, set, crate::decode::q_ctx_of(base_q_idx))
1411 };
1412 #[cfg(test)]
1413 stage_add(3, t.elapsed());
1414 Trial {
1415 levels,
1416 reconstruction,
1417 sse,
1418 bits,
1419 }
1420 }
1421
1422 /// Codes this block's luma at transform depth `depth`: the
1423 /// `(side >> depth)^2` transform units in raster order, each predicted
1424 /// from the reconstruction the units before it left behind -- exactly
1425 /// what the decoder's multi-transform-unit branch does (decode.rs
1426 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
1427 /// reconstructed on its own. Commits the result and hands back the
1428 /// block-coordinate levels, the block's squared error and what its
1429 /// coefficients cost.
1430 fn code_tx_depth(
1431 &mut self,
1432 at: At,
1433 mode: u8,
1434 depth: usize,
1435 search: &Search, fctx: &crate::decode::FrameCtx,
1436 ) -> (Vec<i32>, f64, f64) {
1437 let At { x, y, side, reach, .. } = at;
1438 let tx = side >> depth;
1439 let n = 1usize << depth;
1440 let set = match tx {
1441 32 => TxbSet::Luma32,
1442 16 => TxbSet::Luma16,
1443 8 => TxbSet::Luma8,
1444 _ => TxbSet::Luma4,
1445 };
1446 let mut levels = vec![0i32; side * side];
1447 census_add(4, n * n);
1448 let (mut sse, mut bits) = (0.0, 0.0);
1449 for tu_row in 0..n {
1450 for tu_col in 0..n {
1451 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
1452 let tu = At {
1453 x: x + col_off,
1454 y: y + row_off,
1455 side: tx,
1456 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
1457 set,
1458 };
1459 let trial = self.trial(tu, mode, search.base_q_idx, search.deadzone, fctx);
1460 sse += trial.sse;
1461 bits += trial.bits;
1462 self.commit(tu.x, tu.y, tx, &trial);
1463 for row in 0..tx {
1464 levels[(row_off + row) * side + col_off..][..tx]
1465 .copy_from_slice(&trial.levels[row * tx..][..tx]);
1466 }
1467 }
1468 }
1469 (levels, sse, bits)
1470 }
1471
1472 /// Writes a trial's reconstruction back into the plane.
1473 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
1474 for row in 0..side {
1475 self.reconstruction[(y + row) * self.width + x..][..side]
1476 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
1477 }
1478 }
1479
1480 /// The source samples of one square, contiguous — what a motion search
1481 /// compares its candidates' predictions against ([`motion::search`]'s
1482 /// `source`), since [`Self::source`] itself is the whole plane, strided
1483 /// by [`Self::width`].
1484 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
1485 (y..y + side)
1486 .flat_map(|row| self.source[row * self.width + x..][..side].to_vec())
1487 .collect()
1488 }
1489
1490 /// The reconstructed samples of one square, so that a partition trial can
1491 /// be undone.
1492 fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
1493 (y..y + side)
1494 .flat_map(|row| self.reconstruction[row * self.width + x..][..side].to_vec())
1495 .collect()
1496 }
1497
1498 /// Puts a snapshot back.
1499 fn restore(&mut self, x: usize, y: usize, side: usize, samples: &[u8]) {
1500 for row in 0..side {
1501 self.reconstruction[(y + row) * self.width + x..][..side]
1502 .copy_from_slice(&samples[row * side..][..side]);
1503 }
1504 }
1505
1506 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
1507 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
1508 /// prescreen by the identical rule rather than a second one that could
1509 /// drift from it.
1510 fn intra_scores(
1511 &self,
1512 at: At,
1513 modes: &[u8],
1514 mode_bits: &[f64; 13],
1515 lambda: f64, fctx: &crate::decode::FrameCtx,
1516 ) -> Vec<(f64, u8)> {
1517 let At {
1518 x, y, side, reach, ..
1519 } = at;
1520 let (above, left, corner) = self.edges(x, y, side, reach);
1521 modes
1522 .iter()
1523 .map(|&mode| {
1524 let mut prediction = vec![0u8; side * side];
1525 intra_predict_u8(
1526 mode,
1527 0,
1528 above.as_deref(),
1529 left.as_deref(),
1530 corner,
1531 side,
1532 side,
1533 false,
1534 false,
1535 &mut prediction, fctx,
1536 );
1537 let sad: f64 = (0..side * side)
1538 .map(|i| {
1539 let (row, col) = (i / side, i % side);
1540 f64::from(
1541 (i32::from(self.source[(y + row) * self.width + x + col])
1542 - i32::from(prediction[i]))
1543 .abs(),
1544 )
1545 })
1546 .sum();
1547 (sad + lambda * mode_bits[usize::from(mode)], mode)
1548 })
1549 .collect()
1550 }
1551
1552 /// Codes one block under every mode the search offers (or, when
1553 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
1554 /// pre-pass plus DC) and commits the one whose squared error and
1555 /// estimated rate come out cheapest.
1556 ///
1557 /// The prediction is built once per mode regardless -- the full RD trial
1558 /// needs it too -- so ranking modes by SAD on that same prediction before
1559 /// running the expensive part (forward transform, quantize, reconstruct,
1560 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
1561 /// only to sum.
1562 fn search_block(
1563 &mut self,
1564 at: At,
1565 search: &Search,
1566 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
1567 ) -> (Vec<Coeff>, u8, f64) {
1568 let At {
1569 x, y, side, reach, ..
1570 } = at;
1571 let (above, left, corner) = self.edges(x, y, side, reach);
1572 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
1573 // the census reports it), so summing it under the default unpruned
1574 // search is `side * side` absolute differences per mode spent on a
1575 // number no one reads.
1576 let want_sad = search.top_k.is_some() || census_on();
1577 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
1578 .modes
1579 .iter()
1580 .map(|&mode| {
1581 let mut prediction = vec![0u8; side * side];
1582 intra_predict_u8(
1583 mode,
1584 0,
1585 above.as_deref(),
1586 left.as_deref(),
1587 corner,
1588 side,
1589 side,
1590 false,
1591 false,
1592 &mut prediction, fctx,
1593 );
1594 let sad: f64 = if want_sad {
1595 (0..side * side)
1596 .map(|i| {
1597 let (row, col) = (i / side, i % side);
1598 f64::from(
1599 (i32::from(self.source[(y + row) * self.width + x + col])
1600 - i32::from(prediction[i]))
1601 .abs(),
1602 )
1603 })
1604 .sum()
1605 } else {
1606 0.0
1607 };
1608 (
1609 sad + search.lambda * mode_bits[usize::from(mode)],
1610 mode,
1611 prediction,
1612 )
1613 })
1614 .collect();
1615 if let Some(k) = search.top_k {
1616 if k < scored.len() {
1617 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
1618 let dc_entry = dc_pos.map(|i| scored.remove(i));
1619 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
1620 scored.truncate(if dc_entry.is_some() {
1621 k.saturating_sub(1)
1622 } else {
1623 k
1624 });
1625 if let Some(dc_entry) = dc_entry {
1626 scored.push(dc_entry);
1627 }
1628 }
1629 }
1630 let ranking: Vec<(f64, u8)> = if census_on() {
1631 scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
1632 } else {
1633 Vec::new()
1634 };
1635 census_add(0, 1);
1636 census_add(1, scored.len());
1637 let mut best: Option<(f64, u8, Trial)> = None;
1638 for (_, mode, prediction) in scored {
1639 let trial = self.code_from_prediction(
1640 x,
1641 y,
1642 side,
1643 &prediction,
1644 false,
1645 search.base_q_idx,
1646 search.deadzone,
1647 at.set,
1648 );
1649 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
1650 if best
1651 .as_ref()
1652 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
1653 {
1654 best = Some((cost, mode, trial));
1655 }
1656 }
1657 let (cost, mode, trial) = best.expect("the search offers at least one mode");
1658 if census_on() {
1659 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
1660 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1661 }
1662 self.commit(x, y, side, &trial);
1663 (coeffs(&trial.levels, side), mode, cost)
1664 }
1665}
1666
1667/// Where one block sits in its plane, and how far past its own edges its
1668/// prediction may read.
1669#[derive(Clone, Copy)]
1670struct At {
1671 x: usize,
1672 y: usize,
1673 side: usize,
1674 reach: Reach,
1675 /// Which of the tile writer's coefficient tables this block's levels are
1676 /// coded with, and so which the search prices them through.
1677 set: TxbSet,
1678}
1679
1680/// Which of the samples past a block's own edges the decoder has decoded by
1681/// the time it predicts the block, and so which a directional mode may read.
1682///
1683/// The decoder derives these from its `BlockDecoded` flags, which are cleared
1684/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
1685/// that map, this reads the answer the same way libaom and rav1e do: for a
1686/// block whose transform covers it whole, whether the samples above its right
1687/// (or below its left) are decoded depends only on where the block sits inside
1688/// its 64x64 superblock, which is a pinned table per block size.
1689#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1690pub(crate) struct Reach {
1691 pub(crate) above_right: bool,
1692 pub(crate) below_left: bool,
1693}
1694
1695/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
1696/// libaom): for a block that is neither in the superblock's top row nor its
1697/// rightmost column, whether the block above and to its right is coded before
1698/// it. Indexed by the block's position in the superblock, in blocks of its own
1699/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
1700/// 128, not this crate's 64 superblock -- bit by bit from the low end.
1701const HAS_TOP_RIGHT: [&[u8]; 4] = [
1702 &[255, 85, 119, 85, 127, 85, 119, 85],
1703 &[95, 87],
1704 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
1705 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
1706 &[
1707 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
1708 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
1709 ],
1710
1711 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
1712 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
1713 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
1714 // with side 4 outside a TX4 split; without their own row they clamped
1715 // into the 8x8 table and read above-right samples the decoder has not
1716 // written yet (all-zero pixels in the bottom-right triangle of a
1717 // directional 4x4 leaf).
1718 &[
1719 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
1720 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
1721 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
1722 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
1723 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
1724 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
1725 119, 119, 119, 119, 85, 85, 85, 85,
1726 ],
1727];
1728
1729/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
1730/// left.
1731const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
1732 &[84, 16, 84, 0, 84, 16, 84, 0],
1733 &[4, 4],
1734 // has_bl_8x8 (libaom av1/common/reconintra.c)
1735 &[
1736 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
1737 84, 85, 16, 17, 84, 85, 0, 0,
1738 ],
1739
1740 // has_bl_4x4 (same source, same order).
1741 &[
1742 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
1743 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,
1744 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
1745 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,
1746 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
1747 85, 85, 0, 0, 0, 0,
1748 ],
1749];
1750
1751/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
1752/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
1753/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
1754/// rather than in raster order, so the bottom-left square's top-right
1755/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
1756/// libaom switches tables on the partition type (`get_has_tr_table`); the
1757/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
1758/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
1759/// lane-part32 r5 caught reading undecoded samples.
1760const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
1761 // has_tr_vert_16x16
1762 &[255, 0, 119, 0, 127, 0, 119, 0],
1763 // has_tr_vert_32x32
1764 &[15, 7],
1765 // has_tr_vert_8x8
1766 &[
1767 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
1768 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
1769 ],
1770];
1771
1772/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
1773const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
1774 // has_bl_vert_16x16
1775 &[254, 16, 254, 0, 254, 16, 254, 0],
1776 // has_bl_vert_32x32
1777 &[14, 14],
1778 // has_bl_vert_8x8
1779 &[
1780 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
1781 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
1782 ],
1783];
1784
1785thread_local! {
1786 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
1787 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
1788 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
1789 /// threading one bool through this crate's already twenty-argument
1790 /// `decode_block` would touch every call site instead of the two arms
1791 /// that need it.
1792 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1793}
1794
1795/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
1796pub(crate) struct VertAbGuard(bool);
1797
1798impl Drop for VertAbGuard {
1799 fn drop(&mut self) {
1800 VERT_AB_PARTITION.with(|c| c.set(self.0));
1801 }
1802}
1803
1804/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
1805/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
1806/// so no byte is retyped). Each is indexed by
1807/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
1808/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
1809/// superblock grid; on this crate's 64-pixel superblock the highest index a
1810/// shape can reach stays inside its own table, so no wrap is involved.
1811///
1812/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
1813/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
1814/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
1815/// 10 of the 21 reachable superblock positions for above-right and 7 for
1816/// below-left.
1817/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
1818const 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];
1819/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
1820const 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];
1821/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
1822const 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];
1823/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
1824const 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];
1825/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
1826const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119];
1827/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
1828const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
1829/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
1830const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
1831/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
1832const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0];
1833/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
1834const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
1835/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
1836const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
1837/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
1838const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
1839/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
1840const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
1841/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
1842const HAS_TR_32X64: [u8; 1] = [127];
1843/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
1844const HAS_BL_32X64: [u8; 1] = [0];
1845/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
1846const HAS_TR_64X32: [u8; 1] = [19];
1847/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
1848const HAS_BL_64X32: [u8; 1] = [34];
1849/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
1850const 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];
1851/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
1852const 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];
1853/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
1854const 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];
1855/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
1856const 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];
1857/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
1858const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
1859/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
1860const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
1861/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
1862const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
1863/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
1864const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
1865/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
1866const HAS_TR_16X64: [u8; 2] = [255, 127];
1867/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
1868const HAS_BL_16X64: [u8; 2] = [0, 0];
1869/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
1870const HAS_TR_64X16: [u8; 2] = [3, 1];
1871/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
1872const HAS_BL_64X16: [u8; 2] = [42, 42];
1873
1874/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
1875fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
1876 match (bw, bh) {
1877 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
1878 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
1879 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
1880 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
1881 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
1882 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
1883 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
1884 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
1885 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
1886 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
1887 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
1888 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
1889 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
1890 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
1891 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
1892 }
1893}
1894
1895impl Reach {
1896 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
1897 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
1898 /// own answer is `block` -- a different rule from the standalone-block
1899 /// tables, because a unit's neighbours are mostly its own block's
1900 /// already-reconstructed units:
1901 /// * top-right: available while the unit to the right is still inside
1902 /// the block (`col_off + tx < bw`); otherwise only the block's top row
1903 /// of units reaches past it, through the block-level answer
1904 /// (libaom's `row_off > 0` branch returns exactly
1905 /// `col_off + txw < plane_bw`).
1906 /// * bottom-left: a unit outside the block's left column has none
1907 /// (libaom returns 0 for `col_off > 0`); inside the block
1908 /// (`row_off + tx < bh`) they are the left unit's, already
1909 /// reconstructed; the bottom row falls back to the block-level answer.
1910 pub(crate) fn of_tu(
1911 bw: usize,
1912 bh: usize,
1913 col_off: usize,
1914 row_off: usize,
1915 // The unit's own width and height in pixels; equal for a square
1916 // transform, different for the rect unit a 1:4 strip's first split
1917 // produces (lane-rectsplitx r1).
1918 tx_w: usize,
1919 tx_h: usize,
1920 block: Self,
1921 ) -> Self {
1922 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
1923 // order, so both libaom predicates special-case it (lane-sb128c r10);
1924 // without this the last unit column of every chunk of a 128x64 block
1925 // predicts from a chunk libaom has not decoded yet.
1926 let wide = bw > 64;
1927 Self {
1928 above_right: if row_off > 0 {
1929 // `has_top_right`'s `row_off > 0` branch: the offset is taken
1930 // modulo the 64-wide chunk, except for the one unit whose
1931 // top-right corner is the centre of a 128x128 block.
1932 if wide {
1933 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
1934 } else {
1935 col_off + tx_w < bw
1936 }
1937 } else if col_off + tx_w < bw {
1938 true
1939 } else {
1940 block.above_right
1941 },
1942 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
1943 // `has_bottom_left`: at the left edge of a right-hand chunk
1944 // the bottom-left pixels are in the already-coded left chunk,
1945 // provided they stay inside it.
1946 (row_off % 64) + tx_h < bh.min(64)
1947 } else if col_off > 0 {
1948 false
1949 } else if row_off + tx_h < bh {
1950 true
1951 } else {
1952 block.below_left
1953 },
1954 }
1955 }
1956
1957 /// What a block of `side` samples at `(x, y)` may read past its own edges,
1958 /// in a frame of `width` by `height`.
1959 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
1960 Self {
1961 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
1962 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
1963 }
1964 }
1965
1966 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
1967 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
1968 /// block's own width for the row stride and by its own height for the
1969 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
1970 /// unlike the square [`Self::of`] which uses one `side` for everything.
1971 pub(crate) fn of_rect(
1972 bw: usize,
1973 bh: usize,
1974 x: usize,
1975 y: usize,
1976 width: usize,
1977 height: usize, fctx: &crate::decode::FrameCtx,
1978 ) -> Self {
1979 Self {
1980 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
1981 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
1982 }
1983 }
1984
1985 /// [`Self::of`] for one transform unit of a square block whose transform
1986 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
1987 /// non-zero `row_off`/`col_off`): interior units answer from the block's
1988 /// own geometry, and only a unit on the block's top row (resp. left
1989 /// column) reaches the table -- which is the BLOCK's table read at the
1990 /// BLOCK's position, never a table row for the transform's size. Letting
1991 /// the unit stand in for a block of its own size agrees with libaom for
1992 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
1993 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
1994 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
1995 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
1996 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
1997 /// the transform covering the whole block, luma): everything before the
1998 /// table lookup is that function's own early-exit ladder.
1999 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2000 let sb_mi: usize = reach_sb_px(fctx) / 4;
2001 let (mi_row, mi_col) = (y / 4, x / 4);
2002 let bw_log2 = (bw / 4).trailing_zeros() as usize;
2003 let bh_log2 = (bh / 4).trailing_zeros() as usize;
2004 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
2005 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
2006 // Top row of the superblock: the top-right pixels are in the (already
2007 // decoded) superblock above.
2008 if blk_row == 0 {
2009 return true;
2010 }
2011 // Rightmost column: they fall in the superblock to the right.
2012 if ((blk_col + 1) << bw_log2) >= sb_mi {
2013 return false;
2014 }
2015 let table = rect_reach_tables(bw, bh).0;
2016 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
2017 }
2018
2019 /// libaom `has_top_right`'s own index arithmetic:
2020 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
2021 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
2022 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
2023 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
2024 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
2025 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
2026 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
2027 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
2028 (blk_row << (5 - bw_log2)) + blk_col
2029 }
2030
2031 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
2032 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2033 let sb_mi: usize = reach_sb_px(fctx) / 4;
2034 let (mi_row, mi_col) = (y / 4, x / 4);
2035 let bw_log2 = (bw / 4).trailing_zeros() as usize;
2036 let bh_log2 = (bh / 4).trailing_zeros() as usize;
2037 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
2038 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
2039 // Leftmost column of the superblock: the bottom-left pixels are in
2040 // the left superblock iff they stay inside its height.
2041 if blk_col == 0 {
2042 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
2043 }
2044 // Bottom row (and not the leftmost column): they fall in the
2045 // superblock below, which is not decoded yet.
2046 if ((blk_row + 1) << bh_log2) >= sb_mi {
2047 return false;
2048 }
2049 let table = rect_reach_tables(bw, bh).1;
2050 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
2051 }
2052
2053 /// Marks every [`Reach::of`] made until the returned guard drops as being
2054 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
2055 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
2056 /// unaffected: libaom's own comment says vertical rectangles keep their
2057 /// non-vert table, which is what [`Reach::of_rect`] already reads.
2058 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
2059 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
2060 /// can count the sub-block work that partition creates (lane-ab16).
2061 pub(crate) fn in_vert_ab() -> bool {
2062 VERT_AB_PARTITION.with(std::cell::Cell::get)
2063 }
2064
2065 pub(crate) fn vert_ab_partition() -> VertAbGuard {
2066 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
2067 }
2068
2069 /// Neither, which is all a mode that reads no further than its own edges
2070 /// needs.
2071 pub(crate) fn none() -> Self {
2072 Self {
2073 above_right: false,
2074 below_left: false,
2075 }
2076 }
2077
2078 /// `has_top_right` for a block whose transform covers it whole: the top
2079 /// row of a superblock reads into the superblock above, which is decoded;
2080 /// the rightmost column would read into the superblock to the right, which
2081 /// is not; and everything between is the table's to answer.
2082 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2083 let (row, col, per_side) = Self::position(side, x, y, fctx);
2084 if row == 0 {
2085 return true;
2086 }
2087 if col + 1 == per_side {
2088 return false;
2089 }
2090 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
2091 // (the clamp corner-cut that used to live here is gone); sides
2092 // 16/32/64 share row 0 exactly as libaom's tables repeat.
2093 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
2094 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
2095 // -- a reach over-estimate (extra above-right reference pixels),
2096 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
2097 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
2098 // NB: named `table_row`, not `row` -- `row` above is the block's
2099 // position inside the superblock and is what the bit index below
2100 // steps by (a merge that shadowed it desynced every block size).
2101 let table_row = Self::table(side);
2102 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() {
2103 HAS_TOP_RIGHT_VERT[table_row]
2104 } else {
2105 HAS_TOP_RIGHT[table_row]
2106 };
2107 Self::bit(
2108 table,
2109 (row * Self::table_stride(side) + col) % (table.len() * 8),
2110 )
2111 }
2112
2113 /// `has_bottom_left` for such a block: the leftmost column of a superblock
2114 /// reads into the superblock to its left, which is decoded only as far
2115 /// down as its own bottom; the bottom row would read into the superblock
2116 /// below, which is not decoded at all; and the table answers the rest.
2117 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2118 let (row, col, per_side) = Self::position(side, x, y, fctx);
2119 if col == 0 {
2120 return row * side + side < reach_sb_px(fctx);
2121 }
2122 if row + 1 == per_side {
2123 return false;
2124 }
2125 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
2126 // (the clamp corner-cut that used to live here is gone); sides
2127 // 16/32/64 share row 0 exactly as libaom's tables repeat.
2128 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
2129 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
2130 // -- a reach over-estimate (extra above-right reference pixels),
2131 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
2132 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
2133 // NB: named `table_row`, not `row` -- `row` above is the block's
2134 // position inside the superblock and is what the bit index below
2135 // steps by (a merge that shadowed it desynced every block size).
2136 let table_row = Self::table(side);
2137 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() {
2138 HAS_BOTTOM_LEFT_VERT[table_row]
2139 } else {
2140 HAS_BOTTOM_LEFT[table_row]
2141 };
2142 Self::bit(
2143 table,
2144 (row * Self::table_stride(side) + col) % (table.len() * 8),
2145 )
2146 }
2147
2148 /// Where a block sits inside its superblock, in blocks of its own size,
2149 /// and how many of them a superblock is across.
2150 fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
2151 let sb = reach_sb_px(fctx);
2152 ((y % sb) / side, (x % sb) / side, sb / side)
2153 }
2154
2155 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
2156 /// these tables to its compile-time maximum superblock (128, spec
2157 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
2158 /// size an encode actually uses, so a block's row in the bit index steps
2159 /// by 128 / `side` even though this crate only ever codes a 64
2160 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
2161 /// here instead indexes the wrong bit for every block size but the one
2162 /// where 64 and 128 give the same stride.
2163 fn table_stride(side: usize) -> usize {
2164 128 / side
2165 }
2166
2167 /// Which of the three block sizes the encoder codes a table row is for.
2168 fn table(side: usize) -> usize {
2169 if side == BLOCK {
2170 1
2171 } else if side == 8 {
2172 2
2173 } else if side == 4 {
2174 3
2175 } else {
2176 0
2177 }
2178 }
2179
2180 /// One bit of a table, counting from the low end of its first byte.
2181 fn bit(table: &[u8], index: usize) -> bool {
2182 (table[index / 8] >> (index % 8)) & 1 != 0
2183 }
2184}
2185
2186/// What one symbol costs against a CDF, in bits.
2187pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
2188 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
2189 let width = cdf[symbol] - low;
2190 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
2191 // 32769 prices a symbol can carry; the `log2` behind each is computed
2192 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
2193 // profile -- this function is called for every symbol of every candidate
2194 // the RD search prices). Each entry is exactly the expression this used
2195 // to evaluate, so every price is bit-identical.
2196 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
2197 PRICES.get_or_init(|| {
2198 (0..=32768u32)
2199 .map(|w| -(f64::from(w) / 32768.0).log2())
2200 .collect()
2201 })[usize::from(width)]
2202}
2203
2204/// What the tile writer spends to say a block is coded in each of the thirteen
2205/// modes, given the modes of the blocks above it and to its left: the luma mode
2206/// symbol against the CDF those two neighbours pick, the angle delta a
2207/// directional mode carries, and the chroma mode symbol, whose CDF the luma
2208/// mode itself indexes.
2209///
2210/// Without this the search is blind to what a mode costs to name, which is not
2211/// a rounding error: a directional mode on a picture that does not run that way
2212/// is a rate loss the squared error never sees.
2213/// Codes one square of the picture as a single block: searches the luma mode,
2214/// codes both chroma planes DC, and hands back the block and what it cost --
2215/// squared error plus lambda times the bits its symbols spend.
2216/// How many halvings of a `side`-square block's transform the `tx_depth`
2217/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
2218/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
2219fn max_tx_depth(side: usize) -> usize {
2220 match side {
2221 8 => 1,
2222 16 | 32 => 2,
2223 _ => 0,
2224 }
2225}
2226
2227/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
2228/// Priced at context row 0 -- the writer picks the real row from its
2229/// neighbours' transform sizes, which the search has no view of; the term is
2230/// the same for every depth of one block either way, so it only shifts the
2231/// depth-0-versus-split margin, never the ordering between two splits.
2232fn tx_depth_bits(side: usize, depth: usize) -> f64 {
2233 match side {
2234 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
2235 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
2236 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
2237 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
2238 }
2239}
2240
2241/// How many blocks resolved to each `tx_depth`, the fire count that says
2242/// whether the depth search below reaches its candidates at all.
2243static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
2244 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
2245
2246/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
2247/// to its own encode.
2248#[cfg(test)]
2249pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
2250 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
2251}
2252
2253/// How many inter blocks resolved to each var-tx depth (0 = one transform
2254/// over the whole block, 1 = its four halves), the fire count a gate prints
2255/// to see the split search reach its candidates at all.
2256static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 2] =
2257 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
2258
2259/// How many 32x32-and-below inter blocks each reference frame won, indexed by
2260/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
2261/// fire count a gate prints to see an extra reference reach a block at all
2262/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
2263/// chosen is a pyramid that costs bytes and buys nothing).
2264static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
2265 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
2266
2267/// Reads [`REF_FRAME_HITS`] and zeroes it.
2268#[cfg(test)]
2269pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
2270 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
2271}
2272
2273/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
2274#[cfg(test)]
2275pub(crate) fn take_inter_tx_split_hits() -> [usize; 2] {
2276 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
2277}
2278
2279/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
2280/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
2281/// is one flag, depth 1 is a split root plus one unsplit flag per child
2282/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
2283/// or a 4x4 sub-size).
2284fn txfm_split_bits(side: usize, depth: usize) -> f64 {
2285 let max_tx = side.min(64);
2286 let ctx = |tx: usize| {
2287 crate::decode::txfm_partition_ctx_rect(
2288 crate::decode::TXFM_CTX_INIT,
2289 crate::decode::TXFM_CTX_INIT,
2290 side,
2291 tx,
2292 tx,
2293 )
2294 };
2295 if depth == 0 {
2296 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
2297 }
2298 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
2299 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
2300}
2301
2302/// The inter block's own var-tx decision, once its motion vector is settled:
2303/// its residual as ONE transform over the whole block, or as the four
2304/// transforms of half the side the tree's first halving names. The prediction
2305/// is the same motion compensation either way, so the split trial
2306/// re-transforms the identical residual in four pieces -- it wins where four
2307/// small transforms carry a locally varying residual cheaper than one big
2308/// one. Commits the winner into `luma` and hands back its block-coordinate
2309/// levels, the depth the writer codes and the cost the winner adds to (or
2310/// takes off) the caller's already-computed flat cost.
2311///
2312/// Only for a block wholly inside the frame: past the true edge the reader's
2313/// var-tx recursion skips the units that fall outside
2314/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
2315/// leave the residual units this writes unpaired.
2316#[allow(clippy::too_many_arguments)]
2317fn commit_inter_luma(
2318 luma: &mut Plane,
2319 (x, y): (usize, usize),
2320 side: usize,
2321 mv: (i32, i32),
2322 reference: (&[u16], usize, usize, usize),
2323 search: &Search,
2324 flat: &Trial,
2325 skip: bool, fctx: &crate::decode::FrameCtx,
2326) -> (Vec<i32>, u8, f64) {
2327 let eligible = tx_select()
2328 && tx_select_inter()
2329 && !skip
2330 && side >= 16
2331 && x + side <= luma.true_width
2332 && y + side <= luma.true_height;
2333 if !eligible {
2334 luma.commit(x, y, side, flat);
2335 return (flat.levels.clone(), 0, 0.0);
2336 }
2337 let tx = side / 2;
2338 let set = if tx >= 16 { TxbSet::Luma16Inter } else { TxbSet::Luma8Inter };
2339 let mut levels = vec![0i32; side * side];
2340 let (mut sse, mut bits) = (0.0, 0.0);
2341 let mut units = Vec::with_capacity(4);
2342 for tu_row in 0..2 {
2343 for tu_col in 0..2 {
2344 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
2345 let trial = mc_trial(
2346 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
2347 reference.3, false, search.base_q_idx, search.deadzone, set, fctx,
2348 );
2349 sse += trial.sse;
2350 bits += trial.bits;
2351 for row in 0..tx {
2352 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
2353 .copy_from_slice(&trial.levels[row * tx..][..tx]);
2354 }
2355 units.push((tu_x, tu_y, trial));
2356 }
2357 }
2358 let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1));
2359 let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0));
2360 if split_cost < flat_cost {
2361 for (tu_x, tu_y, trial) in &units {
2362 luma.commit(*tu_x, *tu_y, tx, trial);
2363 }
2364 INTER_TX_SPLIT_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2365 return (levels, 1, split_cost - flat_cost);
2366 }
2367 INTER_TX_SPLIT_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2368 luma.commit(x, y, side, flat);
2369 (flat.levels.clone(), 0, 0.0)
2370}
2371
2372/// The largest distinct-colour count a block may hold and still be offered a
2373/// palette candidate at all: past it the k-means quantisation costs more
2374/// error than the map saves rate, and every trial is wasted wall.
2375///
2376/// Swept on the gate's own screen capture (lane-av1pal2, the
2377/// `unswept-decision-constants` class): 32 (the value this lane inherited)
2378/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
2379/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
2380/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
2381/// binds on nothing this content holds. 128 ships: best BD against both
2382/// references and no wall cost at all (6.1s, the same as at 32, because the
2383/// blocks it newly admits are ones the RD then keeps).
2384/// `EC_AV1_PAL_MAXCOLORS`.
2385fn palette_max_colors() -> usize {
2386 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2387 *N.get_or_init(|| {
2388 std::env::var("EC_AV1_PAL_MAXCOLORS")
2389 .ok()
2390 .and_then(|v| v.parse().ok())
2391 .unwrap_or(128)
2392 })
2393}
2394
2395/// The palettes worth trying for one block's luma, in the shape libaom's
2396/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
2397/// distinct colours takes them ALL (the prediction is then exact and the
2398/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
2399/// one-dimensional Lloyd iteration seeded evenly across its range -- both
2400/// offered, because which wins is an RD question the caller answers.
2401/// `block` is `side*side` source samples, row-major.
2402fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
2403 let mut histogram = [0u32; 256];
2404 for &v in block {
2405 histogram[usize::from(v)] += 1;
2406 }
2407 let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
2408 if present.len() < 2 {
2409 return Vec::new();
2410 }
2411 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
2412 let mut base = [0u16; 8];
2413 base[..colors.len()].copy_from_slice(colors);
2414 let map = block
2415 .iter()
2416 .map(|&v| {
2417 colors
2418 .iter()
2419 .enumerate()
2420 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
2421 .map(|(i, _)| i as u8)
2422 .expect("a palette holds at least two colours")
2423 })
2424 .collect();
2425 crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
2426 };
2427 if present.len() <= 8 {
2428 return vec![exact(&present)];
2429 }
2430 if present.len() > palette_max_colors() {
2431 return Vec::new();
2432 }
2433 let (lo, hi) = (
2434 i32::from(present[0]),
2435 i32::from(present[present.len() - 1]),
2436 );
2437 let mut out = Vec::with_capacity(2);
2438 for n in [8usize, 4] {
2439 // Even seeding across the block's own range, then four Lloyd passes
2440 // over the histogram (256 bins, not `side*side` pixels).
2441 let mut centres: Vec<f64> = (0..n)
2442 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
2443 .collect();
2444 for _ in 0..4 {
2445 let mut sums = vec![0f64; n];
2446 let mut counts = vec![0u32; n];
2447 for (v, &count) in histogram.iter().enumerate() {
2448 if count == 0 {
2449 continue;
2450 }
2451 let k = (0..n)
2452 .min_by(|&a, &b| {
2453 (centres[a] - v as f64)
2454 .abs()
2455 .total_cmp(&(centres[b] - v as f64).abs())
2456 })
2457 .expect("n >= 2");
2458 sums[k] += (v as u32 * count) as f64;
2459 counts[k] += count;
2460 }
2461 for k in 0..n {
2462 if counts[k] > 0 {
2463 centres[k] = sums[k] / f64::from(counts[k]);
2464 }
2465 }
2466 }
2467 let mut colors: Vec<u16> = centres
2468 .iter()
2469 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
2470 .collect();
2471 colors.sort_unstable();
2472 colors.dedup();
2473 if colors.len() >= 2 {
2474 out.push(exact(&colors));
2475 }
2476 }
2477 out
2478}
2479
2480#[allow(clippy::too_many_arguments)]
2481// ---------------------------------------------------------------------------
2482// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
2483// validity). A key frame that detected screen content and finds enough exact
2484// repeats in its own source sets `allow_intrabc`, which the spec forces every
2485// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
2486// its place when the copied blocks pay back the deblock/CDEF/LR the frame
2487// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
2488// ---------------------------------------------------------------------------
2489
2490/// Whether intra block copy is offered at all. **Off by default** --
2491/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
2492/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
2493/// but on the gate's real screen capture it MEASURED WORSE: setting
2494/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
2495/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
2496/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
2497/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
2498/// that detected no screen content.
2499fn intrabc_enabled() -> bool {
2500 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
2501 return forced;
2502 }
2503 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
2504 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
2505}
2506
2507thread_local! {
2508 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
2509 /// probe runs both arms in one process, and the suite is one process, so
2510 /// an environment variable cannot separate them (same reason
2511 /// [`SCREEN_FORCE`] exists).
2512 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
2513}
2514
2515#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2516pub(crate) fn force_intrabc(value: Option<bool>) {
2517 INTRABC_FORCE.with(|c| c.set(value));
2518}
2519
2520/// How many of a screen frame's 16x16 blocks must have an exact repeat
2521/// somewhere else in the source before `allow_intrabc` is worth the in-loop
2522/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
2523/// constant class: `probe_intrabc_threshold` measures the arm at several
2524/// values.
2525fn intrabc_pct() -> usize {
2526 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2527 *N.get_or_init(|| {
2528 std::env::var("EC_AV1_INTRABC_PCT")
2529 .ok()
2530 .and_then(|v| v.parse().ok())
2531 .unwrap_or(10)
2532 })
2533}
2534
2535/// The pixel grid intrabc source positions are hashed on
2536/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
2537/// which keeps the block-hash table (and so the search) linear in the frame
2538/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
2539/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
2540/// bilinear interpolation decode.rs applies but this encoder does not.
2541fn intrabc_step() -> usize {
2542 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2543 *N.get_or_init(|| {
2544 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
2545 .ok()
2546 .and_then(|v| v.parse().ok())
2547 .unwrap_or(4);
2548 if n % 2 == 0 { n.max(2) } else { 4 }
2549 })
2550}
2551
2552/// The side of the luma square the block-hash table is keyed on.
2553const IBC_HASH: usize = 16;
2554
2555/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
2556/// the current one the source's bottom-right corner must already be.
2557const INTRABC_DELAY_SB64: i32 = 4;
2558
2559/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
2560fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
2561 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
2562 for row in 0..IBC_HASH {
2563 let base = (y + row) * width + x;
2564 for &v in &plane[base..base + IBC_HASH] {
2565 h ^= u64::from(v);
2566 h = h.wrapping_mul(0x100_0000_01b3);
2567 }
2568 }
2569 h
2570}
2571
2572/// Every `intrabc_step()`-aligned position of `plane` inside
2573/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
2574fn ibc_index(
2575 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
2576 plane: &[u8],
2577 width: usize,
2578 (x0, y0): (usize, usize),
2579 (x1, y1): (usize, usize),
2580) {
2581 let step = intrabc_step();
2582 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
2583 return;
2584 }
2585 let mut y = y0.next_multiple_of(step);
2586 while y + IBC_HASH <= y1 {
2587 let mut x = x0.next_multiple_of(step);
2588 while x + IBC_HASH <= x1 {
2589 table
2590 .entry(ibc_hash(plane, width, x, y))
2591 .or_default()
2592 .push((x as u32, y as u32));
2593 x += step;
2594 }
2595 y += step;
2596 }
2597}
2598
2599/// Whether `screen`-detected source `y` repeats itself enough to be worth
2600/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
2601/// content appears at some other position, against [`intrabc_pct`]. Returns
2602/// the share as well, for the gate's own print.
2603fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
2604 if true_width < 4 * 64 || true_height < 2 * 64 {
2605 return (false, 0.0);
2606 }
2607 let mut table = std::collections::HashMap::new();
2608 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
2609 let (mut total, mut matched) = (0usize, 0usize);
2610 let mut by = 0;
2611 while by + IBC_HASH <= true_height {
2612 let mut bx = 0;
2613 while bx + IBC_HASH <= true_width {
2614 total += 1;
2615 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
2616 if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
2617 matched += 1;
2618 }
2619 }
2620 bx += IBC_HASH;
2621 }
2622 by += IBC_HASH;
2623 }
2624 let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
2625 (share * 100.0 >= intrabc_pct() as f64, share)
2626}
2627
2628/// One tile's intrabc search state: a block-hash table over the part of the
2629/// tile's own reconstruction that is already final (whole superblock rows --
2630/// the in-loop filters are off on this frame, so a coded superblock row never
2631/// changes again), plus the last DV chosen, which the RD price uses as its
2632/// predictor estimate.
2633struct Ibc {
2634 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
2635 /// source repeats exactly where a lossily coded reconstruction only
2636 /// nearly does, so an exact-match table over the reconstruction finds
2637 /// almost nothing. The candidate is then SCORED against the
2638 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
2639 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
2640 /// The tile's own luma rect, in samples.
2641 tile: (usize, usize, usize, usize),
2642 /// The DV the previous intrabc block of this tile took -- the *estimate*
2643 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
2644 /// against. The writer computes the true predictor off its own mi grid
2645 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
2646 /// a slightly mispriced candidate, never a wrong bitstream.
2647 last_dv: Option<(i32, i32)>,
2648 /// How many blocks took intrabc, and how many hash lookups found at least
2649 /// one valid candidate -- the gate's own fire counts.
2650 hits: usize,
2651 lookups: usize,
2652 found: usize,
2653}
2654
2655impl Ibc {
2656 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
2657 let mut table = std::collections::HashMap::new();
2658 ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
2659 Self {
2660 table,
2661 tile,
2662 last_dv: None,
2663 hits: 0,
2664 lookups: 0,
2665 found: 0,
2666 }
2667 }
2668
2669 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
2670 /// (1/8 pel), with this lane's own extra restriction on top: the source
2671 /// must lie entirely in a COMPLETED superblock row, which is exactly the
2672 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
2673 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
2674 /// wavefront's own diagonal) are legal and not searched; the upgrade path
2675 /// is to index the current row's finished superblocks too.
2676 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
2677 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
2678 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
2679 return false;
2680 }
2681 let (tx0, ty0, tx1, ty1) = (
2682 self.tile.0 as i32,
2683 self.tile.1 as i32,
2684 self.tile.2 as i32,
2685 self.tile.3 as i32,
2686 );
2687 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
2688 let (w, h) = (w as i32, h as i32);
2689 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
2690 return false;
2691 }
2692 let active_sb_row = (y as i32 - ty0) >> 6;
2693 let active_sb_col = (x as i32 - tx0) >> 6;
2694 let src_sb_row = (sy + h - 1 - ty0) >> 6;
2695 let src_sb_col = (sx + w - 1 - tx0) >> 6;
2696 // This lane's own restriction (see the doc comment).
2697 if src_sb_row >= active_sb_row {
2698 return false;
2699 }
2700 let total = ((tx1 - tx0 - 1) >> 6) + 1;
2701 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64
2702 {
2703 return false;
2704 }
2705 // libaom's wavefront: only the top-left cone of the frame is legal.
2706 let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row);
2707 src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf
2708 }
2709}
2710
2711/// How many block searches ran, how many found at least one VALID candidate,
2712/// and how many won on rate-distortion -- the hash hit rate a gate prints
2713/// (class `gate-blind-to-feature`: "the search ran" and "the search found
2714/// something" and "the block took it" are three different claims).
2715static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
2716 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
2717
2718impl Drop for Ibc {
2719 fn drop(&mut self) {
2720 for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
2721 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
2722 }
2723 }
2724}
2725
2726/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
2727/// its own encode.
2728#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
2729pub(crate) fn take_intrabc_search() -> [usize; 3] {
2730 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
2731}
2732
2733/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
2734/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
2735/// infers rather than codes.
2736fn dv_component_bits(diff: i32) -> f64 {
2737 let z = diff.unsigned_abs() as i32 - 1;
2738 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
2739 let class = mv_class_of(z);
2740 bits += symbol_bits(&cdf::MV_CLASS, class);
2741 let local = z - mv_class_base(class);
2742 if class == 0 {
2743 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
2744 } else {
2745 let d = local >> 3;
2746 for i in 0..class {
2747 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
2748 }
2749 }
2750 bits
2751}
2752
2753/// What one block vector costs against `pred`, plus the `skip` and
2754/// `use_intrabc` flags the block carries and the ordinary intra block does
2755/// not pay in this currency.
2756fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
2757 let diff = (dv.0 - pred.0, dv.1 - pred.1);
2758 let joint = match (diff.0 != 0, diff.1 != 0) {
2759 (false, false) => 0,
2760 (false, true) => 1,
2761 (true, false) => 2,
2762 (true, true) => 3,
2763 };
2764 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
2765 if diff.0 != 0 {
2766 bits += dv_component_bits(diff.0);
2767 }
2768 if diff.1 != 0 {
2769 bits += dv_component_bits(diff.1);
2770 }
2771 bits
2772}
2773
2774/// The squared error of copying the `side`-square block at `(sx, sy)` of each
2775/// plane's reconstruction onto the source block at `(x, y)`, luma and both
2776/// chroma planes together -- what an intrabc block's whole (residual-free)
2777/// distortion is.
2778fn ibc_sse(
2779 luma: &Plane,
2780 chroma: &[Plane; 2],
2781 (x, y): (usize, usize),
2782 (sx, sy): (usize, usize),
2783 side: usize,
2784) -> f64 {
2785 let mut sse = 0.0f64;
2786 for row in 0..side {
2787 let src = &luma.source[(y + row) * luma.width + x..][..side];
2788 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..side];
2789 for (&s, &r) in src.iter().zip(rec) {
2790 let d = f64::from(i32::from(s) - i32::from(r));
2791 sse += d * d;
2792 }
2793 }
2794 let half = side / 2;
2795 for plane in chroma {
2796 for row in 0..half {
2797 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..half];
2798 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..half];
2799 for (&s, &r) in src.iter().zip(rec) {
2800 let d = f64::from(i32::from(s) - i32::from(r));
2801 sse += d * d;
2802 }
2803 }
2804 }
2805 sse
2806}
2807
2808/// Copies the `side`-square block at `(sx, sy)` of each plane's
2809/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
2810/// since it carries no residual (`skip`). Full-pel in both planes by
2811/// construction ([`intrabc_step`] keeps every DV even), which is what makes
2812/// this a plain copy where decode.rs runs the bilinear kernel over the same
2813/// samples.
2814fn ibc_commit(
2815 luma: &mut Plane,
2816 chroma: &mut [Plane; 2],
2817 (x, y): (usize, usize),
2818 (sx, sy): (usize, usize),
2819 side: usize,
2820) {
2821 for row in 0..side {
2822 let from = (sy + row) * luma.width + sx;
2823 let to = (y + row) * luma.width + x;
2824 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
2825 luma.reconstruction[to..to + side].copy_from_slice(&copied);
2826 }
2827 let half = side / 2;
2828 for plane in chroma {
2829 for row in 0..half {
2830 let from = (sy / 2 + row) * plane.width + sx / 2;
2831 let to = (y / 2 + row) * plane.width + x / 2;
2832 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
2833 plane.reconstruction[to..to + half].copy_from_slice(&copied);
2834 }
2835 }
2836}
2837
2838/// Searches this block's own DV: every hash-table position whose 16x16 luma
2839/// square equals the block's source square, plus the previous block's DV as a
2840/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
2841/// the winning `(dv, cost)`, or `None` when nothing valid was found.
2842fn ibc_search(
2843 ibc: &mut Ibc,
2844 luma: &Plane,
2845 chroma: &[Plane; 2],
2846 (x, y): (usize, usize),
2847 side: usize,
2848 lambda: f64,
2849) -> Option<((i32, i32), f64, (usize, usize))> {
2850 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
2851 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
2852 let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
2853 let dv = (
2854 (sy as i32 - y as i32) * 8,
2855 (sx as i32 - x as i32) * 8,
2856 );
2857 if !ibc.dv_valid(x, y, side, side, dv) {
2858 return;
2859 }
2860 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
2861 if best.as_ref().is_none_or(|b| cost < b.1) {
2862 *best = Some((dv, cost, (sx, sy)));
2863 }
2864 };
2865 ibc.lookups += 1;
2866 let key = ibc_hash(luma.source, luma.width, x, y);
2867 // The table is filled in raster order, so the entries BEFORE this block's
2868 // own position are exactly the already-coded ones -- and the nearest of
2869 // them costs the fewest DV bits. Walking backwards from the block's own
2870 // slot is what makes the search look up-and-left; taking the newest
2871 // entries outright only ever finds candidates below and to the right,
2872 // every one of which `dv_valid` rejects.
2873 let hits: Vec<(u32, u32)> = ibc
2874 .table
2875 .get(&key)
2876 .map(|h| {
2877 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
2878 h[..end].iter().rev().take(32).copied().collect()
2879 })
2880 .unwrap_or_default();
2881 for (hx, hy) in hits {
2882 consider(&*ibc, hx as usize, hy as usize, &mut best);
2883 }
2884 if let Some(dv) = ibc.last_dv {
2885 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
2886 if sx >= 0 && sy >= 0 {
2887 consider(&*ibc, sx as usize, sy as usize, &mut best);
2888 }
2889 }
2890 if best.is_some() {
2891 ibc.found += 1;
2892 }
2893 best
2894}
2895
2896fn code_square(
2897 luma: &mut Plane,
2898 chroma: &mut [Plane; 2],
2899 (x, y): (usize, usize),
2900 side: usize,
2901 search: &Search,
2902 mode_bits: &[f64; 13],
2903 // The frame header's `tx_mode == TxMode::Select`: the block then searches
2904 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
2905 // transform over its whole side.
2906 tx_select: bool,
2907 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
2908 // header did not set `allow_intrabc`.
2909 ibc: Option<&mut Ibc>, fctx: &crate::decode::FrameCtx,
2910) -> (BlockCoeffs, f64) {
2911 let (luma_set, chroma_set) = if side == BLOCK {
2912 (TxbSet::Luma32, TxbSet::Chroma16)
2913 } else if side == 8 {
2914 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
2915 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
2916 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
2917 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
2918 // (this branch is still unreached), so leaving `Chroma8` here would
2919 // silently wire the wrong table the moment one does; `Chroma4` is
2920 // what a real caller needs.
2921 (TxbSet::Luma8, TxbSet::Chroma4)
2922 } else {
2923 (TxbSet::Luma16, TxbSet::Chroma8)
2924 };
2925 let at = At {
2926 x,
2927 y,
2928 side,
2929 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
2930 set: luma_set,
2931 };
2932 let (mut luma_coeffs, mode, mut cost) = luma.search_block(at, search, mode_bits, fctx);
2933 // The depth search runs on the mode the whole-block transform picked --
2934 // libaom's own ordering, and the reason it costs one extra pass per depth
2935 // rather than one per (mode, depth) pair.
2936 let mut tx_depth = 0u8;
2937 if tx_select && max_tx_depth(side) > 0 {
2938 let mut best = (
2939 cost + search.lambda * tx_depth_bits(side, 0),
2940 0usize,
2941 luma.snapshot(x, y, side),
2942 luma_coeffs,
2943 );
2944 for depth in 1..=max_tx_depth(side) {
2945 let (levels, sse, bits) = luma.code_tx_depth(at, mode, depth, search, fctx);
2946 let cost_d = sse
2947 + search.lambda
2948 * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth));
2949 if cost_d < best.0 {
2950 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
2951 }
2952 }
2953 luma.restore(x, y, side, &best.2);
2954 cost = best.0;
2955 tx_depth = best.1 as u8;
2956 luma_coeffs = best.3;
2957 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2958 }
2959 // The palette candidate is priced against the mode the luma search (and
2960 // its transform-depth search) already settled on, so a block only takes
2961 // one when it beats the best ordinary intra coding of the same pixels.
2962 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
2963 // prediction is the colour map, not the DC of its neighbours.
2964 let mut mode = mode;
2965 let mut palette = None;
2966 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
2967 let source: Vec<u8> = (y..y + side)
2968 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
2969 .collect();
2970 let kept = luma.snapshot(x, y, side);
2971 for pal in palette_candidates(&source) {
2972 let n = usize::from(pal.size);
2973 let prediction: Vec<u8> = pal
2974 .map
2975 .iter()
2976 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
2977 .collect();
2978 let trial = luma.code_from_prediction(
2979 x,
2980 y,
2981 side,
2982 &prediction,
2983 false,
2984 search.base_q_idx,
2985 search.deadzone,
2986 luma_set,
2987 );
2988 let cost_p = trial.sse
2989 + search.lambda
2990 * (trial.bits
2991 + mode_bits[DC_PRED as usize]
2992 + crate::tile::palette_bits(&pal, side)
2993 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
2994 if cost_p < cost {
2995 cost = cost_p;
2996 mode = DC_PRED as u8;
2997 tx_depth = 0;
2998 luma_coeffs = coeffs(&trial.levels, side);
2999 luma.commit(x, y, side, &trial);
3000 palette = Some(pal);
3001 }
3002 }
3003 if palette.is_none() {
3004 luma.restore(x, y, side, &kept);
3005 }
3006 }
3007
3008 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
3009 // planes; what it costs still counts towards the partition decision.
3010 let ([u, v], uv_mode, chroma_cost, palette_uv) =
3011 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);
3012 cost += chroma_cost;
3013
3014 // The intrabc arm is priced against the WHOLE block -- luma and both
3015 // chroma planes, residual-free -- so it is compared after the chroma
3016 // search has added its own cost, not against the luma decision alone.
3017 if let Some(ibc) = ibc {
3018 if let Some((dv, cost_ibc, src)) =
3019 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
3020 {
3021 if cost_ibc < cost {
3022 ibc_commit(luma, chroma, (x, y), src, side);
3023 ibc.last_dv = Some(dv);
3024 ibc.hits += 1;
3025 return (
3026 BlockCoeffs {
3027 skip: true,
3028 dv: Some(dv),
3029 ..BlockCoeffs::default()
3030 },
3031 cost_ibc,
3032 );
3033 }
3034 }
3035 }
3036 (
3037 BlockCoeffs {
3038 u,
3039 v,
3040 luma: luma_coeffs,
3041 mode,
3042 uv_mode,
3043 tx_depth,
3044 palette,
3045 palette_uv,
3046 ..BlockCoeffs::default()
3047 },
3048 cost,
3049 )
3050}
3051
3052/// The chroma modes the search offers, and the only ones it may offer: each
3053/// predicts from the row directly above and the column directly to the left
3054/// and nothing further, so none of them needs the above-right/below-left
3055/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
3056/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
3057/// reconstruction and its own alpha syntax; both are left out here.
3058const CHROMA_MODES: [u8; 7] = [
3059 DC_PRED,
3060 V_PRED,
3061 H_PRED,
3062 SMOOTH_PRED,
3063 SMOOTH_V_PRED,
3064 SMOOTH_H_PRED,
3065 PAETH_PRED,
3066];
3067
3068/// The thirteen intra mode names, for the chroma fire count's print.
3069#[cfg(test)]
3070const UV_MODE_NAMES: [&str; 13] = [
3071 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
3072 "SMOOTH_H", "PAETH",
3073];
3074
3075/// How many blocks each chroma mode has won, indexed by the mode itself --
3076/// the fire count that says whether the search below reaches its candidates
3077/// at all (the `gate-blind-to-feature` class), printed once per gate run.
3078static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 13] =
3079 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
3080
3081/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
3082/// to its own encode.
3083#[cfg(test)]
3084pub(crate) fn take_uv_mode_hits() -> [usize; 13] {
3085 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
3086}
3087
3088/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
3089/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
3090/// Returns each plane's levels, the mode, and what the pair cost (squared
3091/// error plus lambda times bits, the same currency the luma search speaks).
3092///
3093/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
3094/// which is what the luma mode decision was taken against, so what a
3095/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
3096/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
3097/// writer then has to code.
3098#[allow(clippy::too_many_arguments)]
3099/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
3100/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
3101/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
3102/// trials all seven, as before this lever.
3103///
3104/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
3105/// the search's largest trial population by far -- seven modes times two
3106/// planes for every intra block, against 3.7 luma trials -- and the RD
3107/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
3108/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
3109fn chroma_top_k() -> Option<usize> {
3110 static K: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
3111 *K.get_or_init(|| match std::env::var("EC_AV1_CHROMA_K").ok() {
3112 Some(v) => v.parse::<usize>().ok().filter(|&k| k > 0),
3113 None => CHROMA_TOP_K,
3114 })
3115}
3116
3117/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
3118/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
3119/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
3120/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
3121/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
3122/// BD swings by about a point in either direction as near-tie chroma modes
3123/// flip, which is the measurement's own sensitivity, not a trend: nothing
3124/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
3125const CHROMA_TOP_K: Option<usize> = None;
3126
3127fn search_chroma(
3128 chroma: &mut [Plane; 2],
3129 (x, y): (usize, usize),
3130 side: usize,
3131 set: TxbSet,
3132 search: &Search,
3133 luma_mode: u8,
3134 fctx: &crate::decode::FrameCtx,
3135) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) {
3136 let at = At {
3137 x: x / 2,
3138 y: y / 2,
3139 side: side / 2,
3140 reach: Reach::none(),
3141 set,
3142 };
3143 // The census's cheap proxy for a chroma mode: the SAD of its prediction
3144 // summed over both planes, ranked by the same rule the luma histogram
3145 // uses. Only built under `EC_AV1_CENSUS`.
3146 // The SAD of each mode's prediction, summed over both planes -- the
3147 // census's ranking rule, and what [`chroma_top_k`] prunes by.
3148 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
3149 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
3150 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
3151 u.iter()
3152 .zip(v.iter())
3153 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
3154 .collect()
3155 };
3156 let modes: Vec<u8> = match chroma_top_k() {
3157 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
3158 _ => CHROMA_MODES.to_vec(),
3159 };
3160 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
3161 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
3162 let ranking: Vec<(f64, u8)> = if census_on() {
3163 sad_scores(chroma)
3164 } else {
3165 Vec::new()
3166 };
3167 census_add(2, 1);
3168 census_add(3, modes.len());
3169 let mut best: Option<(f64, u8, Trial, Trial)> = None;
3170 for mode in modes {
3171 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
3172 if (V_PRED..=D67_PRED).contains(&mode) {
3173 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
3174 }
3175 let tx_type = crate::decode::default_intra_tx_type(mode);
3176 let u = chroma[0].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx);
3177 let v = chroma[1].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx);
3178 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
3179 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
3180 best = Some((cost, mode, u, v));
3181 }
3182 }
3183 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
3184 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
3185 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
3186 // what keeps `u_colors` ascending and distinct the way
3187 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
3188 // each cluster's own mean, since the colour-index map is SHARED by the
3189 // two planes. Priced against the best ordinary chroma mode above, so a
3190 // block only takes one when it beats it; a palette block's chroma mode is
3191 // `UV_DC_PRED` by construction.
3192 let mut palette_uv = None;
3193 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
3194 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
3195 let plane_source = |p: &Plane| -> Vec<u8> {
3196 (at.y..at.y + at.side)
3197 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
3198 .collect()
3199 };
3200 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
3201 for pal in palette_candidates(&u_source) {
3202 let n = usize::from(pal.size);
3203 // V's base colour per cluster: the mean of the samples the shared
3204 // map assigns to it (an empty cluster cannot happen -- every
3205 // colour `palette_candidates` returns is some pixel's nearest).
3206 let mut sums = [0u32; 8];
3207 let mut counts = [0u32; 8];
3208 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
3209 let k = usize::from(i).min(n - 1);
3210 sums[k] += u32::from(sample);
3211 counts[k] += 1;
3212 }
3213 let mut v_colors = [0u16; 8];
3214 for k in 0..n {
3215 v_colors[k] = if counts[k] > 0 {
3216 ((sums[k] + counts[k] / 2) / counts[k]) as u16
3217 } else {
3218 0
3219 };
3220 }
3221 let candidate = crate::tile::PaletteUv {
3222 size: pal.size,
3223 u_colors: pal.colors,
3224 v_colors,
3225 map: pal.map,
3226 };
3227 let predict = |colors: &[u16; 8]| -> Vec<u8> {
3228 candidate
3229 .map
3230 .iter()
3231 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
3232 .collect()
3233 };
3234 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
3235 let u_trial = chroma[0].code_from_prediction(
3236 at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
3237 );
3238 let v_trial = chroma[1].code_from_prediction(
3239 at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
3240 );
3241 let cost_p = u_trial.sse
3242 + v_trial.sse
3243 + search.lambda
3244 * (u_trial.bits
3245 + v_trial.bits
3246 + crate::tile::palette_uv_bits(&candidate, side));
3247 if cost_p < cost {
3248 cost = cost_p;
3249 mode = DC_PRED;
3250 u = u_trial;
3251 v = v_trial;
3252 palette_uv = Some(candidate);
3253 }
3254 }
3255 }
3256 if census_on() {
3257 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
3258 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3259 }
3260 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3261 chroma[0].commit(at.x, at.y, at.side, &u);
3262 chroma[1].commit(at.x, at.y, at.side, &v);
3263 (
3264 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
3265 mode,
3266 cost,
3267 palette_uv,
3268 )
3269}
3270
3271/// Codes one leaf of a straddling quadrant as whichever costs least of intra
3272/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
3273/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
3274/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
3275/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
3276/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
3277/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
3278/// attempted here: these leaves only ever fill the sliver of real content a
3279/// true edge lands in the middle of a larger block, not a leaf worth a full
3280/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
3281/// (see `write_inter_frame_leaf`'s doc comment).
3282#[allow(clippy::too_many_arguments)]
3283fn code_square_inter(
3284 luma: &mut Plane,
3285 chroma: &mut [Plane; 2],
3286 (x, y): (usize, usize),
3287 side: usize,
3288 search: &Search,
3289 mode_bits: &[f64; 13],
3290 reference: &Picture,
3291 stack: &MvStack,
3292 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
3293 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
3294 // `reference_select`, and at the straddling call sites).
3295 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
3296 fctx: &crate::decode::FrameCtx,
3297) -> (BlockCoeffs, f64) {
3298 let (intra_block, intra_cost) =
3299 code_square(
3300 luma,
3301 chroma,
3302 (x, y),
3303 side,
3304 search,
3305 mode_bits,
3306 tx_select() && tx_select_inter(),
3307 None,
3308 fctx,
3309 );
3310 let luma_set = if side == 8 {
3311 TxbSet::Luma8Inter
3312 } else {
3313 TxbSet::Luma16Inter
3314 };
3315 let chroma_set = if side == 8 {
3316 TxbSet::Chroma4
3317 } else {
3318 TxbSet::Chroma8
3319 };
3320
3321 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
3322 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
3323 let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0)
3324 + symbol_bits(&cdf::SINGLE_REF[0][2], 0)
3325 + symbol_bits(&cdf::SINGLE_REF[0][3], 0);
3326 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
3327 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
3328 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
3329
3330 let mv = stack.nearest_mv;
3331 let ref_luma = (
3332 &reference.y,
3333 reference.width,
3334 luma.true_width,
3335 luma.true_height,
3336 );
3337 let ref_u = (
3338 &reference.u,
3339 reference.width / 2,
3340 chroma[0].true_width,
3341 chroma[0].true_height,
3342 );
3343 let ref_v = (
3344 &reference.v,
3345 reference.width / 2,
3346 chroma[1].true_width,
3347 chroma[1].true_height,
3348 );
3349 let luma_trial = mc_trial(
3350 luma,
3351 x,
3352 y,
3353 side,
3354 mv,
3355 true,
3356 ref_luma.0,
3357 ref_luma.1,
3358 ref_luma.2,
3359 ref_luma.3,
3360 false,
3361 search.base_q_idx,
3362 search.deadzone,
3363 luma_set, fctx,
3364 );
3365 let u = mc_trial(
3366 &chroma[0],
3367 x / 2,
3368 y / 2,
3369 side / 2,
3370 mv,
3371 false,
3372 ref_u.0,
3373 ref_u.1,
3374 ref_u.2,
3375 ref_u.3,
3376 false,
3377 search.base_q_idx,
3378 search.deadzone,
3379 chroma_set, fctx,
3380 );
3381 let v = mc_trial(
3382 &chroma[1],
3383 x / 2,
3384 y / 2,
3385 side / 2,
3386 mv,
3387 false,
3388 ref_v.0,
3389 ref_v.1,
3390 ref_v.2,
3391 ref_v.3,
3392 false,
3393 search.base_q_idx,
3394 search.deadzone,
3395 chroma_set, fctx,
3396 );
3397 let skip = luma_trial.levels.iter().all(|&l| l == 0)
3398 && u.levels.iter().all(|&l| l == 0)
3399 && v.levels.iter().all(|&l| l == 0);
3400 let inter_cost = luma_trial.sse
3401 + u.sse
3402 + v.sse
3403 + search.lambda
3404 * (skip_bits(skip)
3405 + intra_inter_bits(true)
3406 + single_ref_bits
3407 + mode_bits_inter
3408 + if skip {
3409 0.0
3410 } else {
3411 luma_trial.bits + u.bits + v.bits
3412 });
3413
3414 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
3415 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
3416 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
3417 // scan's own coverage already reached as far) but a real gap at 4-mi
3418 // leaf geometry. r3 ported the extended scan and, while proving it a
3419 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
3420 // `mvstack.rs`), found and fixed a second bug the extended scan's
3421 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
3422 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
3423 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
3424 // regardless of whether it also casts a ref-frame-matching vote) --
3425 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
3426 // branches), which is what made 8-mi geometry a true no-op instead of
3427 // one that only held when every neighbour happened to be inter.
3428 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
3429 // only ever took the stack's NEARESTMV candidate or went intra, so a
3430 // 32x32 block splitting because its four quarters MOVE differently could
3431 // not code the movement it split for. Same candidate `search_inter_block`
3432 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
3433 // a vector the residual syntax can name -- at this leaf's own side.
3434 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
3435 // This leaf's own `NEWMV` vector, kept whether or not it won the
3436 // single-reference comparison: it seeds the compound half-new candidate
3437 // below, exactly as `search_inter_block` seeds its own from the searches
3438 // it already ran.
3439 let mut searched_new: Option<(i32, i32)> = None;
3440 if leaf_new_mv() {
3441 let source_block = luma.source_block(x, y, side);
3442 let (seeds, seed_n) = mv_seeds(stack);
3443 let found = motion::search(
3444 ref_luma.0,
3445 ref_luma.1,
3446 ref_luma.2,
3447 ref_luma.3,
3448 &source_block,
3449 x,
3450 y,
3451 side,
3452 side,
3453 stack.pred_mv,
3454 &seeds[..seed_n],
3455 search.lambda, fctx,
3456 1,
3457 );
3458 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
3459 if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) {
3460 searched_new = Some(new_mv);
3461 // Same reuse as `search_inter_block`: a NEWMV equal to the
3462 // stack's NEARESTMV is the same three trials, already run above.
3463 let (luma_new, u_new, v_new) = if new_mv == mv {
3464 (luma_trial.clone(), u.clone(), v.clone())
3465 } else {
3466 (
3467 mc_trial(
3468 luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2,
3469 ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx,
3470 ),
3471 mc_trial(
3472 &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1,
3473 ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set,
3474 fctx,
3475 ),
3476 mc_trial(
3477 &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1,
3478 ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set,
3479 fctx,
3480 ),
3481 )
3482 };
3483 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
3484 && u_new.levels.iter().all(|&l| l == 0)
3485 && v_new.levels.iter().all(|&l| l == 0);
3486 let drl_bits = if stack.entries.len() > 1 {
3487 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
3488 } else {
3489 0.0
3490 };
3491 let cost_new = luma_new.sse
3492 + u_new.sse
3493 + v_new.sse
3494 + search.lambda
3495 * (skip_bits(skip_new)
3496 + intra_inter_bits(true)
3497 + single_ref_bits
3498 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
3499 + drl_bits
3500 + mv_bits
3501 + if skip_new {
3502 0.0
3503 } else {
3504 luma_new.bits + u_new.bits + v_new.bits
3505 });
3506 if cost_new < best.0 {
3507 best = (
3508 cost_new,
3509 Some((
3510 luma_new,
3511 u_new,
3512 v_new,
3513 skip_new,
3514 InterInfo {
3515 ref1: None,
3516 mv1: (0, 0),
3517 ref_frame: crate::mvstack::LAST_FRAME,
3518 mode: InterMode::NewMv,
3519 mv: new_mv,
3520 ref_mv_idx: 0,
3521 },
3522 )),
3523 );
3524 }
3525 }
3526 }
3527
3528 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
3529 // `search_inter_block` prices for a whole 32x32 block minus the two that
3530 // need a motion search against the SECOND reference: a leaf never runs
3531 // one (`NEAREST_NEWMV`/`NEW_NEWMV` would each cost another
3532 // `motion::search` per extra reference per leaf), so the set here is
3533 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV` and `NEW_NEARESTMV` off the
3534 // vector this leaf already searched. Priced with the same static-CDF
3535 // approximation, plus the compound-only syntax the writer emits.
3536 for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) {
3537 let (ref1, g) = (*ref1, *g);
3538 let uni =
3539 (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1);
3540 let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
3541 + if uni {
3542 symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
3543 + symbol_bits(&cdf::COMP_REF[0][0], 0)
3544 + symbol_bits(&cdf::COMP_REF[0][1], 0)
3545 + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
3546 } else {
3547 symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
3548 + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
3549 + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
3550 + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
3551 };
3552 let mode_ctx =
3553 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
3554 let mode_bits_of =
3555 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
3556 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
3557 (
3558 cstack.nearest_mv,
3559 mode_bits_of(0),
3560 InterInfo {
3561 ref_frame: crate::mvstack::LAST_FRAME,
3562 mode: InterMode::NearestNearestMv,
3563 mv: cstack.nearest_mv.0,
3564 mv1: cstack.nearest_mv.1,
3565 ref1: Some(ref1),
3566 ref_mv_idx: 0,
3567 },
3568 ),
3569 (
3570 ((0, 0), (0, 0)),
3571 mode_bits_of(6),
3572 InterInfo {
3573 ref_frame: crate::mvstack::LAST_FRAME,
3574 mode: InterMode::GlobalGlobalMv,
3575 mv: (0, 0),
3576 mv1: (0, 0),
3577 ref1: Some(ref1),
3578 ref_mv_idx: 0,
3579 },
3580 ),
3581 ];
3582 // `NEW_NEARESTMV`: the NEW half is this leaf's own searched vector,
3583 // its residual priced against compound stack entry 0 (what
3584 // `assign_compound_mv` predicts from at `ref_mv_idx = 0`).
3585 let cbase = cstack
3586 .entries
3587 .first()
3588 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
3589 if let Some(new_mv) = searched_new {
3590 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
3591 ccands.push((
3592 (new_mv, cstack.nearest_mv.1),
3593 mode_bits_of(3) + b0,
3594 InterInfo {
3595 ref_frame: crate::mvstack::LAST_FRAME,
3596 mode: InterMode::NewNearestMv,
3597 mv: new_mv,
3598 mv1: cstack.nearest_mv.1,
3599 ref1: Some(ref1),
3600 ref_mv_idx: 0,
3601 },
3602 ));
3603 }
3604 }
3605 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
3606 ccands.dedup_by_key(|c| c.0);
3607 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
3608 let g_u = (
3609 g.u.as_slice(),
3610 g.width / 2,
3611 chroma[0].true_width,
3612 chroma[0].true_height,
3613 );
3614 let g_v = (
3615 g.v.as_slice(),
3616 g.width / 2,
3617 chroma[1].true_width,
3618 chroma[1].true_height,
3619 );
3620 for (mvs, bits, info) in ccands {
3621 let luma_c = mc_trial_compound(
3622 luma, x, y, side, mvs, true,
3623 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
3624 search.base_q_idx, search.deadzone, luma_set, fctx,
3625 );
3626 let u_c = mc_trial_compound(
3627 &chroma[0], x / 2, y / 2, side / 2, mvs, false,
3628 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
3629 search.base_q_idx, search.deadzone, chroma_set, fctx,
3630 );
3631 let v_c = mc_trial_compound(
3632 &chroma[1], x / 2, y / 2, side / 2, mvs, false,
3633 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
3634 search.base_q_idx, search.deadzone, chroma_set, fctx,
3635 );
3636 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
3637 && u_c.levels.iter().all(|&l| l == 0)
3638 && v_c.levels.iter().all(|&l| l == 0);
3639 let cost_c = luma_c.sse
3640 + u_c.sse
3641 + v_c.sse
3642 + search.lambda
3643 * (skip_bits(skip_c)
3644 + intra_inter_bits(true)
3645 + bits
3646 + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
3647 if cost_c < best.0 {
3648 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
3649 }
3650 }
3651 }
3652
3653 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
3654 if cost < intra_cost {
3655 // A compound winner commits the flat trial it was priced from:
3656 // `commit_inter_luma`'s var-tx trial set is single-reference
3657 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
3658 // corner-cut: no var-tx split for a compound leaf -- ceiling is
3659 // the split gain on 16x16 compound blocks; upgrade path is a
3660 // compound `commit_inter_luma` taking both references.
3661 let (levels, tx_depth, dcost) = if info.ref1.is_some() {
3662 luma.commit(x, y, side, &luma_new);
3663 (luma_new.levels.clone(), 0, 0.0)
3664 } else {
3665 commit_inter_luma(
3666 luma, (x, y), side, info.mv,
3667 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
3668 search, &luma_new, skip_new, fctx,
3669 )
3670 };
3671 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
3672 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
3673 return (
3674 BlockCoeffs {
3675 luma: coeffs(&levels, side),
3676 u: coeffs(&u_new.levels, side / 2),
3677 v: coeffs(&v_new.levels, side / 2),
3678 mode: DC_PRED as u8,
3679 uv_mode: DC_PRED,
3680 skip: skip_new,
3681 eight: None,
3682 dv: None,
3683 palette: None,
3684 palette_uv: None,
3685 tx_depth,
3686 inter: Some(info),
3687 },
3688 cost + dcost,
3689 );
3690 }
3691 }
3692
3693 census_add(8, 1);
3694 if skip {
3695 census_add(10, 1);
3696 }
3697 if inter_cost >= intra_cost {
3698 census_add(9, 1);
3699 }
3700 if inter_cost < intra_cost {
3701 let (levels, tx_depth, dcost) = commit_inter_luma(
3702 luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, fctx,
3703 );
3704 chroma[0].commit(x / 2, y / 2, side / 2, &u);
3705 chroma[1].commit(x / 2, y / 2, side / 2, &v);
3706 (BlockCoeffs {
3707 luma: coeffs(&levels, side),
3708 u: coeffs(&u.levels, side / 2),
3709 v: coeffs(&v.levels, side / 2),
3710 mode: DC_PRED as u8,
3711 uv_mode: DC_PRED,
3712 skip,
3713 eight: None,
3714 dv: None,
3715 palette: None,
3716 palette_uv: None,
3717 tx_depth,
3718 inter: Some(InterInfo {
3719 ref1: None,
3720 mv1: (0, 0),
3721 ref_frame: crate::mvstack::LAST_FRAME,
3722 mode: InterMode::NearestMv,
3723 mv,
3724 ref_mv_idx: 0,
3725 }),
3726 }, inter_cost + dcost)
3727 } else {
3728 (intra_block, intra_cost)
3729 }
3730}
3731
3732/// Publishes one coded inter-frame block into the `mi` grid the next block's
3733/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
3734/// block casts no vote but is still a coded cell (see `code_square_inter`'s
3735/// note on `processed_rows`/`processed_cols`).
3736fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: Option<InterInfo>) {
3737 let info = match inter {
3738 Some(info) => MiInfo {
3739 is_inter: true,
3740 ref_frame: info.ref_frame,
3741 // A COMPOUND block votes with BOTH of its references and both of
3742 // its vectors, exactly as the tile writer publishes it: recording
3743 // a compound block as a single-reference one here left the
3744 // encoder's own grid disagreeing with the writer's from the first
3745 // compound block on, so every later stack it searched against was
3746 // not the stack the decoder derives.
3747 ref_frame1: info.ref1.unwrap_or(NO_REF1),
3748 mv1: mv16(info.mv1),
3749 mv: mv16(info.mv),
3750 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
3751 // side, compound modes 2/3/7 on the other.
3752 is_new_mv: matches!(
3753 info.mode,
3754 InterMode::NewMv
3755 | InterMode::NewNewMv
3756 | InterMode::NearestNewMv
3757 | InterMode::NewNearestMv
3758 ),
3759 size,
3760 size_h: size,
3761 is_global_mv0: false,
3762 is_global_mv1: false,
3763 },
3764 None => MiInfo {
3765 is_inter: false,
3766 ref_frame: -1,
3767 ref_frame1: NO_REF1,
3768 mv1: (0, 0),
3769 mv: (0, 0),
3770 is_new_mv: false,
3771 size,
3772 size_h: size,
3773 is_global_mv0: false,
3774 is_global_mv1: false,
3775 },
3776 };
3777 for dr in 0..usize::from(size) {
3778 for dc in 0..usize::from(size) {
3779 grid.set(mi_row + dr, mi_col + dc, info);
3780 }
3781 }
3782}
3783
3784/// The reconstructed samples one 32x32 square covers in all three planes, so
3785/// that a partition trial can be undone.
3786fn snapshot(
3787 luma: &Plane,
3788 chroma: &[Plane; 2],
3789 (x, y): (usize, usize),
3790 side: usize,
3791) -> [Vec<u8>; 3] {
3792 [
3793 luma.snapshot(x, y, side),
3794 chroma[0].snapshot(x / 2, y / 2, side / 2),
3795 chroma[1].snapshot(x / 2, y / 2, side / 2),
3796 ]
3797}
3798
3799/// Puts such a snapshot back.
3800fn restore(
3801 luma: &mut Plane,
3802 chroma: &mut [Plane; 2],
3803 (x, y): (usize, usize),
3804 side: usize,
3805 saved: &[Vec<u8>; 3],
3806) {
3807 luma.restore(x, y, side, &saved[0]);
3808 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
3809 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
3810}
3811
3812/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
3813/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
3814/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
3815/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
3816/// rule shared with the key-frame path, not a second one that could diverge.
3817fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
3818 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
3819 let dc_entry = dc_pos.map(|i| scored.remove(i));
3820 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
3821 scored.truncate(if dc_entry.is_some() {
3822 top_k.saturating_sub(1)
3823 } else {
3824 top_k
3825 });
3826 if let Some(dc_entry) = dc_entry {
3827 scored.push(dc_entry);
3828 }
3829 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
3830 modes.iter().copied().filter(|m| keep.contains(m)).collect()
3831}
3832
3833fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
3834 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
3835 [INTRA_MODE_CTX[usize::from(left_mode)]];
3836 std::array::from_fn(|mode| {
3837 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
3838 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
3839 } else {
3840 0.0
3841 };
3842 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
3843 })
3844}
3845
3846/// What the luma mode search picks between, and under what terms.
3847struct Search<'a> {
3848 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
3849 /// luma search then offers a palette candidate beside the intra modes.
3850 screen: bool,
3851 base_q_idx: u8,
3852 deadzone: f64,
3853 lambda: f64,
3854 modes: &'a [u8],
3855 /// How many of `modes` the full RD trial (forward transform, quantize,
3856 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
3857 /// pre-pass on the prediction residual alone plus DC (always kept, since
3858 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
3859 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
3860 /// mode through full RD, unchanged from before this lever.
3861 top_k: Option<usize>,
3862}
3863
3864/// [`Search::top_k`]'s value: `None` keeps every mode's search unchanged
3865/// (the default, until a lever's quality gate justifies pruning by default);
3866/// `EC_AV1_PRUNE_K` sweeps it in a test build without touching callers.
3867fn prune_top_k() -> Option<usize> {
3868 #[cfg(test)]
3869 {
3870 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
3871 return k;
3872 }
3873 }
3874 let swept = std::env::var("EC_AV1_PRUNE_K")
3875 .ok()
3876 .and_then(|v| v.parse::<usize>().ok());
3877 match swept {
3878 Some(k) if cfg!(test) => Some(k),
3879 _ => PRUNE_TOP_K,
3880 }
3881}
3882
3883// A per-thread override [`prune_top_k`] checks first, so one test can sweep
3884// `top_k` in-process without mutating the environment (forbidden here --
3885// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
3886#[cfg(test)]
3887thread_local! {
3888 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
3889 const { std::cell::Cell::new(None) };
3890}
3891
3892#[cfg(test)]
3893fn set_test_top_k_override(value: Option<usize>) {
3894 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
3895}
3896
3897/// The default: unpruned, thirteen full trials per block, same as before this
3898/// lever. Set from the sweep in the lane report if the quality gate clears it.
3899const PRUNE_TOP_K: Option<usize> = None;
3900
3901/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
3902/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
3903/// quality gates were measured separately and may land on different
3904/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
3905/// [`EC_AV1_PRUNE_K`] or the key-frame path.
3906fn prune_top_k_inter() -> Option<usize> {
3907 #[cfg(test)]
3908 {
3909 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
3910 return k;
3911 }
3912 }
3913 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
3914 .ok()
3915 .and_then(|v| v.parse::<usize>().ok());
3916 match swept {
3917 Some(k) if cfg!(test) => Some(k),
3918 _ => INTER_PRUNE_TOP_K,
3919 }
3920}
3921
3922// A per-thread override [`prune_top_k_inter`] checks first, same reason as
3923// [`TEST_TOP_K_OVERRIDE`].
3924#[cfg(test)]
3925thread_local! {
3926 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
3927 const { std::cell::Cell::new(None) };
3928}
3929
3930#[cfg(test)]
3931fn set_test_top_k_override_inter(value: Option<usize>) {
3932 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
3933}
3934
3935/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
3936/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
3937/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
3938/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
3939/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
3940/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
3941/// pruning them costs less quality here.
3942const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
3943
3944// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
3945// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
3946// inter frame's cost can be attributed to a bucket without changing what
3947// the search actually does. Index: 0 = whole-call time inside
3948// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
3949// [`crate::mc::predict`] (every call, from the motion search's own
3950// candidates and from a committed inter block's final prediction alike),
3951// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
3952#[cfg(test)]
3953thread_local! {
3954 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
3955 std::cell::Cell::new(0),
3956 std::cell::Cell::new(0),
3957 std::cell::Cell::new(0),
3958 std::cell::Cell::new(0),
3959 ];
3960}
3961
3962#[cfg(test)]
3963pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
3964 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
3965}
3966
3967#[cfg(test)]
3968fn stage_reset() {
3969 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
3970}
3971
3972#[cfg(test)]
3973fn stage_read() -> [std::time::Duration; 4] {
3974 STAGE_NS.with(|c| {
3975 c.each_ref()
3976 .map(|cell| std::time::Duration::from_nanos(cell.get()))
3977 })
3978}
3979
3980/// One mode's coding of one block, before it is committed.
3981#[derive(Clone)]
3982struct Trial {
3983 levels: Vec<i32>,
3984 reconstruction: Vec<u8>,
3985 sse: f64,
3986 bits: f64,
3987}
3988
3989/// The non-zero levels of a block, as the tile writer takes them.
3990fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
3991 levels
3992 .iter()
3993 .enumerate()
3994 .filter(|&(_, &level)| level != 0)
3995 .map(|(i, &level)| Coeff {
3996 row: (i / side) as u8,
3997 col: (i % side) as u8,
3998 level,
3999 })
4000 .collect()
4001}
4002
4003thread_local! {
4004 /// The tile grid the next frame is coded with, as `(TileColsLog2,
4005 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
4006 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
4007 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
4008 /// one tile per frame, what every caller that never arms anything gets
4009 /// and what every stream this crate wrote before tiles existed carries.
4010 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
4011}
4012
4013/// Arms this thread's next frame encodes with a tile grid (log2 counts).
4014pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
4015 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
4016}
4017
4018fn armed_tiles() -> (u32, u32) {
4019 let armed = TILE_LOG2.with(std::cell::Cell::get);
4020 if armed != (0, 0) {
4021 return armed;
4022 }
4023 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
4024 // (which codes through `encode_sequence`, not the facade) can measure what
4025 // a tile grid costs without a knob of its own -- same shape as
4026 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
4027 match std::env::var("EC_AV1_TILES").ok() {
4028 Some(v) if cfg!(test) => {
4029 let mut f = v.split(':');
4030 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
4031 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
4032 (cols, rows)
4033 }
4034 _ => armed,
4035 }
4036}
4037
4038/// Codes a frame's `tiles` tiles, each entirely on its own (see
4039/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
4040/// the crate's own pool, and hands back their payloads in tile order plus
4041/// whatever `code` returned for tile `store` -- the CDF state
4042/// `context_update_tile_id` names. The result cannot depend on the thread
4043/// count: each job writes one tile from the frame's own starting tables into
4044/// its own slot.
4045fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
4046where
4047 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
4048{
4049 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
4050 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
4051 let threads = crate::par::tile_threads().min(tiles);
4052 let mut slots: Vec<Slot> = Vec::new();
4053 if threads <= 1 {
4054 for index in 0..tiles {
4055 slots.push(Some(code(index)));
4056 }
4057 } else {
4058 let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
4059 {
4060 let batch = crate::par::Batch::new("ec-av1-tile");
4061 for (from, to) in crate::par::bands(tiles, threads) {
4062 let done = &done;
4063 let code = &code;
4064 batch.submit(move || {
4065 for index in from..to {
4066 let coded = code(index);
4067 done.lock().expect("tile slots")[index] = Some(coded);
4068 }
4069 });
4070 }
4071 }
4072 slots = done.into_inner().expect("tile slots");
4073 }
4074 let mut out = Vec::with_capacity(tiles);
4075 let mut stored = None;
4076 for (index, slot) in slots.into_iter().enumerate() {
4077 let (bytes, cdfs) = slot.expect("every tile was coded")?;
4078 if index == store {
4079 stored = cdfs;
4080 }
4081 out.push(bytes);
4082 }
4083 Ok((out, stored))
4084}
4085
4086/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
4087/// workers, and returns the results in tile order. The counterpart of
4088/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
4089/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
4090/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
4091/// availability is already tile-relative (`clip_planes_to_tile`,
4092/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
4093/// other tiles have run -- gated by
4094/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
4095/// covers the search as well as the write.
4096///
4097/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
4098/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
4099/// does it for the decoder's filter bands.
4100fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
4101where
4102 T: Send,
4103 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
4104{
4105 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
4106 let threads = crate::par::tile_threads().min(tiles);
4107 if threads <= 1 {
4108 return (0..tiles).map(|index| job(index, fctx)).collect();
4109 }
4110 type Slot<T> = Option<Result<T>>;
4111 let done: std::sync::Mutex<Vec<Slot<T>>> =
4112 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
4113 {
4114 let batch = crate::par::Batch::new("ec-av1-tile-search");
4115 for (from, to) in crate::par::bands(tiles, threads) {
4116 let done = &done;
4117 let job = &job;
4118 let ctx = crate::decode::filter_ctx_copy(fctx);
4119 batch.submit(move || {
4120 for index in from..to {
4121 let searched = job(index, &ctx);
4122 done.lock().expect("tile slots")[index] = Some(searched);
4123 }
4124 });
4125 }
4126 }
4127 done.into_inner()
4128 .expect("tile slots")
4129 .into_iter()
4130 .map(|slot| slot.expect("every tile was searched"))
4131 .collect()
4132}
4133
4134/// One tile job's own copy of a plane: the frame's source, a blank
4135/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
4136/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
4137/// of the frame's reconstruction because a tile's prediction never reads a
4138/// sample outside its own rectangle, and every sample inside it is written
4139/// before it is read.
4140fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
4141 Plane {
4142 source,
4143 reconstruction: vec![128; source.len()],
4144 width,
4145 height,
4146 true_width,
4147 true_height,
4148 tile_x0: 0,
4149 tile_y0: 0,
4150 tile_x1: width,
4151 tile_y1: height,
4152 }
4153}
4154
4155/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
4156/// the frame's plane, through the [`crate::par::Shared`] every job holds.
4157///
4158/// corner-cut: the disjointness that makes the aliasing sound is the caller's
4159/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
4160/// rectangles partition it -- checked end-to-end by
4161/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
4162/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
4163/// row-range `split_at_mut` plumbing through `Plane`, which would have to
4164/// thread an origin offset through every prediction and transform call site
4165/// for the same bytes.
4166#[allow(unsafe_code)]
4167fn copy_rect(
4168 dst: crate::par::Shared<'_, Vec<u8>>,
4169 src: &[u8],
4170 stride: usize,
4171 x0: usize,
4172 y0: usize,
4173 x1: usize,
4174 y1: usize,
4175) {
4176 // SAFETY: this job touches only its own tile rectangle (see above).
4177 let dst = unsafe { dst.get() };
4178 for y in y0..y1 {
4179 let (a, b) = (y * stride + x0, y * stride + x1);
4180 dst[a..b].copy_from_slice(&src[a..b]);
4181 }
4182}
4183
4184/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
4185/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
4186/// tables the frame stores (spec 7.20), which is what
4187/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
4188/// below publish.
4189fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
4190 ec_av1_syntax::TileInfo {
4191 uniform_spacing: true,
4192 cols: layout.cols(),
4193 rows: layout.rows(),
4194 cols_log2: layout.cols_log2,
4195 rows_log2: layout.rows_log2,
4196 mi_col_starts: layout.mi_col_starts(),
4197 mi_row_starts: layout.mi_row_starts(),
4198 context_update_tile_id: layout.largest_tile() as u32,
4199 tile_size_bytes,
4200 }
4201}
4202
4203/// Clips the three planes' intra edge reads to `rect`, the tile the
4204/// superblock about to be searched belongs to (the encoder side of the
4205/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
4206/// raster order -- which is a linear extension of every tile's own coding
4207/// order, so a block still only ever predicts from samples already
4208/// reconstructed -- and only availability is tile-relative.
4209fn clip_planes_to_tile(
4210 luma: &mut Plane<'_>,
4211 chroma: &mut [Plane<'_>; 2],
4212 rect: crate::tile::TileRect,
4213) {
4214 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
4215 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
4216 luma.set_tile(x0, y0, x1, y1);
4217 for plane in chroma.iter_mut() {
4218 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
4219 }
4220}
4221
4222/// Encodes one picture as a key frame.
4223///
4224/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
4225/// picks its coefficient CDFs from one of four q contexts by that index.
4226/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
4227/// smaller values trade fidelity for rate.
4228///
4229/// The picture may be any even width and height: the encoder pads it by edge
4230/// replication to a whole number of 32x32 blocks internally, and the frame it
4231/// writes crops back to the picture's own size (`render_width`/
4232/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
4233/// own size, never the padded one.
4234///
4235/// # Errors
4236/// Returns an error when the picture's width or height is zero or odd, or
4237/// when its planes are not 4:2:0 of that size.
4238/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
4239/// stream. The per-frame decode state this needs lives for exactly this call.
4240///
4241/// # Errors
4242/// Returns an error under the same conditions
4243/// [`encode_key_frame_with_modes`] does.
4244pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
4245 encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
4246}
4247
4248/// [`encode_key_frame`] with the per-block intra modes given rather than
4249/// searched.
4250///
4251/// # Errors
4252/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
4253/// is empty, or when a block's coefficients do not fit the coded frame.
4254pub fn encode_key_frame_with_modes(
4255 picture: &Picture,
4256 base_q_idx: u8,
4257 deadzone: f64,
4258 modes: &[u8],
4259) -> Result<Encoded> {
4260 encode_key_frame_with_modes_with_ctx(
4261 picture,
4262 base_q_idx,
4263 deadzone,
4264 modes,
4265 &crate::decode::FrameCtx::new(),
4266 )
4267}
4268
4269/// Codes `pictures` as one key frame followed by inter frames.
4270///
4271/// # Errors
4272/// Returns an error under the same conditions [`encode_key_frame`] and the
4273/// inter frame path do.
4274pub fn encode_sequence(
4275 pictures: &[Picture],
4276 base_q_idx: u8,
4277 deadzone: f64,
4278) -> Result<EncodedSequence> {
4279 encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
4280}
4281
4282pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
4283 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
4284}
4285
4286/// Encodes one picture as a key frame, choosing each block's luma mode from
4287/// `modes` alone.
4288///
4289/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
4290/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
4291/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
4292/// uses.
4293///
4294/// # Errors
4295/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
4296/// names a mode [`crate::intra::predict`] does not predict.
4297pub(crate) fn encode_key_frame_with_modes_with_ctx(
4298 picture: &Picture,
4299 base_q_idx: u8,
4300 deadzone: f64,
4301 modes: &[u8], fctx: &crate::decode::FrameCtx,
4302) -> Result<Encoded> {
4303 picture.check_even()?;
4304 let padded = picture.padded_to(BLOCK);
4305 let encoded = encode_key_frame_inner(
4306 &padded,
4307 base_q_idx,
4308 deadzone,
4309 modes,
4310 split_blocks(),
4311 (picture.width, picture.height),
4312 unspecified_color_config(), fctx,
4313 )?;
4314 Ok(crop_encoded(&encoded, picture.width, picture.height))
4315}
4316
4317/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
4318/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
4319/// already padded to a whole number of 32x32 blocks; `render` is the real
4320/// (pre-pad) size the frame header tells a decoder to crop back to.
4321pub(crate) fn encode_key_frame_inner(
4322 picture: &Picture,
4323 base_q_idx: u8,
4324 deadzone: f64,
4325 modes: &[u8],
4326 split_blocks: bool,
4327 render: (usize, usize),
4328 color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
4329) -> Result<Encoded> {
4330 picture.check()?;
4331 if modes.is_empty() {
4332 return Err(Error::unsupported(
4333 "AV1 encode",
4334 "a mode search needs at least one mode to choose from",
4335 ));
4336 }
4337 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
4338 return Err(Error::unsupported(
4339 "AV1 encode",
4340 format!("intra mode {bad} is not one the encoder predicts"),
4341 ));
4342 }
4343 // The header carries the frame's true (unpadded) size as `frame_width`/
4344 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
4345 // `mi_rows` derived from that same true size (spec `compute_image_size`).
4346 // `render_width`/`render_height` come out equal to it too, so
4347 // `render_and_frame_size_different` is false and no render_size bits are
4348 // written, mirroring libaom/rav1e: the padded `picture` below is only the
4349 // internal coding surface, never what the header names.
4350 // Screen-content detection runs on the SOURCE luma, before any header is
4351 // built: it decides this sequence's `seq_force_screen_content_tools` (and
4352 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
4353 // this frame's own `allow_screen_content_tools`.
4354 let screen = screen_content(
4355 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
4356 picture.width,
4357 (picture.width).min(render.0),
4358 (picture.height).min(render.1),
4359 );
4360 arm_seq_screen(screen);
4361 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
4362 // forces deblocking, CDEF and loop restoration OFF for this frame
4363 // (frame.rs:194/210/252/272), so it is only set when the source repeats
4364 // itself enough for the copied blocks to pay that back
4365 // ([`intrabc_worth_it`]).
4366 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
4367 // grid across every tile while this writer builds one per tile, so a
4368 // multi-tile allow_intrabc frame would predict its DVs off a different
4369 // grid than the decoder does. corner-cut, ceiling named: the upgrade
4370 // path is a frame-scoped grid shared by the tile writers.
4371 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
4372 intrabc_worth_it(
4373 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
4374 picture.width,
4375 picture.width.min(render.0),
4376 picture.height.min(render.1),
4377 )
4378 } else {
4379 (false, 0.0)
4380 };
4381 IBC_SHARE.with(|c| c.set(ibc_share));
4382 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
4383 header.allow_screen_content_tools = screen;
4384 header.allow_intrabc = allow_intrabc;
4385 header.render_width = render.0 as u32;
4386 header.render_height = render.1 as u32;
4387 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
4388 // its luma transform below its own side (`crate::tile::write_luma_select`).
4389 // Set here rather than in `key_frame_headers_colour` so the header
4390 // builders' other callers -- the hand-built tile writers, which code no
4391 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
4392 let tx_select = tx_select();
4393 if tx_select {
4394 header.tx_mode = TxMode::Select;
4395 }
4396 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
4397
4398 // Prediction reads no further than this, in each plane's own units --
4399 // see `Plane::true_width`/`true_height`.
4400 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
4401 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
4402 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
4403 // design (see `intra_predict_u8`'s doc comment), so narrow the source
4404 // once here.
4405 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
4406 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
4407 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
4408 let mut luma = Plane {
4409 source: &picture_y8,
4410 reconstruction: vec![128; picture_y8.len()],
4411 width: picture.width,
4412 height: picture.height,
4413 true_width,
4414 true_height,
4415 tile_x0: 0,
4416 tile_y0: 0,
4417 tile_x1: picture.width,
4418 tile_y1: picture.height,
4419 };
4420 let mut chroma = [
4421 Plane {
4422 source: &picture_u8,
4423 reconstruction: vec![128; picture_u8.len()],
4424 width: picture.width / 2,
4425 height: picture.height / 2,
4426 true_width: true_width / 2,
4427 true_height: true_height / 2,
4428 tile_x0: 0,
4429 tile_y0: 0,
4430 tile_x1: picture.width / 2,
4431 tile_y1: picture.height / 2,
4432 },
4433 Plane {
4434 source: &picture_v8,
4435 reconstruction: vec![128; picture_v8.len()],
4436 width: picture.width / 2,
4437 height: picture.height / 2,
4438 true_width: true_width / 2,
4439 true_height: true_height / 2,
4440 tile_x0: 0,
4441 tile_y0: 0,
4442 tile_x1: picture.width / 2,
4443 tile_y1: picture.height / 2,
4444 },
4445 ];
4446
4447 // The search trades a bit for the squared error it saves, in the units the
4448 // reconstruction is measured in: one step of the quantizer, squared.
4449 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
4450 let search = Search {
4451 base_q_idx,
4452 deadzone,
4453 lambda: lambda_scale() * step * step,
4454 modes,
4455 top_k: prune_top_k(),
4456 screen,
4457 };
4458
4459 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
4460 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
4461 // which may be fewer columns/rows than the padded picture has room for
4462 // -- a block whose origin sits past the true bound is not coded at all,
4463 // matching what a decoder derives from `frame_width`/`frame_height` and
4464 // so never visits either.
4465 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
4466 let (cols, rows) = (cols as usize, rows as usize);
4467 // The luma mode of the block above and of the block to the left, which is
4468 // what picks the CDF the next block's mode is coded against -- the same
4469 // bookkeeping the tile writer keeps, so that the search is costing the
4470 // symbol the writer will actually write.
4471 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
4472 // because a 32x32 block may be split into four 16x16 ones.
4473 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
4474 // This frame's tile grid (one tile unless the facade armed more).
4475 let layout =
4476 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
4477 header.tile_info = tile_info_of(&layout, 1);
4478 // The filter search re-decodes this frame's tiles; the decoder derives
4479 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
4480 // `mi_row_starts`), which is what makes the writer's rects and the
4481 // reader's the same rects.
4482 let header_tile_info = header.tile_info.clone();
4483 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
4484 // once over the whole frame. Each tile job builds its own reconstruction
4485 // planes and its own `above_mode`/`left_mode` bands, which is also what
4486 // the tile writer reads -- a tile resets its neighbour contexts (spec
4487 // 5.11.1), so a block at a tile's left edge must cost its mode against
4488 // the default context, not against whatever the tile to its west left in
4489 // that row. At one tile the bands are the frame's, exactly as before.
4490 let (frame_width, frame_height) = (picture.width, picture.height);
4491 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
4492 let [cb, cr] = &mut chroma;
4493 let chroma_out = [
4494 crate::par::Shared::new(&mut cb.reconstruction),
4495 crate::par::Shared::new(&mut cr.reconstruction),
4496 ];
4497 let search_tile = |index: usize,
4498 fctx: &crate::decode::FrameCtx|
4499 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
4500 let rect = layout.rect(index);
4501 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
4502 let mut chroma = [
4503 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
4504 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
4505 ];
4506 clip_planes_to_tile(&mut luma, &mut chroma, rect);
4507 let mut above_mode = vec![DC_PRED; cols * 2];
4508 let mut left_mode = vec![DC_PRED; rows * 2];
4509 let mut ibc = allow_intrabc.then(|| {
4510 Ibc::new(
4511 (
4512 rect.mi_col0 as usize * 4,
4513 rect.mi_row0 as usize * 4,
4514 (rect.mi_col1 as usize * 4).min(true_width),
4515 (rect.mi_row1 as usize * 4).min(true_height),
4516 ),
4517 &picture_y8,
4518 frame_width,
4519 )
4520 });
4521 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
4522 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
4523 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
4524 let mut modes = Vec::with_capacity(4);
4525 // The quadrants of a superblock are coded in the order the decoder
4526 // walks them, which for a 64x64 split into 32x32 blocks is raster
4527 // order among the quadrants that are inside the frame.
4528 let mut blocks = Vec::with_capacity(4);
4529 for quadrant in 0..4 {
4530 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
4531 if col >= cols || row >= rows {
4532 continue;
4533 }
4534 let (x, y) = (col * BLOCK, row * BLOCK);
4535 let (c0, r0) = (col * 2, row * 2);
4536 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
4537
4538 // spec `decode_partition`'s hasRows/hasCols recomputed at this
4539 // 32x32 block's own half (see `crate::tile::has_half`): the
4540 // true frame edge can fall inside a quadrant a superblock-level
4541 // check already let through. A quadrant that fails either may
4542 // not be left whole; a 16x16 sub-block that fails either (once
4543 // split) is a leaf this writer has no rectangular transform
4544 // for, so the search must not pick a split that would need one.
4545 let (has_cols32, has_rows32) = (
4546 crate::tile::has_half(
4547 col as u32 * crate::tile::BLOCK_MI,
4548 crate::tile::BLOCK_MI,
4549 header.mi_cols,
4550 ),
4551 crate::tile::has_half(
4552 row as u32 * crate::tile::BLOCK_MI,
4553 crate::tile::BLOCK_MI,
4554 header.mi_rows,
4555 ),
4556 );
4557 let whole_legal = has_cols32 && has_rows32;
4558 // A 16x16 sub-block's own hasCols/hasRows (spec
4559 // `decode_partition`, recomputed at this leaf's own half): one
4560 // axis false is a straddling leaf this writer codes as two
4561 // 8x8 leaves (`crate::tile::write_leaf8`, lane-av1-rect r7);
4562 // both axes false needs a rectangular transform this writer
4563 // has no size for at all, whether whole or split.
4564 let sub_half = |sr: usize, sc: usize| {
4565 (
4566 crate::tile::has_half(
4567 sc as u32 * crate::tile::SUB_MI,
4568 crate::tile::SUB_MI,
4569 header.mi_cols,
4570 ),
4571 crate::tile::has_half(
4572 sr as u32 * crate::tile::SUB_MI,
4573 crate::tile::SUB_MI,
4574 header.mi_rows,
4575 ),
4576 )
4577 };
4578 let both_axes_cut = (0..4)
4579 .map(|i| (r0 + i / 2, c0 + i % 2))
4580 .filter(|&(sr, sc)| {
4581 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
4582 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
4583 })
4584 .any(|(sr, sc)| {
4585 let (has_cols16, has_rows16) = sub_half(sr, sc);
4586 !has_cols16 && !has_rows16
4587 });
4588 if !whole_legal && both_axes_cut {
4589 return Err(Error::unsupported(
4590 "AV1 encode",
4591 format!(
4592 "the 32x32 block at ({col},{row}) straddles the true frame edge \
4593 in a way that needs a rectangular (HORZ/VERT) transform this \
4594 encoder does not code yet"
4595 ),
4596 ));
4597 }
4598
4599 // What the whole 32x32 costs, including the partition symbol
4600 // that says it is not split.
4601 let (whole, mut cost_whole) = code_square(
4602 &mut luma,
4603 &mut chroma,
4604 (x, y),
4605 BLOCK,
4606 &search,
4607 &mode_bits(above_mode[c0], left_mode[r0]),
4608 tx_select,
4609 ibc.as_mut(), fctx,
4610 );
4611 cost_whole += search.lambda * partition_bits(BLOCK, false);
4612 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
4613
4614 // What four 16x16 blocks cost instead, each searched against
4615 // the reconstruction the ones before it left.
4616 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
4617 let mut split = Vec::with_capacity(4);
4618 let mut cost_split = search.lambda
4619 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
4620 let mut split_modes = Vec::with_capacity(4);
4621 for sub in 0..4 {
4622 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
4623 // Same filter as the writer's `sub_positions` (spec
4624 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
4625 // return): a sub-block whose own origin sits past the
4626 // true frame is never coded, so it must not be searched
4627 // or pushed onto `split` either, or the writer's block
4628 // count will not match what it is prepared to name.
4629 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
4630 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
4631 {
4632 continue;
4633 }
4634 let (has_cols16, has_rows16) = sub_half(sr, sc);
4635 if has_cols16 && has_rows16 {
4636 let (block, cost) = code_square(
4637 &mut luma,
4638 &mut chroma,
4639 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
4640 SUB,
4641 &search,
4642 &mode_bits(above_mode[sc], left_mode[sr]),
4643 tx_select,
4644 ibc.as_mut(), fctx,
4645 );
4646 cost_split += cost;
4647 split_modes.push(block.mode);
4648 above_mode[sc] = block.mode;
4649 left_mode[sr] = block.mode;
4650 split.push(block);
4651 } else {
4652 // A straddling 16x16: two (or, at a true corner, one)
4653 // 8x8 leaves, in the raster order `write_leaf8`'s
4654 // caller expects. Both leaves cost against the SAME
4655 // enclosing-slot mode context (see
4656 // `crate::tile::write_leaf8`'s doc), and neither
4657 // updates `above_mode`/`left_mode` at this SUB slot --
4658 // the writer never does either, so the search must
4659 // not diverge from what it will actually read next.
4660 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
4661 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
4662 let mut leaves = Vec::with_capacity(2);
4663 for i in 0..4 {
4664 let leaf_x = x_sub + (i % 2) * 8;
4665 let leaf_y = y_sub + (i / 2) * 8;
4666 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
4667 continue;
4668 }
4669 let (leaf, cost) = code_square(
4670 &mut luma,
4671 &mut chroma,
4672 (leaf_x, leaf_y),
4673 8,
4674 &search,
4675 &leaf_mode_bits,
4676 tx_select,
4677 None, fctx,
4678 );
4679 cost_split += cost;
4680 split_modes.push(leaf.mode);
4681 leaves.push(leaf);
4682 }
4683 split.push(BlockCoeffs {
4684 eight: Some(leaves),
4685 ..BlockCoeffs::default()
4686 });
4687 }
4688 }
4689
4690 // A split whose subs are all whole 16x16 is a real quality
4691 // alternative to `whole`, exactly as before. Through r14, a
4692 // split carrying an 8x8-leaf sub was only ever forced
4693 // (`!whole_legal`), never chosen on cost, because the leaf
4694 // path was not yet proven against a real decoder; r15 proved
4695 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
4696 // the read path (`decode_leaf8`), so leaf8 can now win on
4697 // cost anywhere, same as any other split.
4698 if !whole_legal || (split_blocks && cost_split < cost_whole) {
4699 modes.extend_from_slice(&split_modes);
4700 blocks.push(Quadrant::Split(split));
4701 } else {
4702 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
4703 for cell in 0..2 {
4704 above_mode[c0 + cell] = whole.mode;
4705 left_mode[r0 + cell] = whole.mode;
4706 }
4707 modes.push(whole.mode);
4708 blocks.push(Quadrant::Whole(whole));
4709 }
4710 }
4711 coded.push((sb_row * sb_cols + sb_col, Superblock::Split(blocks), modes));
4712 }
4713 }
4714 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
4715 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
4716 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
4717 for (&out, tile) in chroma_out.iter().zip(&chroma) {
4718 copy_rect(
4719 out,
4720 &tile.reconstruction,
4721 frame_width / 2,
4722 x0 / 2,
4723 y0 / 2,
4724 x1.div_ceil(2),
4725 y1.div_ceil(2),
4726 );
4727 }
4728 Ok(coded)
4729 };
4730 let searched = search_tiles(layout.count(), fctx, search_tile)?;
4731 // Back into frame raster order: the tile writer indexes `superblocks` by
4732 // the frame's own superblock index, and `modes` is the coding order the
4733 // ablation drivers read.
4734 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
4735 for (at, superblock, block_modes) in searched.into_iter().flatten() {
4736 in_order[at] = Some((superblock, block_modes));
4737 }
4738 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
4739 let mut modes = Vec::with_capacity(cols * rows);
4740 for slot in in_order {
4741 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
4742 superblocks.push(superblock);
4743 modes.extend_from_slice(&block_modes);
4744 }
4745
4746 #[cfg(test)]
4747 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
4748 // A key frame always starts from the defaults (`primary_ref_frame` is
4749 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
4750 // set, so what it stores into the slots it refreshes is exactly those
4751 // defaults again (spec 7.20's `started_from` arm) -- the first inter
4752 // frame after it therefore starts from the defaults too.
4753 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
4754 let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
4755 let start_cdfs = CdfSnapshot(cdfs);
4756 // The luma restoration-unit grid this frame's `lr_params` implies
4757 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
4758 // swallowed by the one before it), for the tile writer's own per-unit
4759 // walk.
4760 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
4761 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
4762 // Every tile is coded from this frame's OWN starting tables and leaves
4763 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
4764 // loop-restoration reference and its neighbour contexts), so the tiles
4765 // are independent of each other and of the order they are written in.
4766 let code_tiles = |bits: u8,
4767 sb_cols: usize,
4768 grid: &[u8],
4769 units: &[Option<crate::restoration::WienerInfo>]|
4770 -> Result<Vec<Vec<u8>>> {
4771 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
4772 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
4773 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
4774 let mut cdfs = start_cdfs.0.clone();
4775 crate::tile::arm_screen(screen);
4776 crate::tile::arm_intrabc(allow_intrabc);
4777 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
4778 mi_cols,
4779 mi_rows,
4780 base_q_idx,
4781 &superblocks,
4782 tx_select,
4783 &mut cdfs,
4784 layout.rect(index),
4785 )?;
4786 Ok((bytes, None))
4787 })?;
4788 Ok(out)
4789 };
4790 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
4791 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
4792 // the tile just coded back to the decoder under each candidate (see
4793 // `crate::filter_search`), and keep the filtered picture that wins as
4794 // the reconstruction -- what a decoder outputs, and what the next
4795 // frame predicts from.
4796 pick_and_apply_filters(
4797 &mut header,
4798 &mut luma,
4799 &mut chroma,
4800 [&picture_y8, &picture_u8, &picture_v8],
4801 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
4802 // and loop restoration off and codes none of their parameters
4803 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
4804 // the encoder's reconstruction is already what a decoder produces.
4805 !allow_intrabc,
4806 &mut tiles,
4807 search.lambda,
4808 fctx,
4809 // Every re-code starts from this frame's OWN starting tables, never
4810 // from where the first write left them: the second tile is the same
4811 // symbol sequence plus new ones, so it must adapt from the same
4812 // point the decoder will.
4813 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
4814 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
4815 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
4816 crate::decode::decode_key_frame_tiles_lr(
4817 &payloads,
4818 &header_tile_info,
4819 h.mi_cols,
4820 h.mi_rows,
4821 base_q_idx,
4822 h.frame_width,
4823 h.frame_height,
4824 seq.enable_filter_intra,
4825 cdef,
4826 lf,
4827 tx_select,
4828 h.reduced_tx_set,
4829 h.allow_screen_content_tools,
4830 h.allow_intrabc,
4831 lr,
4832 fctx,
4833 )
4834 },
4835 )?;
4836 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
4837 header.tile_info.tile_size_bytes = tile_size_bytes;
4838 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
4839 let mut stream = temporal_delimiter();
4840 stream.extend_from_slice(&sequence_header_obu(&seq)?);
4841 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
4842
4843 let [u, v] = chroma;
4844 Ok(Encoded {
4845 stream,
4846 modes,
4847 inter_block_share: 0.0,
4848 reconstruction: Picture {
4849 width: luma.width,
4850 height: luma.height,
4851 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
4852 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
4853 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
4854 },
4855 tile,
4856 mi_cols: header.mi_cols,
4857 mi_rows: header.mi_rows,
4858 base_q_idx,
4859 tx_select,
4860 screen,
4861 next_cdfs: start_cdfs.clone(),
4862 start_cdfs,
4863 loop_filter: header.loop_filter,
4864 cdef: header.cdef,
4865 loop_restoration: header.loop_restoration,
4866 allow_intrabc,
4867 })
4868}
4869
4870/// Chooses this frame's deblocking levels and CDEF strengths, writes them
4871/// into `header` and
4872/// replaces the frame's own region of the encoder's reconstruction with the
4873/// filtered picture the decoder produced under them
4874/// ([`crate::filter_search::pick_deblock`]).
4875///
4876/// `search == false` leaves the header at level 0 (deblocking off) and the
4877/// reconstruction untouched: the caller's stream is one this crate's own
4878/// decoder cannot read back, so there is nothing to search against.
4879///
4880/// # Errors
4881/// The decoder's own error, when it refuses the tile the encoder just wrote
4882/// -- that is an encoder defect, not a filter one, so it is propagated
4883/// rather than swallowed into "no deblocking".
4884fn pick_and_apply_filters(
4885 header: &mut FrameHeader,
4886 luma: &mut Plane<'_>,
4887 chroma: &mut [Plane<'_>; 2],
4888 source: [&[u8]; 3],
4889 search: bool,
4890 // The coded tiles, one payload per tile of the frame's grid, replaced in
4891 // place when the search chooses a per-64x64 `cdef_idx` list
4892 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
4893 // tile is written a second time under `recode` and the winner
4894 // re-decoded from them.
4895 tiles: &mut Vec<Vec<u8>>,
4896 lambda: f64,
4897 fctx: &crate::decode::FrameCtx,
4898 recode: impl Fn(
4899 u8,
4900 usize,
4901 &[u8],
4902 &[Option<crate::restoration::WienerInfo>],
4903 ) -> Result<Vec<Vec<u8>>>,
4904 decode: impl Fn(
4905 &LoopFilterParams,
4906 &CdefParams,
4907 &FrameHeader,
4908 &[Vec<u8>],
4909 &LoopRestorationParams,
4910 ) -> Result<Picture>,
4911) -> Result<()> {
4912 if !search {
4913 return Ok(());
4914 }
4915 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
4916 let hdr = header.clone();
4917 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
4918 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
4919 let damping = 3 + (header.quantization.base_q_idx >> 6);
4920 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
4921 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
4922 let none_lr = LoopRestorationParams::default();
4923 // Every candidate scores the same coded tile: decode it once and re-run
4924 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
4925 // the encoder's profile before this). The per-64x64 error the CDEF
4926 // preset search reads comes off the REPLAYED picture, which is the same
4927 // picture a decode produces -- that is what the replay is pinned on.
4928 crate::decode::clear_filter_replay();
4929 // lane-av1fpar: the per-tile search is over, so every core is idle from
4930 // here to the end of the frame -- band each candidate's deblock/CDEF
4931 // replay, the capture decode's own filter chain and the loop-restoration
4932 // passes across the same workers the search used.
4933 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
4934 let ft = crate::par::timer(crate::par::S_FILTER);
4935 let search_result = crate::filter_search::pick_filters(
4936 |lf, cdef| {
4937 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
4938 return Ok(picture);
4939 }
4940 crate::decode::arm_filter_replay();
4941 let _t = crate::par::timer(crate::par::S_FIRST);
4942 decode(lf, cdef, &hdr, tiles, &none_lr)
4943 },
4944 source,
4945 luma.width,
4946 (fw, fh),
4947 damping,
4948 (sb_cols, sb_rows),
4949 lambda,
4950 );
4951 drop(ft);
4952 crate::decode::clear_filter_replay();
4953 let (lf, cdef, idx_grid, picture) = search_result?;
4954 header.loop_filter = lf;
4955 header.cdef = cdef;
4956 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
4957 // in the frame header, so a re-decode under candidate parameters cannot
4958 // search them the way deblocking and CDEF are searched above. What the
4959 // decoder hands back instead is its own filter chain's intermediates
4960 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
4961 // those, through the decoder's own Wiener kernel.
4962 //
4963 // The capture rides the decode this stage was already going to do: the
4964 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
4965 // decode of the tile as it stands. That decode's header still says
4966 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
4967 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
4968 // an approximation inside the SEARCH only; the reconstruction this
4969 // function ends up splicing is always a real decode of the real tile.
4970 let lr_on = restoration_enabled();
4971 fctx.capture_stages.set(lr_on);
4972 let mut filtered = if idx_grid.is_empty() {
4973 if lr_on {
4974 let _t = crate::par::timer(crate::par::S_CAPTURE);
4975 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
4976 } else {
4977 picture
4978 }
4979 } else {
4980 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
4981 let _t = crate::par::timer(crate::par::S_CAPTURE);
4982 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
4983 *tiles = coded;
4984 picture
4985 };
4986 fctx.capture_stages.set(false);
4987 let mut lr = LoopRestorationParams::default();
4988 if lr_on {
4989 let mut want = LoopRestorationParams {
4990 loop_restoration_size: [64, 64, 64],
4991 uses_lr: true,
4992 ..LoopRestorationParams::default()
4993 };
4994 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
4995 let lrt = crate::par::timer(crate::par::S_LR);
4996 let units = match crate::decode::take_filter_stages(fctx) {
4997 Some(stages) => crate::filter_search::pick_restoration(
4998 &stages,
4999 source[0],
5000 luma.width,
5001 (fw, fh),
5002 &want,
5003 lambda,
5004 fctx,
5005 ),
5006 None => Vec::new(),
5007 };
5008 // A frame no unit restores keeps `RESTORE_NONE` on every plane
5009 // rather than paying ~1 bit per 64x64 for a tile full of
5010 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
5011 // clip whose units never take a filter).
5012 drop(lrt);
5013 if units.iter().any(Option::is_some) {
5014 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
5015 let _t = crate::par::timer(crate::par::S_CAPTURE);
5016 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
5017 *tiles = coded;
5018 lr = want;
5019 }
5020 }
5021 header.loop_restoration = lr;
5022 let dec_cw = filtered.width.div_ceil(2);
5023 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
5024 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
5025 crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
5026 crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
5027 Ok(())
5028}
5029
5030/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
5031/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
5032/// since every block this crate's inter tile writer codes is 32x32.
5033const SIZE_GROUP_32: usize = 3;
5034
5035/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
5036/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
5037/// stack this encoder builds is ever asked to predict against.
5038const LAST_FRAME: i8 = 1;
5039
5040/// What an inter frame's intra branch spends to name each of the thirteen
5041/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
5042/// context, since an inter frame's intra blocks do not read their
5043/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
5044/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
5045/// state, so it is built once per frame.
5046fn inter_mode_bits() -> [f64; 13] {
5047 std::array::from_fn(|mode| {
5048 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
5049 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
5050 } else {
5051 0.0
5052 };
5053 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
5054 + angle
5055 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
5056 })
5057}
5058
5059/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
5060/// [`mc::predict`] takes, in the units of the plane it predicts into.
5061///
5062/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
5063/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
5064/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
5065/// domain. `luma` picks which.
5066fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
5067 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
5068}
5069
5070/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
5071/// that module): the magnitude an `MV_CLASS_n` component's own bits start
5072/// counting from.
5073fn mv_class_base(class: usize) -> i32 {
5074 if class == 0 { 0 } else { 2i32 << (class + 2) }
5075}
5076
5077/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
5078/// `tile::mv_class_of`.
5079fn mv_class_of(z: i32) -> usize {
5080 let mut class = 0;
5081 while class < 10 && mv_class_base(class + 1) <= z {
5082 class += 1;
5083 }
5084 class
5085}
5086
5087/// What [`crate::tile::write_mv_component`] (private to that module) would
5088/// spend coding one non-zero motion vector component, against the same
5089/// static default CDFs the writer starts a frame from — the same
5090/// static-table approximation [`mode_bits`] costs the luma mode symbol
5091/// through, not the tile writer's own adapting state, which this encoder has
5092/// no way to read without duplicating it block for block.
5093///
5094/// Returns `None` when `diff` needs the eighth-pel precision this crate's
5095/// frames never carry (`allow_high_precision_mv` is always off), which is
5096/// what [`round_to_valid_mv`] exists to avoid ever happening.
5097fn mv_component_bits(diff: i32) -> Option<f64> {
5098 let mag = diff.unsigned_abs() as i32;
5099 let z = mag - 1;
5100 if z & 1 == 0 {
5101 return None;
5102 }
5103 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
5104 let class = mv_class_of(z);
5105 bits += symbol_bits(&cdf::MV_CLASS, class);
5106 let local = z - mv_class_base(class);
5107 if class == 0 {
5108 let bit = (local >> 3) & 1;
5109 let fr = (local >> 1) & 3;
5110 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
5111 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
5112 } else {
5113 let d = local >> 3;
5114 let fr = (local >> 1) & 3;
5115 for i in 0..class {
5116 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
5117 }
5118 bits += symbol_bits(&cdf::MV_FR, fr as usize);
5119 }
5120 Some(bits)
5121}
5122
5123/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
5124/// own -- a second motion search per block against that reference's picture,
5125/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
5126/// off in a test build (what the lane measured both arms with).
5127fn extra_ref_new_mv() -> bool {
5128 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
5129 Some(v) if cfg!(test) => v != "0",
5130 _ => EXTRA_REF_NEW_MV,
5131 }
5132}
5133
5134/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
5135/// flat slot plan (`inter_frame_headers_slots`): every reference but
5136/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
5137/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
5138/// frame two back when there is one (otherwise it, too, names the key frame's
5139/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
5140pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
5141 let last = order_hint.wrapping_sub(1) & 0x7f;
5142 let alt = if has_altref {
5143 order_hint.wrapping_sub(2) & 0x7f
5144 } else {
5145 key_hint
5146 };
5147 [last, last, last, key_hint, last, last, alt]
5148}
5149
5150/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
5151/// header bit that lets each block choose between a single and a compound
5152/// reference. Off by default until compound prediction is measured to pay;
5153/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
5154/// runs as), and every block still codes SINGLE, so the only cost is one
5155/// `comp_mode` symbol per inter block.
5156const REFERENCE_SELECT: bool = true;
5157
5158/// [`REFERENCE_SELECT`], with the test-build environment override.
5159pub(crate) fn reference_select() -> bool {
5160 match std::env::var("EC_AV1_COMPOUND").ok() {
5161 Some(v) if cfg!(test) => v != "0",
5162 _ => REFERENCE_SELECT,
5163 }
5164}
5165
5166/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
5167/// per entry past `start`, `1` to advance and `0` to stop, at most two.
5168fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
5169 let mut bits = 0.0;
5170 let mut idx = start;
5171 while idx < start + 2 && stack.entries.len() > idx + 1 {
5172 let advance = idx < target;
5173 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
5174 if !advance {
5175 break;
5176 }
5177 idx += 1;
5178 }
5179 bits
5180}
5181
5182/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
5183/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
5184/// `assign_mv`), so the same vector costs a different residual from each.
5185fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
5186 let mut best: Option<(f64, u8)> = None;
5187 for idx in 0..3usize {
5188 if idx > 0 && stack.entries.len() <= idx {
5189 break;
5190 }
5191 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
5192 if let Some(b) = mv_residual_bits(mv, base) {
5193 let total = b + drl_bits_for(stack, 0, idx);
5194 if best.is_none_or(|(t, _)| total < t) {
5195 best = Some((total, idx as u8));
5196 }
5197 }
5198 }
5199 best
5200}
5201
5202/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
5203/// zero vector and the stack's own candidates. A neighbour block's vector is
5204/// where this block's motion most often already is, which is what pays for
5205/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
5206/// vs libaom for 0.2 s off a 6 s ladder).
5207fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
5208 let mut seeds = [(0, 0); 4];
5209 let mut n = 1;
5210 for e in stack.entries.iter().take(3) {
5211 seeds[n] = e.mv;
5212 n += 1;
5213 }
5214 (seeds, n)
5215}
5216
5217/// What [`crate::tile::write_mv`] (private to that module) would spend
5218/// coding `mv` as a residual against `pred`: the joint symbol naming which
5219/// components differ, then each differing component. `None` under the same
5220/// condition [`mv_component_bits`] returns `None`.
5221/// How many frames back `ref_frame` sits from the frame being coded, off the
5222/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
5223/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
5224/// what [`crate::motion::search`] scales its starting step by.
5225fn ref_distance(ref_frame: i8) -> u32 {
5226 let (bits, order_hint, hints) = crate::tile::order_hints();
5227 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
5228 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
5229 .unsigned_abs()
5230 .max(1);
5231 if crate::envflags::env_flag!("EC_TRACE_DIST") {
5232 eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]);
5233 }
5234 d
5235}
5236
5237fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
5238 let diff = (mv.0 - pred.0, mv.1 - pred.1);
5239 let joint = match (diff.0 != 0, diff.1 != 0) {
5240 (false, false) => 0,
5241 (false, true) => 1,
5242 (true, false) => 2,
5243 (true, true) => 3,
5244 };
5245 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
5246 for d in [diff.0, diff.1] {
5247 if d != 0 {
5248 bits += mv_component_bits(d)?;
5249 }
5250 }
5251 Some(bits)
5252}
5253
5254/// Rounds `mv` so that its residual against `pred` is one
5255/// [`crate::tile::write_mv_component`] can actually code: each component's
5256/// difference is either zero or has an even magnitude (the eighth-pel bit
5257/// `allow_high_precision_mv` off always infers as one forces the coded
5258/// magnitude odd one step further in, which comes out even here since this
5259/// crate's motion search works in whole units of that same step). Rounding
5260/// down keeps every coded MV — and so every `nearest_mv` a later block's
5261/// stack votes with — built from an even displacement from `(0, 0)`, so the
5262/// invariant holds without this function seeing the whole stack.
5263fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
5264 let round = |m: i32, p: i32| {
5265 let diff = m - p;
5266 let mag = diff.unsigned_abs() as i32;
5267 let even = mag - mag % 2;
5268 if even == 0 {
5269 p
5270 } else {
5271 p + even * diff.signum()
5272 }
5273 };
5274 (round(mv.0, pred.0), round(mv.1, pred.1))
5275}
5276
5277/// Predicts one `side`-square block by motion compensation from `reference`
5278/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
5279#[allow(clippy::too_many_arguments)]
5280fn mc_trial(
5281 plane: &Plane,
5282 x: usize,
5283 y: usize,
5284 side: usize,
5285 mv: (i32, i32),
5286 luma: bool,
5287 reference: &[u16],
5288 stride: usize,
5289 ref_width: usize,
5290 ref_height: usize,
5291 skip: bool,
5292 base_q_idx: u8,
5293 deadzone: f64,
5294 set: TxbSet, fctx: &crate::decode::FrameCtx,
5295) -> Trial {
5296 let x_q4 = mv_to_q4(x, mv.1, luma);
5297 let y_q4 = mv_to_q4(y, mv.0, luma);
5298 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
5299 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
5300 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
5301 // lane-av1speed: both buffers are per-candidate scratch on the hottest
5302 // path in the encoder, so they live on the stack -- `side` is at most
5303 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
5304 // per motion-compensated trial otherwise.
5305 let mut prediction16 = [0u16; BLOCK * BLOCK];
5306 let prediction16 = &mut prediction16[..side * side];
5307 mc::predict(
5308 reference,
5309 stride,
5310 ref_width,
5311 ref_height,
5312 x_q4,
5313 y_q4,
5314 side,
5315 side,
5316 prediction16, fctx,
5317 );
5318 let mut prediction = [0u8; BLOCK * BLOCK];
5319 let prediction = &mut prediction[..side * side];
5320 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
5321 *dst = src as u8;
5322 }
5323 plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set)
5324}
5325
5326/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
5327/// references predict into the `CONV_BUF` intermediate domain
5328/// ([`mc::predict_compound_intermediate`]) and are blended by
5329/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
5330/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
5331/// block, so the encoder's reconstruction is the decoder's.
5332#[allow(clippy::too_many_arguments)]
5333fn mc_trial_compound(
5334 plane: &Plane,
5335 x: usize,
5336 y: usize,
5337 side: usize,
5338 (mv0, mv1): ((i32, i32), (i32, i32)),
5339 luma: bool,
5340 ref0: (&[u16], usize, usize, usize),
5341 ref1: (&[u16], usize, usize, usize),
5342 base_q_idx: u8,
5343 deadzone: f64,
5344 set: TxbSet, fctx: &crate::decode::FrameCtx,
5345) -> Trial {
5346 let mut inter0 = [0i32; BLOCK * BLOCK];
5347 let mut inter1 = [0i32; BLOCK * BLOCK];
5348 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
5349 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
5350 mc::predict_compound_intermediate(
5351 r.0,
5352 r.1,
5353 r.2,
5354 r.3,
5355 mv_to_q4(x, mv.1, luma),
5356 mv_to_q4(y, mv.0, luma),
5357 mc::REF_NO_SCALE,
5358 side,
5359 side,
5360 mc::InterpFilterKind::Regular,
5361 mc::InterpFilterKind::Regular,
5362 dst,
5363 );
5364 }
5365 let mut blended16 = [0u16; BLOCK * BLOCK];
5366 let blended16 = &mut blended16[..side * side];
5367 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
5368 let mut prediction = [0u8; BLOCK * BLOCK];
5369 let prediction = &mut prediction[..side * side];
5370 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
5371 *dst = src as u8;
5372 }
5373 plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set)
5374}
5375
5376/// Codes one 32x32 block of an inter frame as whichever costs least of: each
5377/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
5378/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
5379/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
5380/// coding a real residual (`skip: false`) whenever one prices out cheaper
5381/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
5382/// missing inter `tx_type` symbol (the desync this function's candidates
5383/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
5384/// fixed.
5385///
5386/// The symbol costs this ranks candidates by use fixed contexts (0) for
5387/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
5388/// contexts for those come from its own neighbour bookkeeping
5389/// (`tile::Neighbours`), which is private to that module and not worth
5390/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
5391/// `drl_mode` contexts come straight from `stack`, which is exact, because
5392/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
5393/// the tile writer derives from the same grid state.
5394#[allow(clippy::too_many_arguments)]
5395fn search_inter_block(
5396 luma: &mut Plane,
5397 chroma: &mut [Plane; 2],
5398 (x, y): (usize, usize),
5399 search: &Search,
5400 mode_bits: &[f64; 13],
5401 reference: &Picture,
5402 stack: &MvStack,
5403 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
5404 // for the whole GOP, with the stack this block derives against it. Only
5405 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
5406 // second motion search would double the wall of the stage that already
5407 // owns most of it.
5408 extra: &[(i8, &Picture, &MvStack)],
5409 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
5410 // the caller off the same MI grid the tile writer will (empty unless the
5411 // frame carries `reference_select`).
5412 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)], fctx: &crate::decode::FrameCtx,
5413) -> (BlockCoeffs, f64) {
5414 // `luma_set` is the INTRA candidates' table; the two inter candidates
5415 // below price their coefficients through `TxbSet::Luma32Inter`, which is
5416 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
5417 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
5418 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
5419 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
5420
5421 // skip / intra_inter symbol costs at a fixed context -- see this
5422 // function's doc comment.
5423 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
5424 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
5425 // `write_single_ref`'s own tree, at the fixed context this pricer uses
5426 // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0 and GOLDEN
5427 // p1=0,p3=1,p5=1.
5428 let single_ref_bits = |ref_frame: i8| {
5429 symbol_bits(&cdf::SINGLE_REF[0][0], 0)
5430 + if ref_frame == crate::mvstack::GOLDEN_FRAME {
5431 symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1)
5432 } else {
5433 symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0)
5434 }
5435 };
5436
5437 struct Candidate {
5438 cost: f64,
5439 luma: Trial,
5440 u: Trial,
5441 v: Trial,
5442 mode: u8,
5443 skip: bool,
5444 inter: Option<InterInfo>,
5445 }
5446 let mut best: Option<Candidate> = None;
5447 let mut consider = |candidate: Candidate| {
5448 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
5449 best = Some(candidate);
5450 }
5451 };
5452
5453 // The chroma trial an intra candidate prices does not depend on `mode`
5454 // at all -- both planes always code `DC_PRED` here (a coding choice this
5455 // search inherited, not this loop's to second-guess) at the same `reach:
5456 // Reach::none()` -- so it is the same call with the same inputs on every
5457 // one of the thirteen iterations below; run it once and reuse the result
5458 // rather than repeat an already-priced transform/quantize/entropy call
5459 // twelve times for nothing (bit-identical: the value each iteration
5460 // reads back is exactly what it used to recompute).
5461 let u_trial = chroma[0].trial(
5462 At {
5463 x: x / 2,
5464 y: y / 2,
5465 side: BLOCK / 2,
5466 reach: Reach::none(),
5467 set: chroma_set,
5468 },
5469 DC_PRED,
5470 search.base_q_idx,
5471 search.deadzone, fctx,
5472 );
5473 let v_trial = chroma[1].trial(
5474 At {
5475 x: x / 2,
5476 y: y / 2,
5477 side: BLOCK / 2,
5478 reach: Reach::none(),
5479 set: chroma_set,
5480 },
5481 DC_PRED,
5482 search.base_q_idx,
5483 search.deadzone, fctx,
5484 );
5485
5486 let intra_modes: Vec<u8> = match search.top_k {
5487 Some(k) if k < search.modes.len() => {
5488 let scored = luma.intra_scores(
5489 At {
5490 x,
5491 y,
5492 side: BLOCK,
5493 reach,
5494 set: luma_set,
5495 },
5496 search.modes,
5497 mode_bits,
5498 search.lambda, fctx,
5499 );
5500 prune_by_sad(search.modes, scored, k)
5501 }
5502 _ => search.modes.to_vec(),
5503 };
5504 census_add(5, 1);
5505 census_add(6, intra_modes.len());
5506 for &mode in &intra_modes {
5507 let luma_trial = luma.trial(
5508 At {
5509 x,
5510 y,
5511 side: BLOCK,
5512 reach,
5513 set: luma_set,
5514 },
5515 mode,
5516 search.base_q_idx,
5517 search.deadzone, fctx,
5518 );
5519 let u = u_trial.clone();
5520 let v = v_trial.clone();
5521 let cost = luma_trial.sse
5522 + u.sse
5523 + v.sse
5524 + search.lambda
5525 * (luma_trial.bits
5526 + u.bits
5527 + v.bits
5528 + mode_bits[usize::from(mode)]
5529 + skip_bits(false)
5530 + intra_inter_bits(false));
5531 consider(Candidate {
5532 cost,
5533 luma: luma_trial,
5534 u,
5535 v,
5536 mode,
5537 skip: false,
5538 inter: None,
5539 });
5540 }
5541
5542 // The reference frame buffer a spec decoder holds is exactly the true
5543 // (unpadded) coded extent -- a superblock whose partition stops early at
5544 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
5545 // beyond it, so those samples are never part of the decoded picture.
5546 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
5547 // reference sample position clamp), not to this crate's own
5548 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
5549 // here would let a fractional-pel read past the true edge pick up this
5550 // encoder's own uncoded padding instead of the true edge's replicated
5551 // value a decoder computes.
5552 let ref_luma = (
5553 &reference.y,
5554 reference.width,
5555 luma.true_width,
5556 luma.true_height,
5557 );
5558 let ref_u = (
5559 &reference.u,
5560 reference.width / 2,
5561 chroma[0].true_width,
5562 chroma[0].true_height,
5563 );
5564 let ref_v = (
5565 &reference.v,
5566 reference.width / 2,
5567 chroma[1].true_width,
5568 chroma[1].true_height,
5569 );
5570 // Every single-reference mode the writer can code (spec 5.11.24's symbol
5571 // chain, mirrored by `tile::write_inter_mode`), priced with the static
5572 // CDFs at this block's own stack contexts. A candidate is a motion
5573 // vector plus the cheapest syntax that reaches it, so two modes landing
5574 // on the same vector share one set of trials: the added modes cost
5575 // mode-bit arithmetic, not another motion compensation.
5576 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
5577 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
5578 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
5579 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
5580 // the loop cannot reach is never offered below -- every candidate's
5581 // index is one this same loop walks to.
5582 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
5583 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME);
5584 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
5585 (
5586 stack.nearest_mv,
5587 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
5588 InterInfo {
5589 ref1: None,
5590 mv1: (0, 0),
5591 ref_frame: crate::mvstack::LAST_FRAME,
5592 mode: InterMode::NearestMv,
5593 mv: stack.nearest_mv,
5594 ref_mv_idx: 0,
5595 },
5596 ),
5597 // GLOBALMV is the identity model's zero vector -- this encoder writes
5598 // no `gm_params` -- and the cheapest syntax of the four on the static
5599 // content where that vector is also the right one.
5600 (
5601 (0, 0),
5602 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
5603 InterInfo {
5604 ref1: None,
5605 mv1: (0, 0),
5606 ref_frame: crate::mvstack::LAST_FRAME,
5607 mode: InterMode::GlobalMv,
5608 mv: (0, 0),
5609 ref_mv_idx: 0,
5610 },
5611 ),
5612 ];
5613 let near_bits =
5614 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
5615 for idx in 1..=2usize {
5616 if let Some(e) = stack.entries.get(idx) {
5617 cands.push((
5618 e.mv,
5619 near_bits + drl_bits(1, idx),
5620 InterInfo {
5621 ref1: None,
5622 mv1: (0, 0),
5623 ref_frame: crate::mvstack::LAST_FRAME,
5624 mode: InterMode::NearMv,
5625 mv: e.mv,
5626 ref_mv_idx: idx as u8,
5627 },
5628 ));
5629 }
5630 }
5631
5632 let source_block = luma.source_block(x, y, BLOCK);
5633 let (seeds, seed_n) = mv_seeds(stack);
5634 #[cfg(test)]
5635 let t = std::time::Instant::now();
5636 let found = motion::search(
5637 ref_luma.0,
5638 ref_luma.1,
5639 ref_luma.2,
5640 ref_luma.3,
5641 &source_block,
5642 x,
5643 y,
5644 BLOCK,
5645 BLOCK,
5646 stack.pred_mv,
5647 &seeds[..seed_n],
5648 search.lambda, fctx,
5649 1,
5650 );
5651 #[cfg(test)]
5652 stage_add(0, t.elapsed());
5653 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
5654 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
5655 // the same vector costs a different residual from each: take the index
5656 // whose residual plus DRL bits is cheapest, not entry 0 by default.
5657 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
5658 cands.push((
5659 mv,
5660 last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,
5661 InterInfo {
5662 ref1: None,
5663 mv1: (0, 0),
5664 ref_frame: crate::mvstack::LAST_FRAME,
5665 mode: InterMode::NewMv,
5666 mv,
5667 ref_mv_idx,
5668 },
5669 ));
5670 }
5671
5672 // Each extra reference's own `NEWMV` vector, for the compound
5673 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
5674 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
5675 for &(ref_frame, g, gstack) in extra {
5676 let g_ref_bits = single_ref_bits(ref_frame);
5677 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
5678 cands.push((
5679 gstack.nearest_mv,
5680 g_ref_bits
5681 + g_not_new
5682 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
5683 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
5684 InterInfo {
5685 ref1: None,
5686 mv1: (0, 0),
5687 ref_frame,
5688 mode: InterMode::NearestMv,
5689 mv: gstack.nearest_mv,
5690 ref_mv_idx: 0,
5691 },
5692 ));
5693 cands.push((
5694 (0, 0),
5695 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
5696 InterInfo {
5697 ref1: None,
5698 mv1: (0, 0),
5699 ref_frame,
5700 mode: InterMode::GlobalMv,
5701 mv: (0, 0),
5702 ref_mv_idx: 0,
5703 },
5704 ));
5705 // A motion search of this reference's own: without it, GOLDEN/ALTREF
5706 // can only be coded at a vector some neighbour already found, which
5707 // is why they carried a third of the inter blocks at their two
5708 // search-free modes alone.
5709 // The search is skipped when this reference's own NEARESTMV already
5710 // prices out `margin` times better than LAST's best vector does --
5711 // one candidate evaluation (`motion::cost_at`) standing in for a
5712 // whole search of ~50.
5713 let margin = extra_new_skip_margin();
5714 let skip_search = extra_ref_new_mv()
5715 && margin > 0.0
5716 && motion::cost_at(
5717 &g.y,
5718 g.width,
5719 luma.true_width,
5720 luma.true_height,
5721 &source_block,
5722 x,
5723 y,
5724 BLOCK,
5725 BLOCK,
5726 gstack.nearest_mv,
5727 gstack.pred_mv,
5728 search.lambda,
5729 fctx,
5730 ) * margin
5731 <= found.cost;
5732 if extra_ref_new_mv() && !skip_search {
5733 let (gseeds, gn) = mv_seeds(gstack);
5734 #[cfg(test)]
5735 let t = std::time::Instant::now();
5736 let gfound = motion::search(
5737 &g.y,
5738 g.width,
5739 luma.true_width,
5740 luma.true_height,
5741 &source_block,
5742 x,
5743 y,
5744 BLOCK,
5745 BLOCK,
5746 gstack.pred_mv,
5747 &gseeds[..gn],
5748 search.lambda, fctx,
5749 ref_distance(ref_frame),
5750 );
5751 #[cfg(test)]
5752 stage_add(0, t.elapsed());
5753 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
5754 extra_new_mvs.push((ref_frame, gmv));
5755 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
5756 cands.push((
5757 gmv,
5758 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
5759 InterInfo {
5760 ref1: None,
5761 mv1: (0, 0),
5762 ref_frame,
5763 mode: InterMode::NewMv,
5764 mv: gmv,
5765 ref_mv_idx,
5766 },
5767 ));
5768 }
5769 }
5770 }
5771
5772 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
5773 // trial set each: both references predict the block and the two
5774 // predictions are averaged, which is what pays on content where neither
5775 // reference alone is right. Priced with the same static-CDF approximation
5776 // the single-reference candidates use, plus the compound-only symbols
5777 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
5778 // The two compound-mode arms, each measured alone on the BD gate before
5779 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
5780 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
5781 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
5782 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
5783 let half_new = true;
5784 for (ref1, g, cstack) in compound {
5785 let (ref1, g) = (*ref1, *g);
5786 let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME)
5787 .contains(&ref1);
5788 let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
5789 + if uni {
5790 // LAST + a backward reference: `comp_ref_type` = bidirectional,
5791 // `comp_ref` LAST, `comp_bwdref` ALTREF.
5792 symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
5793 + symbol_bits(&cdf::COMP_REF[0][0], 0)
5794 + symbol_bits(&cdf::COMP_REF[0][1], 0)
5795 + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
5796 } else {
5797 // LAST + GOLDEN: unidirectional, `uni_comp_ref` p0/p1/p2.
5798 symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
5799 + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
5800 + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
5801 + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
5802 };
5803 let mode_ctx =
5804 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
5805 let mode_bits_of =
5806 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
5807 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
5808 (
5809 cstack.nearest_mv,
5810 mode_bits_of(0),
5811 InterInfo {
5812 ref_frame: crate::mvstack::LAST_FRAME,
5813 mode: InterMode::NearestNearestMv,
5814 mv: cstack.nearest_mv.0,
5815 mv1: cstack.nearest_mv.1,
5816 ref1: Some(ref1),
5817 ref_mv_idx: 0,
5818 },
5819 ),
5820 (
5821 ((0, 0), (0, 0)),
5822 mode_bits_of(6),
5823 InterInfo {
5824 ref_frame: crate::mvstack::LAST_FRAME,
5825 mode: InterMode::GlobalGlobalMv,
5826 mv: (0, 0),
5827 mv1: (0, 0),
5828 ref1: Some(ref1),
5829 ref_mv_idx: 0,
5830 },
5831 ),
5832 ];
5833 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
5834 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
5835 // the stack is deep enough for that walk to read one.
5836 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
5837 let drl = if cstack.entries.len() > 2 {
5838 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
5839 } else {
5840 0.0
5841 };
5842 ccands.push((
5843 (e.mv0, e.mv1),
5844 mode_bits_of(1) + drl,
5845 InterInfo {
5846 ref_frame: crate::mvstack::LAST_FRAME,
5847 mode: InterMode::NearNearMv,
5848 mv: e.mv0,
5849 mv1: e.mv1,
5850 ref1: Some(ref1),
5851 ref_mv_idx: 0,
5852 },
5853 ));
5854 }
5855 // The half-new modes and `NEW_NEWMV`, all seeded from the two
5856 // single-reference searches this block already ran -- no joint search
5857 // of its own. Every residual is priced against stack entry 0, which
5858 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
5859 let cbase = cstack
5860 .entries
5861 .first()
5862 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
5863 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
5864 ccands.push((
5865 (mv, cstack.nearest_mv.1),
5866 mode_bits_of(3) + b0,
5867 InterInfo {
5868 ref_frame: crate::mvstack::LAST_FRAME,
5869 mode: InterMode::NewNearestMv,
5870 mv,
5871 mv1: cstack.nearest_mv.1,
5872 ref1: Some(ref1),
5873 ref_mv_idx: 0,
5874 },
5875 ));
5876 }
5877 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
5878 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
5879 ccands.push((
5880 (cstack.nearest_mv.0, mv1),
5881 mode_bits_of(2) + b1,
5882 InterInfo {
5883 ref_frame: crate::mvstack::LAST_FRAME,
5884 mode: InterMode::NearestNewMv,
5885 mv: cstack.nearest_mv.0,
5886 mv1,
5887 ref1: Some(ref1),
5888 ref_mv_idx: 0,
5889 },
5890 ));
5891 }
5892 let base = cbase;
5893 if let (Some(b0), Some(b1)) = (
5894 mv_residual_bits(mv, base.0),
5895 mv_residual_bits(mv1, base.1),
5896 ) {
5897 ccands.push((
5898 (mv, mv1),
5899 mode_bits_of(7) + b0 + b1,
5900 InterInfo {
5901 ref_frame: crate::mvstack::LAST_FRAME,
5902 mode: InterMode::NewNewMv,
5903 mv,
5904 mv1,
5905 ref1: Some(ref1),
5906 ref_mv_idx: 0,
5907 },
5908 ));
5909 }
5910 }
5911 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
5912 ccands.dedup_by_key(|c| c.0);
5913 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
5914 let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height);
5915 let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height);
5916 for (mvs, bits, info) in ccands {
5917 let luma_trial = mc_trial_compound(
5918 luma, x, y, BLOCK, mvs, true,
5919 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
5920 search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx,
5921 );
5922 let u = mc_trial_compound(
5923 &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false,
5924 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
5925 search.base_q_idx, search.deadzone, chroma_set, fctx,
5926 );
5927 let v = mc_trial_compound(
5928 &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false,
5929 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
5930 search.base_q_idx, search.deadzone, chroma_set, fctx,
5931 );
5932 let skip = luma_trial.levels.iter().all(|&l| l == 0)
5933 && u.levels.iter().all(|&l| l == 0)
5934 && v.levels.iter().all(|&l| l == 0);
5935 let cost = luma_trial.sse
5936 + u.sse
5937 + v.sse
5938 + search.lambda
5939 * (skip_bits(skip)
5940 + intra_inter_bits(true)
5941 + bits
5942 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
5943 consider(Candidate {
5944 cost,
5945 luma: luma_trial,
5946 u,
5947 v,
5948 mode: DC_PRED,
5949 skip,
5950 inter: Some(info),
5951 });
5952 }
5953 }
5954
5955 // One trial set per distinct (reference, vector) pair: sort, cheapest
5956 // syntax first, and drop the rest of each pair's run.
5957 cands.sort_by(|a, b| {
5958 (a.2.ref_frame, a.0)
5959 .cmp(&(b.2.ref_frame, b.0))
5960 .then(a.1.total_cmp(&b.1))
5961 });
5962 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
5963 census_add(7, cands.len());
5964 {
5965 for (mv, mode_bits_inter, info) in cands {
5966 let (ref_luma, ref_u, ref_v) = match extra
5967 .iter()
5968 .find(|(r, _, _)| *r == info.ref_frame)
5969 {
5970 Some(&(_, g, _)) => (
5971 (&g.y, g.width, luma.true_width, luma.true_height),
5972 (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
5973 (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
5974 ),
5975 None => (ref_luma, ref_u, ref_v),
5976 };
5977 let luma_trial = mc_trial(
5978 luma,
5979 x,
5980 y,
5981 BLOCK,
5982 mv,
5983 true,
5984 ref_luma.0,
5985 ref_luma.1,
5986 ref_luma.2,
5987 ref_luma.3,
5988 false,
5989 search.base_q_idx,
5990 search.deadzone,
5991 TxbSet::Luma32Inter, fctx,
5992 );
5993 let u = mc_trial(
5994 &chroma[0],
5995 x / 2,
5996 y / 2,
5997 BLOCK / 2,
5998 mv,
5999 false,
6000 ref_u.0,
6001 ref_u.1,
6002 ref_u.2,
6003 ref_u.3,
6004 false,
6005 search.base_q_idx,
6006 search.deadzone,
6007 chroma_set, fctx,
6008 );
6009 let v = mc_trial(
6010 &chroma[1],
6011 x / 2,
6012 y / 2,
6013 BLOCK / 2,
6014 mv,
6015 false,
6016 ref_v.0,
6017 ref_v.1,
6018 ref_v.2,
6019 ref_v.3,
6020 false,
6021 search.base_q_idx,
6022 search.deadzone,
6023 chroma_set, fctx,
6024 );
6025 let skip = luma_trial.levels.iter().all(|&l| l == 0)
6026 && u.levels.iter().all(|&l| l == 0)
6027 && v.levels.iter().all(|&l| l == 0);
6028 let cost = luma_trial.sse
6029 + u.sse
6030 + v.sse
6031 + search.lambda
6032 * (skip_bits(skip)
6033 + intra_inter_bits(true)
6034 + mode_bits_inter
6035 + if skip {
6036 0.0
6037 } else {
6038 luma_trial.bits + u.bits + v.bits
6039 });
6040 consider(Candidate {
6041 cost,
6042 luma: luma_trial,
6043 u,
6044 v,
6045 mode: DC_PRED,
6046 skip,
6047 inter: Some(info),
6048 });
6049 }
6050 }
6051
6052 let best = best.expect("the search offers at least the intra modes");
6053 luma.commit(x, y, BLOCK, &best.luma);
6054 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
6055 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
6056 (
6057 BlockCoeffs {
6058 luma: coeffs(&best.luma.levels, BLOCK),
6059 u: coeffs(&best.u.levels, BLOCK / 2),
6060 v: coeffs(&best.v.levels, BLOCK / 2),
6061 mode: best.mode,
6062 uv_mode: DC_PRED,
6063 skip: best.skip,
6064 inter: best.inter,
6065 eight: None,
6066 dv: None,
6067 palette: None,
6068 palette_uv: None,
6069 tx_depth: 0,
6070 },
6071 best.cost,
6072 )
6073}
6074
6075/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
6076/// references name, which slot it refreshes, whether it is shown when it is
6077/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
6078/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
6079/// 0/2 alternation, every frame shown, every reference in the past).
6080///
6081/// The sign bias is carried rather than derived here because only the caller
6082/// knows what order hint each slot holds; it is armed onto the tile writer
6083/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
6084/// the writer scans the same stacks the decoder will.
6085#[derive(Debug, Clone, Copy)]
6086pub(crate) struct PyramidFrame {
6087 /// The slot `LAST_FRAME` (and every reference this encoder does not name
6088 /// apart) reads.
6089 pub last_slot: u8,
6090 /// The single slot `refresh_frame_flags` sets.
6091 pub self_slot: u8,
6092 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
6093 /// pyramid, which is what makes `sign_bias`'s last entry true.
6094 pub altref_slot: u8,
6095 /// `show_frame`: false for a hidden frame, output later by a
6096 /// `show_existing_frame` header.
6097 pub show_frame: bool,
6098 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
6099 pub sign_bias: crate::mvstack::SignBiasTable,
6100}
6101
6102/// Encodes one picture as an inter frame predicting from `reference`'s
6103/// reconstruction, which the caller decoded (or, for the frame right after
6104/// the key frame, is the key frame's own reconstruction).
6105pub(crate) fn encode_inter_frame(
6106 picture: &Picture,
6107 reference: &Picture,
6108 base_q_idx: u8,
6109 deadzone: f64,
6110 order_hint: u32,
6111 // The order hint each of the seven `ref_frame_idx` entries names, which a
6112 // decoder reads out of its own reference state -- only spec 5.9.22's
6113 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
6114 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
6115 // callers that follow this crate's own flat slot plan.
6116 order_hints: [u32; 7],
6117 render: (usize, usize),
6118 // The tables this frame's writer starts from: what the previous frame
6119 // stored into the slot this one's `primary_ref_frame` names. `None`
6120 // starts from the defaults, which is right only for the frame straight
6121 // after a key frame.
6122 start_cdfs: Option<&crate::cdf_state::Cdfs>,
6123 // The key frame's own (padded) reconstruction, which every frame of the
6124 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
6125 // with `LAST_FRAME` alone, exactly as before.
6126 golden: Option<&Picture>,
6127 // The frame two back, held in the slot this frame is about to refresh
6128 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
6129 // inter frames of a GOP, where the frame two back IS the key frame.
6130 altref: Option<&Picture>, fctx: &crate::decode::FrameCtx,
6131 // Where this frame sits in the coding-order pyramid; `None` is the flat
6132 // one-shown-frame-per-picture stream this encoder wrote before.
6133 pyramid: Option<PyramidFrame>,
6134) -> Result<Encoded> {
6135 picture.check()?;
6136 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
6137 return Err(Error::unsupported(
6138 "AV1 encode",
6139 "an inter frame is coded only for a picture that is a whole number \
6140 of 64x64 superblocks -- the inter tile writer never splits a \
6141 superblock's partition below that",
6142 ));
6143 }
6144 if reference.width != picture.width || reference.height != picture.height {
6145 return Err(Error::unsupported(
6146 "AV1 encode",
6147 "the reference picture must be the same size as the one being coded",
6148 ));
6149 }
6150
6151 // The single slot this crate's inter frames ever predict from or
6152 // refresh (`inter_frame_headers`'s contract): every frame both reads and
6153 // overwrites slot 0, so the frame just coded is always what the next one
6154 // predicts against.
6155 const LAST_SLOT: u8 = 0;
6156 // Slot 0 and slot 2 alternate so the frame two back survives one more
6157 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
6158 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
6159 // in the very slot it will overwrite.
6160 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
6161 let last_slot = pyramid.map_or(
6162 if order_hint <= 1 {
6163 LAST_SLOT
6164 } else if (order_hint - 1) % 2 == 1 {
6165 0
6166 } else {
6167 2
6168 },
6169 |p| p.last_slot,
6170 );
6171 // `render`, not `picture.width`/`picture.height`: `picture` here is
6172 // already padded to a whole number of superblocks (`encode_sequence`'s
6173 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
6174 // every true-edge clamp downstream) must come from the frame's real,
6175 // unpadded size, same as `key_frame_headers_colour` takes `render` and
6176 // not the padded picture in `encode_key_frame_inner`.
6177 let (seq, mut header) = inter_frame_headers_slots(
6178 render.0,
6179 render.1,
6180 base_q_idx,
6181 order_hint,
6182 last_slot,
6183 self_slot,
6184 match pyramid {
6185 Some(p) => p.altref_slot,
6186 None if altref.is_some() => self_slot,
6187 None => GOLDEN_SLOT,
6188 },
6189 )?;
6190 header.render_width = render.0 as u32;
6191 header.render_height = render.1 as u32;
6192 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
6193 // The order hint behind each `ref_frame_idx` entry. The flat path's own
6194 // slot plan (`inter_frame_headers_slots`) is: every reference but
6195 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
6196 // `ALTREF_FRAME`, which reads the frame two back when there is one;
6197 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
6198 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
6199 header.order_hints = order_hints;
6200 header.reference_select = reference_select();
6201 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
6202 // per-reference order-hint distance is read by the block SEARCH, which
6203 // runs long before the writer arms these (the distance-scaled search step
6204 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
6205 // never reached the tool).
6206 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
6207 if let Some(p) = pyramid {
6208 header.show_frame = p.show_frame;
6209 header.showable_frame = !p.show_frame;
6210 header.ref_frame_sign_bias = p.sign_bias;
6211 }
6212 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
6213 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
6214 // block inside this frame codes and searches its own `tx_depth`, the same
6215 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
6216 let tx_select = tx_select() && tx_select_inter();
6217 if tx_select {
6218 header.tx_mode = TxMode::Select;
6219 }
6220
6221 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
6222 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
6223 // here (see `encode_key_frame_inner`).
6224 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
6225 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
6226 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
6227 // This frame's own `allow_screen_content_tools`. It can only be set when
6228 // the SEQUENCE offers the bit at all, which is the key frame's decision
6229 // ([`SEQ_SCREEN`]): a frame header that contradicts
6230 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
6231 // encode.
6232 let screen = seq_screen()
6233 && screen_content(&picture_y8, picture.width, true_width, true_height);
6234 header.allow_screen_content_tools = screen;
6235 let mut luma = Plane {
6236 source: &picture_y8,
6237 reconstruction: vec![128; picture_y8.len()],
6238 width: picture.width,
6239 height: picture.height,
6240 true_width,
6241 true_height,
6242 tile_x0: 0,
6243 tile_y0: 0,
6244 tile_x1: picture.width,
6245 tile_y1: picture.height,
6246 };
6247 let mut chroma = [
6248 Plane {
6249 source: &picture_u8,
6250 reconstruction: vec![128; picture_u8.len()],
6251 width: picture.width / 2,
6252 height: picture.height / 2,
6253 true_width: true_width / 2,
6254 true_height: true_height / 2,
6255 tile_x0: 0,
6256 tile_y0: 0,
6257 tile_x1: picture.width / 2,
6258 tile_y1: picture.height / 2,
6259 },
6260 Plane {
6261 source: &picture_v8,
6262 reconstruction: vec![128; picture_v8.len()],
6263 width: picture.width / 2,
6264 height: picture.height / 2,
6265 true_width: true_width / 2,
6266 true_height: true_height / 2,
6267 tile_x0: 0,
6268 tile_y0: 0,
6269 tile_x1: picture.width / 2,
6270 tile_y1: picture.height / 2,
6271 },
6272 ];
6273
6274 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
6275 let search = Search {
6276 base_q_idx,
6277 deadzone,
6278 lambda: lambda_scale() * step * step,
6279 modes: &KEY_FRAME_MODES,
6280 top_k: prune_top_k_inter(),
6281 screen,
6282 };
6283 let mode_bits_table = inter_mode_bits();
6284
6285 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
6286 // coding surface's: `blocks` carries one entry per 32x32 block the tile
6287 // writer will actually visit, same count it checks `blocks.len()`
6288 // against, which is fewer than the padded surface's own block count
6289 // whenever the true size is not a 64x64 multiple.
6290 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
6291 let (cols, rows) = (cols as usize, rows as usize);
6292 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
6293 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
6294 // This frame's tile grid, as in `encode_key_frame_inner`.
6295 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
6296 let layout =
6297 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
6298 header.tile_info = tile_info_of(&layout, 1);
6299 let header_tile_info = header.tile_info.clone();
6300 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
6301 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
6302 // once per frame (lane-av1rd2), not once per block, which is a whole
6303 // plane's map per 32x32 block and now per leaf too.
6304 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
6305 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
6306 // availability -- intra edges and the MV stack's scans alike -- already
6307 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
6308 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
6309 // giving each job its own planes and its own `MiGrid` therefore leaves
6310 // every decision, and so every coded bit, exactly where the whole-frame
6311 // loop left it, at any tile count and any thread count.
6312 let (frame_width, frame_height) = (picture.width, picture.height);
6313 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
6314 let [cb, cr] = &mut chroma;
6315 let chroma_out = [
6316 crate::par::Shared::new(&mut cb.reconstruction),
6317 crate::par::Shared::new(&mut cr.reconstruction),
6318 ];
6319 let search_tile = |index: usize,
6320 fctx: &crate::decode::FrameCtx|
6321 -> Result<Vec<(usize, Quadrant)>> {
6322 // Thread-local, and this job may be running on a `search_tiles`
6323 // worker: `ref_distance`'s order-hint distance (the scaled motion
6324 // search step) is read by the SEARCH, so every worker arms it or the
6325 // tile's bits depend on the thread count.
6326 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
6327 let rect = layout.rect(index);
6328 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
6329 let mut chroma = [
6330 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
6331 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
6332 ];
6333 clip_planes_to_tile(&mut luma, &mut chroma, rect);
6334 let mut grid = MiGrid::new(mi_cols, mi_rows);
6335 grid.set_sign_bias(sign_bias);
6336 grid.set_tile_bounds(
6337 rect.mi_row0 as usize,
6338 rect.mi_col0 as usize,
6339 rect.mi_row1 as usize,
6340 rect.mi_col1 as usize,
6341 );
6342 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
6343 for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {
6344 for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {
6345 for quadrant in 0..4 {
6346 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
6347 // Same filter as the tile writer's: a quadrant whose own mi
6348 // origin is not inside the true frame is never coded.
6349 if r32 >= rows || c32 >= cols {
6350 continue;
6351 }
6352 // spec `decode_partition`'s hasRows/hasCols recomputed at this
6353 // 32x32 block's own half (`crate::tile::has_half`), same as
6354 // the key frame search: the true frame edge can fall inside a
6355 // quadrant a superblock-level check already let through, and
6356 // such a quadrant cannot be left whole -- it must split into
6357 // the 16x16 leaves that are actually inside the true frame
6358 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
6359 // arm).
6360 let (has_cols32, has_rows32) = (
6361 crate::tile::has_half(
6362 c32 as u32 * crate::tile::BLOCK_MI,
6363 crate::tile::BLOCK_MI,
6364 header.mi_cols,
6365 ),
6366 crate::tile::has_half(
6367 r32 as u32 * crate::tile::BLOCK_MI,
6368 crate::tile::BLOCK_MI,
6369 header.mi_rows,
6370 ),
6371 );
6372 if has_cols32 && has_rows32 {
6373 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
6374 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
6375 let stack =
6376 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
6377 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
6378 (crate::mvstack::GOLDEN_FRAME, golden),
6379 (crate::mvstack::ALTREF_FRAME, altref),
6380 ]
6381 .into_iter()
6382 .filter_map(|(r, pic)| {
6383 pic.map(|p| {
6384 (
6385 r,
6386 p,
6387 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
6388 )
6389 })
6390 })
6391 .collect();
6392 let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
6393 .iter()
6394 .map(|(r, p, st)| (*r, *p, st))
6395 .collect();
6396 // The COMPOUND stack of each `LAST` + extra pair, off the
6397 // same grid (and the same armed sign bias) the tile writer
6398 // rebuilds it from. Empty unless this frame codes
6399 // `reference_select`, which is what gates the syntax.
6400 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
6401 if header.reference_select {
6402 extra_stacks
6403 .iter()
6404 .map(|&(r, p, _)| {
6405 (
6406 r,
6407 p,
6408 crate::mvstack::find_mv_stack_compound(
6409 &grid,
6410 mi_row,
6411 mi_col,
6412 8,
6413 8,
6414 (crate::mvstack::LAST_FRAME, r),
6415 mi_cols,
6416 mi_rows,
6417 grid.sign_bias_table(),
6418 &[(0, 0); 7],
6419 None,
6420 ),
6421 )
6422 })
6423 .collect()
6424 } else {
6425 Vec::new()
6426 };
6427
6428 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
6429 let (block, mut cost_whole) = search_inter_block(
6430 &mut luma,
6431 &mut chroma,
6432 (x, y),
6433 &search,
6434 &mode_bits_table,
6435 reference,
6436 &stack,
6437 &extra,
6438 &compound, fctx,
6439 );
6440 cost_whole += search.lambda * partition_bits(BLOCK, false);
6441 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
6442
6443 // What four 16x16 leaves cost instead (spec
6444 // PARTITION_SPLIT at BLOCK_32X32, which
6445 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
6446 // already writes for a straddling quadrant). Each leaf is
6447 // searched against the reconstruction -- and the `mi`
6448 // grid -- the ones before it left, exactly as the writer
6449 // and the decoder will read them.
6450 //
6451 // A block the whole-32 search left skipped (no residual
6452 // at all) is not offered the split: libaom prunes the
6453 // same way at cpu-used 6, and it is where the wall would
6454 // otherwise go on static content.
6455 let leaf_positions: Vec<(usize, usize)> = (0..4)
6456 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
6457 .collect();
6458 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
6459 crate::tile::has_half(
6460 sc as u32 * crate::tile::SUB_MI,
6461 crate::tile::SUB_MI,
6462 header.mi_cols,
6463 ) && crate::tile::has_half(
6464 sr as u32 * crate::tile::SUB_MI,
6465 crate::tile::SUB_MI,
6466 header.mi_rows,
6467 )
6468 });
6469 // The breakout above: a 32x32 block that codes almost
6470 // nothing is not offered the split at all.
6471 let breakout = split_breakout_coeffs();
6472 let split = (!block.skip
6473 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
6474 && (breakout == 0 || block.luma.len() > 4 * breakout)
6475 && leaves_legal
6476 && split_inter_blocks())
6477 .then(|| {
6478 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
6479 let mut cost = search.lambda * partition_bits(BLOCK, true);
6480 let mut leaves = Vec::with_capacity(4);
6481 for &(sr, sc) in &leaf_positions {
6482 let (mi_row, mi_col) = (sr * 4, sc * 4);
6483 let (lx, ly) = (sc * SUB, sr * SUB);
6484 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
6485 let stack = find_mv_stack(
6486 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
6487 );
6488 let cstacks: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
6489 if header.reference_select && leaf_compound() {
6490 [
6491 (crate::mvstack::GOLDEN_FRAME, golden),
6492 (crate::mvstack::ALTREF_FRAME, altref),
6493 ]
6494 .into_iter()
6495 .filter_map(|(r, pic)| {
6496 pic.map(|p| {
6497 (
6498 r,
6499 p,
6500 crate::mvstack::find_mv_stack_compound(
6501 &grid, mi_row, mi_col, 4, 4,
6502 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6503 grid.sign_bias_table(), &[(0, 0); 7], None,
6504 ),
6505 )
6506 })
6507 })
6508 .collect()
6509 } else {
6510 Vec::new()
6511 };
6512 let (leaf, leaf_cost) = code_square_inter(
6513 &mut luma,
6514 &mut chroma,
6515 (lx, ly),
6516 SUB,
6517 &search,
6518 &mode_bits_table,
6519 reference,
6520 &stack, &cstacks, fctx,
6521 );
6522 let leaf_cost = leaf_cost
6523 + search.lambda * partition_bits(SUB, false);
6524 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
6525
6526 // And what four 8x8 leaves cost instead --
6527 // the same tree one step further down, which
6528 // the writer codes as a real PARTITION_SPLIT
6529 // at BLOCK_16X16 (lane-av1rd2). Same
6530 // skipped-block prune as the level above.
6531 let eight = (!leaf.skip
6532 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
6533 && (breakout == 0 || leaf.luma.len() > breakout)
6534 && split_inter_8())
6535 .then(|| {
6536 restore(
6537 &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base,
6538 );
6539 let mut cost8 = search.lambda
6540 * (partition_bits(SUB, true)
6541 + 4.0 * partition_bits(8, false));
6542 let mut eight = Vec::with_capacity(4);
6543 for i in 0..4 {
6544 let (mr, mc) =
6545 (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
6546 let stack8 = find_mv_stack(
6547 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
6548 );
6549 let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
6550 if header.reference_select && leaf_compound() {
6551 [
6552 (crate::mvstack::GOLDEN_FRAME, golden),
6553 (crate::mvstack::ALTREF_FRAME, altref),
6554 ]
6555 .into_iter()
6556 .filter_map(|(r, pic)| {
6557 pic.map(|p| {
6558 (
6559 r,
6560 p,
6561 crate::mvstack::find_mv_stack_compound(
6562 &grid, mr, mc, 2, 2,
6563 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
6564 grid.sign_bias_table(), &[(0, 0); 7], None,
6565 ),
6566 )
6567 })
6568 })
6569 .collect()
6570 } else {
6571 Vec::new()
6572 };
6573 let (leaf8, cost) = code_square_inter(
6574 &mut luma,
6575 &mut chroma,
6576 (lx + (i % 2) * 8, ly + (i / 2) * 8),
6577 8,
6578 &search,
6579 &mode_bits_table,
6580 reference,
6581 &stack8, &cstacks8, fctx,
6582 );
6583 cost8 += cost;
6584 record_mi(&mut grid, mr, mc, 2, leaf8.inter);
6585 eight.push(leaf8);
6586 }
6587 (eight, cost8)
6588 });
6589 match eight {
6590 Some((eight, cost8)) if cost8 < leaf_cost => {
6591 partition_hit(3);
6592 cost += cost8;
6593 leaves.push(BlockCoeffs {
6594 eight: Some(eight),
6595 ..BlockCoeffs::default()
6596 });
6597 continue;
6598 }
6599 Some(_) => restore(
6600 &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf,
6601 ),
6602 None => {}
6603 }
6604 partition_hit(2);
6605 cost += leaf_cost;
6606 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter);
6607 leaves.push(leaf);
6608 }
6609 (leaves, cost)
6610 });
6611 if let Some((leaves, cost)) = split {
6612 if cost < cost_whole {
6613 // The leaves' own `mi` cells are already in the
6614 // grid, and their reconstruction is what the
6615 // planes hold.
6616 partition_hit(1);
6617 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
6618 continue;
6619 }
6620 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
6621 }
6622 partition_hit(0);
6623 record_mi(&mut grid, mi_row, mi_col, 8, block.inter);
6624 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
6625 } else {
6626 // The sub-positions actually inside the true frame, same
6627 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
6628 let sub_positions: Vec<(usize, usize)> = (0..4)
6629 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
6630 .filter(|&(sr, sc)| {
6631 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
6632 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
6633 })
6634 .collect();
6635 // Each leaf searches intra against its own `NEARESTMV`
6636 // candidate (`code_square_inter`), same real-inter choice
6637 // `search_inter_block` makes for a whole 32x32 block, at
6638 // this leaf's own 4x4-mi mv-stack window -- unless the
6639 // leaf's own half itself straddles the true edge, which
6640 // it codes as two (or one, at a true corner) 8x8 leaves
6641 // (`crate::tile::write_leaf8`'s inter counterpart),
6642 // mirroring the key frame search's straddling-16x16
6643 // handling above (lane-av1inter8).
6644 let mut leaves = Vec::with_capacity(sub_positions.len());
6645 for (sr, sc) in sub_positions {
6646 let (has_cols16, has_rows16) = (
6647 crate::tile::has_half(
6648 sc as u32 * crate::tile::SUB_MI,
6649 crate::tile::SUB_MI,
6650 header.mi_cols,
6651 ),
6652 crate::tile::has_half(
6653 sr as u32 * crate::tile::SUB_MI,
6654 crate::tile::SUB_MI,
6655 header.mi_rows,
6656 ),
6657 );
6658 if !has_cols16 && !has_rows16 {
6659 return Err(Error::unsupported(
6660 "AV1 encode",
6661 format!(
6662 "the 16x16 block at ({sc},{sr}) straddles the true \
6663 frame edge in a way that needs a rectangular \
6664 (HORZ/VERT) transform this encoder does not code yet"
6665 ),
6666 ));
6667 }
6668 if has_cols16 && has_rows16 {
6669 let (x, y) = (sc * SUB, sr * SUB);
6670 let (mi_row, mi_col) = (sr * 4, sc * 4);
6671 let stack = find_mv_stack(
6672 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
6673 );
6674 let (block, _) = code_square_inter(
6675 &mut luma,
6676 &mut chroma,
6677 (x, y),
6678 SUB,
6679 &search,
6680 &mode_bits_table,
6681 reference,
6682 &stack, &[], fctx,
6683 );
6684 // One publication point for every coded leaf
6685 // (`record_mi`): this site used to spell the vote
6686 // out with `ref_frame` pinned to LAST and `mv1`
6687 // to (0,0), which is the encoder-grid-drift class
6688 // -- correct only for as long as a leaf can never
6689 // be compound.
6690 record_mi(&mut grid, mi_row, mi_col, 4, block.inter);
6691 leaves.push(block);
6692 } else {
6693 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
6694 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
6695 let mut eight = Vec::with_capacity(2);
6696 for i in 0..4 {
6697 let leaf_x = x_sub + (i % 2) * 8;
6698 let leaf_y = y_sub + (i / 2) * 8;
6699 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
6700 continue;
6701 }
6702 let (mi_row, mi_col) =
6703 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
6704 let stack = find_mv_stack(
6705 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
6706 );
6707 let (leaf, _) = code_square_inter(
6708 &mut luma,
6709 &mut chroma,
6710 (leaf_x, leaf_y),
6711 8,
6712 &search,
6713 &mode_bits_table,
6714 reference,
6715 &stack, &[], fctx,
6716 );
6717 // Same publication point as the 16x16
6718 // straddling leaf above (`record_mi`).
6719 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter);
6720 eight.push(leaf);
6721 }
6722 leaves.push(BlockCoeffs {
6723 eight: Some(eight),
6724 ..BlockCoeffs::default()
6725 });
6726 }
6727 }
6728 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
6729 }
6730 }
6731 }
6732 }
6733 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
6734 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
6735 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
6736 for (&out, tile) in chroma_out.iter().zip(&chroma) {
6737 copy_rect(
6738 out,
6739 &tile.reconstruction,
6740 frame_width / 2,
6741 x0 / 2,
6742 y0 / 2,
6743 x1.div_ceil(2),
6744 y1.div_ceil(2),
6745 );
6746 }
6747 Ok(blocks)
6748 };
6749 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
6750 .into_iter()
6751 .flatten()
6752 {
6753 blocks[at] = quadrant;
6754 }
6755
6756 let modes = blocks
6757 .iter()
6758 .flat_map(Quadrant::blocks)
6759 .map(|b| b.mode)
6760 .collect::<Vec<_>>();
6761 let inter_block_share = blocks
6762 .iter()
6763 .flat_map(Quadrant::blocks)
6764 .filter(|b| b.inter.is_some())
6765 .count() as f64
6766 / modes.len() as f64;
6767 for block in blocks.iter().flat_map(Quadrant::blocks) {
6768 if let Some(info) = block.inter {
6769 let r = (info.ref_frame as usize).min(7);
6770 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6771 }
6772 }
6773 #[cfg(test)]
6774 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
6775 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
6776 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
6777 // next frame's writer starts from them -- exactly what
6778 // `crate::stream::stored_cdfs_for` hands the decoder.
6779 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
6780 let cdfs = start_cdfs
6781 .cloned()
6782 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
6783 let start_cdfs = CdfSnapshot(cdfs);
6784 let reference_select_bit = header.reference_select;
6785 let order_hint_bits = seq.order_hint_bits;
6786 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
6787 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
6788 // What this frame stores is the LARGEST tile's end-of-tile tables --
6789 // its own header's `context_update_tile_id` (spec 7.20), which
6790 // `tile_info_of` set to exactly that tile.
6791 let store_tile = layout.largest_tile();
6792 let end_cdfs = std::cell::RefCell::new(None);
6793 // As in `encode_key_frame_inner`: every tile starts from this frame's
6794 // own tables, so no tile depends on any other.
6795 let code_tiles = |bits: u8,
6796 sb_cols: usize,
6797 cdef_grid: &[u8],
6798 units: &[Option<crate::restoration::WienerInfo>]|
6799 -> Result<Vec<Vec<u8>>> {
6800 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
6801 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
6802 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
6803 crate::tile::arm_sign_bias(sign_bias);
6804 // Thread-locals: every tile job arms its own worker.
6805 crate::tile::arm_reference_select(reference_select_bit);
6806 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
6807 crate::tile::arm_screen(screen);
6808 let mut cdfs = start_cdfs.0.clone();
6809 // Each tile's own MV grid: a candidate scan never reaches past
6810 // the tile's bounds, so a grid holding only this tile's own
6811 // blocks reads exactly as the decoder's frame-wide one does
6812 // under `MiGrid::set_tile_bounds`.
6813 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
6814 mv_grid.set_sign_bias(sign_bias);
6815 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
6816 mi_cols,
6817 mi_rows,
6818 base_q_idx,
6819 &blocks,
6820 tx_select,
6821 &mut cdfs,
6822 layout.rect(index),
6823 &mut mv_grid,
6824 )?;
6825 Ok((bytes, Some(cdfs)))
6826 })?;
6827 if let Some(cdfs) = stored {
6828 *end_cdfs.borrow_mut() = Some(cdfs);
6829 }
6830 Ok(out)
6831 };
6832 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
6833 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
6834 // this tile against the same single-slot reference this encoder predicted
6835 // from, under each candidate level.
6836 // The reference a DECODER holds is this frame's cropped size, not the
6837 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
6838 // reference whose height is not the header's own `frame_height` (spec
6839 // 7.9's compatible-size rule), and the chained-decode round trips prove
6840 // the two predict identically.
6841 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
6842 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
6843 reference.clone()
6844 } else {
6845 Picture {
6846 width: fw,
6847 height: fh,
6848 y: crop_plane(&reference.y, reference.width, fw, fh),
6849 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
6850 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
6851 }
6852 };
6853 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
6854 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
6855 // blocks may name GOLDEN needs that plane too, cropped the same way.
6856 let trial_golden = golden.map(|g| {
6857 if (g.width, g.height) == (fw, fh) {
6858 g.clone()
6859 } else {
6860 Picture {
6861 width: fw,
6862 height: fh,
6863 y: crop_plane(&g.y, g.width, fw, fh),
6864 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
6865 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
6866 }
6867 }
6868 });
6869 let trial_altref = altref.map(|a| {
6870 if (a.width, a.height) == (fw, fh) {
6871 a.clone()
6872 } else {
6873 Picture {
6874 width: fw,
6875 height: fh,
6876 y: crop_plane(&a.y, a.width, fw, fh),
6877 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
6878 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
6879 }
6880 }
6881 });
6882 let mut refs: [Option<&Picture>; 8] = [None; 8];
6883 refs[1] = Some(&trial_ref);
6884 refs[4] = trial_golden.as_ref();
6885 refs[7] = trial_altref.as_ref();
6886 let refpix = crate::decode::RefPix::ready(refs);
6887 pick_and_apply_filters(
6888 &mut header,
6889 &mut luma,
6890 &mut chroma,
6891 [&picture_y8, &picture_u8, &picture_v8],
6892 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
6893 // this frame's own `tx_select`, so the search runs under inter
6894 // `TxMode::Select` too (it used to skip and leave every inter frame
6895 // unfiltered once Select became the default).
6896 true,
6897 &mut tiles,
6898 search.lambda,
6899 fctx,
6900 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
6901 // are what the NEXT frame writes from, so the winning re-code
6902 // publishes its own into `end_cdfs` -- the first write's are stale
6903 // the moment a second tile is coded.
6904 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
6905 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
6906 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
6907 crate::decode::decode_inter_frame_tiles_lr(
6908 &payloads,
6909 &header_tile_info,
6910 h.mi_cols,
6911 h.mi_rows,
6912 base_q_idx,
6913 h.frame_width,
6914 h.frame_height,
6915 &refpix,
6916 cdef,
6917 lf,
6918 h.allow_high_precision_mv,
6919 h.force_integer_mv,
6920 Some(mc::InterpFilterKind::Regular),
6921 seq.enable_dual_filter,
6922 h.reference_select,
6923 tx_select,
6924 lr,
6925 // The trial decode re-reads the tile the writer just wrote,
6926 // so it starts from the same tables the writer did (this
6927 // frame's `start_cdfs`), not from the defaults.
6928 Some(start_cdfs.0.clone()),
6929 sign_bias,
6930 h.allow_screen_content_tools,
6931 fctx,
6932 )
6933 },
6934 )?;
6935 let mut cdfs = end_cdfs
6936 .into_inner()
6937 .unwrap_or_else(|| start_cdfs.0.clone());
6938 cdfs.reset_counts();
6939 let next_cdfs = CdfSnapshot(cdfs);
6940 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
6941 header.tile_info.tile_size_bytes = tile_size_bytes;
6942 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
6943 let mut stream = temporal_delimiter();
6944 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
6945
6946 let [u, v] = chroma;
6947 Ok(Encoded {
6948 stream,
6949 modes,
6950 inter_block_share,
6951 reconstruction: Picture {
6952 width: luma.width,
6953 height: luma.height,
6954 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
6955 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
6956 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
6957 },
6958 tile,
6959 mi_cols: header.mi_cols,
6960 mi_rows: header.mi_rows,
6961 base_q_idx,
6962 tx_select,
6963 screen,
6964 start_cdfs,
6965 next_cdfs,
6966 loop_filter: header.loop_filter,
6967 cdef: header.cdef,
6968 loop_restoration: header.loop_restoration,
6969 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
6970 // intra frames only).
6971 allow_intrabc: false,
6972 })
6973}
6974
6975/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
6976/// frame's temporal unit followed by one inter frame's temporal unit per
6977/// remaining picture, all sharing the key frame's sequence header -- and
6978/// each frame's own [`Encoded`], in coding order.
6979#[derive(Clone, Debug)]
6980pub struct EncodedSequence {
6981 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
6982 /// sequence header and the key frame) followed by each later frame's
6983 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
6984 /// the sequence header the key frame carried).
6985 pub stream: Vec<u8>,
6986 /// One entry per picture, in coding order.
6987 pub frames: Vec<Encoded>,
6988}
6989
6990/// Encodes a sequence of pictures as a key frame followed by one inter frame
6991/// per remaining picture, each predicting from the previous frame's own
6992/// decoded reconstruction — never from the source, which is what a decoder
6993/// cannot see. Every picture must be the same even size (any even width and
6994/// height — each is padded to a whole number of 64x64 superblocks
6995/// internally, which is what lets an inter frame's reference always match
6996/// the frame being coded against it), and `pictures` must be non-empty.
6997///
6998/// # Errors
6999/// Returns an error when `pictures` is empty, when any picture besides the
7000/// first is not the same size as the first, or under the same conditions
7001/// [`encode_key_frame`] and the inter frame path do.
7002pub(crate) fn encode_sequence_with_ctx(
7003 pictures: &[Picture],
7004 base_q_idx: u8,
7005 deadzone: f64, fctx: &crate::decode::FrameCtx,
7006) -> Result<EncodedSequence> {
7007 let Some((first, rest)) = pictures.split_first() else {
7008 return Err(Error::unsupported(
7009 "AV1 encode",
7010 "a sequence needs at least one picture",
7011 ));
7012 };
7013 first.check_even()?;
7014 let render = (first.width, first.height);
7015 // The key frame and every inter frame after it are coded at the same
7016 // padded size, so the reference each inter frame predicts from -- the
7017 // previous frame's own uncropped reconstruction, at the size a decoder's
7018 // reference buffer actually holds -- always matches the frame being
7019 // coded against it.
7020 let key = encode_key_frame_inner(
7021 &first.padded_to(SUPERBLOCK),
7022 base_q_idx,
7023 deadzone,
7024 &KEY_FRAME_MODES,
7025 split_blocks(),
7026 render,
7027 unspecified_color_config(), fctx,
7028 )?;
7029 let mut stream = key.stream.clone();
7030 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
7031 // key frame refreshes every slot, each inter frame only slot 0), which is
7032 // what `GOLDEN_FRAME` names.
7033 let golden = key.reconstruction.clone();
7034 // The frame two back, once there is one that is not the key frame
7035 // itself (which `GOLDEN_FRAME` already names).
7036 let mut prev2: Option<Picture> = None;
7037 let mut carried = key.next_cdfs.clone();
7038 let mut reference = key.reconstruction.clone();
7039 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
7040 for (i, picture) in rest.iter().enumerate() {
7041 picture.check_even()?;
7042 if (picture.width, picture.height) != render {
7043 return Err(Error::unsupported(
7044 "AV1 encode",
7045 "every picture in a sequence must be the same size as the first",
7046 ));
7047 }
7048 let order_hint = (i + 1) as u32;
7049 let inter = encode_inter_frame(
7050 &picture.padded_to(SUPERBLOCK),
7051 &reference,
7052 base_q_idx,
7053 deadzone,
7054 order_hint,
7055 flat_order_hints(order_hint, 0, prev2.is_some()),
7056 render,
7057 Some(&carried.0),
7058 Some(&golden),
7059 prev2.as_ref(), fctx,
7060 None,
7061 )?;
7062 stream.extend_from_slice(&inter.stream);
7063 carried = inter.next_cdfs.clone();
7064 prev2 = Some(std::mem::replace(
7065 &mut reference,
7066 inter.reconstruction.clone(),
7067 ));
7068 frames.push(crop_encoded(&inter, render.0, render.1));
7069 }
7070 Ok(EncodedSequence { stream, frames })
7071}
7072
7073#[cfg(test)]
7074mod tests {
7075
7076 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
7077 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
7078 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
7079 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
7080 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
7081 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
7082 /// only a quarter of the 16x8 table and read the wrong byte for every
7083 /// block row but the first (silently wrong above-right/below-left
7084 /// availability -- wrong pixels, no error).
7085 #[test]
7086 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
7087 for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
7088 let (bw_log2, bh_log2) =
7089 ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize);
7090 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
7091 for (name, table) in
7092 [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)]
7093 {
7094 assert_eq!(
7095 table.len() * 8,
7096 rows * cols,
7097 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
7098 );
7099 let mut seen = vec![0u32; table.len() * 8];
7100 for blk_row in 0..rows {
7101 for blk_col in 0..cols {
7102 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
7103 assert!(
7104 idx < seen.len(),
7105 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
7106 );
7107 seen[idx] += 1;
7108 }
7109 }
7110 assert!(
7111 seen.iter().all(|&n| n == 1),
7112 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
7113 (row stride is not {cols})"
7114 );
7115 }
7116 }
7117 }
7118 use super::*;
7119 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
7120 use std::io::Write;
7121 use std::process::{Command, Stdio};
7122
7123 /// Every rectangular shape this decoder codes, at every position a block
7124 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
7125 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
7126 /// (`reconintra.c`) answer, whose bodies are ported below.
7127 ///
7128 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
7129 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
7130 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
7131 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
7132 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
7133 /// oracle's own arrays, so a re-routed or truncated table fails here even
7134 /// where the two rows happen to agree.
7135 ///
7136 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
7137 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
7138 /// callers handle by predicting each transform unit as its own block.
7139 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
7140 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
7141 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
7142 /// (the horizontal shapes, which those partitions never produce).
7143 #[test]
7144 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
7145 let fctx = &crate::decode::FrameCtx::new();
7146 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
7147 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
7148 (4, 8, 64, 9280, 64, 550),
7149 (8, 4, 64, 3712, 64, 9630),
7150 (8, 16, 16, 2352, 16, 134),
7151 (16, 8, 16, 960, 16, 2400),
7152 (16, 32, 4, 620, 4, 32),
7153 (32, 16, 4, 32, 4, 184),
7154 (32, 64, 1, 127, 1, 0),
7155 (64, 32, 1, 19, 1, 34),
7156 (4, 16, 32, 5472, 32, 14),
7157 (16, 4, 32, 960, 32, 6464),
7158 (8, 32, 8, 1400, 8, 2),
7159 (32, 8, 8, 32, 8, 1136),
7160 (16, 64, 2, 382, 2, 0),
7161 (64, 16, 2, 4, 2, 84),
7162 ];
7163 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
7164 /// a block whose transform covers it whole (`row_off == col_off == 0`,
7165 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
7166 /// superblock (`sb_mi_size == 16`).
7167 fn libaom_reach(
7168 bw: usize,
7169 bh: usize,
7170 x: usize,
7171 y: usize,
7172 width: usize,
7173 height: usize, _fctx: &crate::decode::FrameCtx,
7174 ) -> (bool, bool) {
7175 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
7176 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
7177 let sb_mi_size = 16usize;
7178 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
7179 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
7180 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
7181 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
7182 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
7183 // has_top_right: top_available && right_available, then row_off == 0.
7184 let top_right = if y == 0 || x + bw >= width {
7185 false
7186 } else if blk_row_in_sb == 0 {
7187 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
7188 // `bw_unit < bw_unit`, false for a whole-block transform.)
7189 true
7190 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
7191 false
7192 } else {
7193 bit(tr_table)
7194 };
7195 // has_bottom_left: bottom_available && left_available, col_off == 0.
7196 let bottom_left = if x == 0 || y + bh >= height {
7197 false
7198 } else if blk_col_in_sb == 0 {
7199 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
7200 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
7201 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
7202 false
7203 } else {
7204 bit(bl_table)
7205 };
7206 (top_right, bottom_left)
7207 }
7208 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
7209 let (tr, bl) = rect_reach_tables(bw, bh);
7210 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
7211 assert_eq!(
7212 (tr.len(), sum(tr), bl.len(), sum(bl)),
7213 (tr_len, tr_sum, bl_len, bl_sum),
7214 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
7215 );
7216 // Two superblocks across and down, so the superblock-relative
7217 // position (and not the frame position) is what decides.
7218 for sb_y in [0usize, 64] {
7219 for sb_x in [0usize, 64] {
7220 for y in (sb_y..sb_y + 64).step_by(bh) {
7221 for x in (sb_x..sb_x + 64).step_by(bw) {
7222 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
7223 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
7224 assert_eq!(
7225 (got.above_right, got.below_left),
7226 want,
7227 "{bw}x{bh} at ({x}, {y})"
7228 );
7229 }
7230 }
7231 }
7232 }
7233 }
7234 }
7235
7236 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
7237 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
7238 /// aomenc gate decodes its stream through ffmpeg and is meaningless
7239 /// without it -- turns it into a hard failure. Without this the require
7240 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
7241 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
7242 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
7243 fn have_ffmpeg() -> bool {
7244 let present = Command::new("ffmpeg")
7245 .arg("-version")
7246 .stdout(Stdio::null())
7247 .stderr(Stdio::null())
7248 .status()
7249 .is_ok_and(|s| s.success());
7250 assert!(
7251 present
7252 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
7253 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
7254 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
7255 );
7256 present
7257 }
7258
7259 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
7260 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
7261 let mut child = Command::new("ffmpeg")
7262 .args([
7263 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
7264 ])
7265 .stdin(Stdio::piped())
7266 .stdout(Stdio::piped())
7267 .stderr(Stdio::piped())
7268 .spawn()
7269 .expect("ffmpeg failed to start");
7270 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
7271 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
7272 // fills before the last input byte is written -- which is exactly what
7273 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
7274 // (measured: 45 min, both processes at 0% CPU). A write error here is
7275 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
7276 // below, are the real diagnosis.
7277 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
7278 let payload = stream.to_vec();
7279 let writer = std::thread::spawn(move || {
7280 let _ = stdin.write_all(&payload);
7281 });
7282 let out = child.wait_with_output().expect("ffmpeg failed to run");
7283 writer.join().expect("ffmpeg stdin writer thread");
7284 assert!(
7285 out.status.success(),
7286 "ffmpeg refused the stream: {}",
7287 String::from_utf8_lossy(&out.stderr)
7288 );
7289 let (luma, chroma) = (width * height, width * height / 4);
7290 assert_eq!(
7291 out.stdout.len(),
7292 luma + 2 * chroma,
7293 "expected one 4:2:0 frame"
7294 );
7295 Picture {
7296 width,
7297 height,
7298 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
7299 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
7300 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
7301 }
7302 }
7303
7304 /// A picture with something of everything in it: a gradient, an edge, a
7305 /// ripple and a block of flat colour, none of them aligned to the block
7306 /// grid.
7307 /// The in-loop filters actually FIRE and the stream still decodes to
7308 /// exactly what the encoder kept as its reconstruction
7309 /// (gate-blind-to-feature: a filter search that always answered "off"
7310 /// would leave every other test just as green, and the BD gate that
7311 /// would notice is `#[ignore]`d).
7312 ///
7313 /// Run:
7314 /// cargo test -p ec-av1 --release --lib -- \
7315 /// encode::tests::the_filter_search_picks_real_filters
7316 #[test]
7317 fn the_filter_search_picks_real_filters() {
7318 let fctx = &crate::decode::FrameCtx::new();
7319 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
7320 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
7321 let fired = encoded
7322 .frames
7323 .iter()
7324 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
7325 .count();
7326 assert!(
7327 fired > 0,
7328 "no frame of this sequence chose any in-loop filtering: {:?}",
7329 encoded
7330 .frames
7331 .iter()
7332 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
7333 .collect::<Vec<_>>()
7334 );
7335 // The reconstruction the encoder predicts from is the FILTERED one,
7336 // and it is what a decoder of the stream produces -- byte for byte,
7337 // frame for frame.
7338 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
7339 assert_eq!(decoded.len(), encoded.frames.len());
7340 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
7341 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
7342 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
7343 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
7344 }
7345 }
7346
7347 fn test_card(width: usize, height: usize) -> Picture {
7348 let mut picture = Picture::grey(width, height);
7349 for y in 0..height {
7350 for x in 0..width {
7351 let gradient = x as f64 * 200.0 / width as f64;
7352 let ripple = 30.0
7353 * (x as f64 * std::f64::consts::PI / 23.0).sin()
7354 * (y as f64 * std::f64::consts::PI / 37.0).cos();
7355 let edge = if x > width * 3 / 7 && y > height / 3 {
7356 40.0
7357 } else {
7358 0.0
7359 };
7360 picture.y[y * width + x] =
7361 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
7362 }
7363 }
7364 for y in 0..height / 2 {
7365 for x in 0..width / 2 {
7366 let i = y * width / 2 + x;
7367 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
7368 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
7369 }
7370 }
7371 picture
7372 }
7373
7374 fn psnr(a: &[u16], b: &[u16]) -> f64 {
7375 let squared: f64 = a
7376 .iter()
7377 .zip(b)
7378 .map(|(&x, &y)| {
7379 let d = f64::from(x) - f64::from(y);
7380 d * d
7381 })
7382 .sum();
7383 if squared == 0.0 {
7384 return f64::INFINITY;
7385 }
7386 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
7387 }
7388
7389 /// The claim the whole encoder rests on: what a decoder produces is what
7390 /// the encoder said it would, sample for sample, on every plane.
7391 ///
7392 /// Prediction reads the reconstruction, so a single sample of drift
7393 /// anywhere would spread into every block below and to the right of it —
7394 /// which is why this is an equality and not a tolerance.
7395 #[test]
7396 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
7397 let fctx = &crate::decode::FrameCtx::new();
7398 if !have_ffmpeg() {
7399 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
7400 return;
7401 }
7402 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] {
7403 let picture = test_card(width, height);
7404 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7405 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7406 assert_eq!(
7407 decoded.y, encoded.reconstruction.y,
7408 "{width}x{height}: luma"
7409 );
7410 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
7411 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
7412 }
7413 // One q index from each of the four coefficient-CDF contexts
7414 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
7415 let (width, height) = (64usize, 64usize);
7416 let picture = test_card(width, height);
7417 let _ = take_tx_depth_hits();
7418 for &q in &[15u8, 45, 100, 200] {
7419 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
7420 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7421 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
7422 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
7423 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
7424 }
7425 // lane-av1tx: the exactness above is only a claim about SPLIT
7426 // transforms if some block actually split one (`gate-blind-to-feature`
7427 // -- with `tx_depth` stuck at 0 every assert here passes on the
7428 // pre-lane stream). The test card's edges split at these four
7429 // quantizers; the counter is per-process (another test encoding in
7430 // parallel can only ADD to it, so this can be masked, never falsely
7431 // failed), so it is read once for the whole q ladder.
7432 let depths = take_tx_depth_hits();
7433 assert!(
7434 depths[1] + depths[2] > 0,
7435 "no block split its transform: depths {depths:?}"
7436 );
7437 }
7438
7439 /// A synthetic screen-content picture -- a few flat colours in a grid of
7440 /// boxes with hard edges and text-like bars, the shape a desktop capture
7441 /// has -- so the palette path is exercised on content it is for.
7442 #[cfg(test)]
7443 fn screen_card(width: usize, height: usize) -> Picture {
7444 const INK: [u16; 4] = [16, 90, 180, 235];
7445 let mut picture = Picture::grey(width, height);
7446 for y in 0..height {
7447 for x in 0..width {
7448 let cell = (x / 24 + y / 24) % 2;
7449 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
7450 picture.y[y * width + x] = INK[cell * 2 + bar];
7451 }
7452 }
7453 // Four chroma colours, not two: a two-colour chroma block only ever
7454 // codes a `PaletteSizeUV` of 2, which leaves
7455 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
7456 // deltas and the neighbour cache flags, exercised only when
7457 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
7458 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
7459 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
7460 for y in 0..height / 2 {
7461 for x in 0..width / 2 {
7462 let cell = (x / 12 + 2 * (y / 12)) % 4;
7463 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
7464 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
7465 }
7466 }
7467 picture
7468 }
7469
7470 /// The lane's own end-to-end check: on screen content the detector fires,
7471 /// blocks really take a palette (fire count, class
7472 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
7473 /// symbol this lane writes -- reconstructs exactly what the encoder did.
7474 /// The film-shaped `test_card` must NOT trip the detector, which is what
7475 /// keeps every non-screen stream byte-identical.
7476 #[test]
7477 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
7478 let fctx = &crate::decode::FrameCtx::new();
7479 let (width, height) = (192usize, 96usize);
7480 let _ = crate::tile::take_palette_hits();
7481 let picture = screen_card(width, height);
7482 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7483 assert!(
7484 encoded.screen,
7485 "the detector did not fire on screen content -- no palette syntax was coded at all"
7486 );
7487 let hits = crate::tile::take_palette_hits();
7488 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
7489 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
7490 // The chroma half is a claim about the plane-1 syntax only if some
7491 // block really took a chroma palette (`gate-blind-to-feature`): every
7492 // exactness assert below passes on a stream that codes
7493 // `palette_uv_mode == 0` everywhere.
7494 let uv_hits = crate::tile::take_palette_uv_hits();
7495 assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
7496 let uv_cached = crate::tile::take_palette_uv_cache_hits();
7497 eprintln!(
7498 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
7499 uv_hits[0],
7500 &uv_hits[2..]
7501 );
7502 assert!(
7503 uv_cached > 0,
7504 "no chroma base colour came out of the neighbour cache -- \
7505 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
7506 );
7507 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
7508 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
7509 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
7510 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
7511 if !have_ffmpeg() {
7512 eprintln!("SKIP the ffmpeg half: no ffmpeg");
7513 return;
7514 }
7515 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7516 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
7517 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
7518 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
7519 // A whole GOP: the inter frames' own intra blocks carry the palette
7520 // syntax too (the three intra arms of the inter writers), which only
7521 // ffmpeg reading the frames back can prove.
7522 let moved: Vec<Picture> = (0..4)
7523 .map(|f| {
7524 let base = screen_card(width, height);
7525 let mut out = Picture::grey(width, height);
7526 for y in 0..height {
7527 for x in 0..width {
7528 let sx = (x + f * 7) % width;
7529 out.y[y * width + x] = base.y[y * width + sx];
7530 }
7531 }
7532 for y in 0..height / 2 {
7533 for x in 0..width / 2 {
7534 let sx = (x + f * 3) % (width / 2);
7535 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
7536 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
7537 }
7538 }
7539 out
7540 })
7541 .collect();
7542 let _ = crate::tile::take_palette_hits();
7543 let _ = crate::tile::take_palette_uv_hits();
7544 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
7545 let gop_hits = crate::tile::take_palette_hits();
7546 let gop_uv_hits = crate::tile::take_palette_uv_hits();
7547 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
7548 eprintln!(
7549 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
7550 {} chroma palette blocks",
7551 inter_screen, gop_hits[0], gop_uv_hits[0]
7552 );
7553 assert!(
7554 gop_uv_hits[0] > 0,
7555 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
7556 );
7557 assert!(
7558 inter_screen > 0,
7559 "no inter frame set allow_screen_content_tools"
7560 );
7561 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
7562 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
7563 assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
7564 }
7565 if have_ffmpeg() {
7566 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
7567 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
7568 assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
7569 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
7570 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
7571 }
7572 }
7573
7574 // The other half of the keep rule: film-shaped content leaves the
7575 // detector (and so the whole sequence header) alone.
7576 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
7577 assert!(!film.screen, "the detector fired on the film-shaped test card");
7578 }
7579
7580 /// The lane's keep-rule measurement: the gate's own screen capture, one
7581 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
7582 /// Setting the bit forces deblocking, CDEF and loop restoration off for
7583 /// that frame, so the table is exactly the filter loss against the bytes
7584 /// the copied blocks save.
7585 #[test]
7586 #[ignore = "needs the real-library manifest and ffmpeg"]
7587 fn probe_intrabc_key_frame() {
7588 let fctx = &crate::decode::FrameCtx::new();
7589 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
7590 .join("../../fixtures");
7591 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
7592 eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest");
7593 return;
7594 };
7595 let Some(clip) = manifest
7596 .lines()
7597 .skip(1)
7598 .filter_map(|l| l.split('\t').next())
7599 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
7600 else {
7601 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
7602 return;
7603 };
7604 let (width, height) = (640usize, 384usize);
7605 let picture = clip_frame(clip, "0", width, height);
7606 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
7607 for q in [5u8, 20, 35, 45] {
7608 for on in [false, true] {
7609 force_intrabc(Some(on));
7610 let _ = crate::tile::take_intrabc_hits();
7611 let _ = take_intrabc_search();
7612 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
7613 let hits = crate::tile::take_intrabc_hits();
7614 let search = take_intrabc_search();
7615 eprintln!(
7616 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
7617 if encoded.allow_intrabc { "on" } else { "off" },
7618 encoded.stream.len(),
7619 psnr_all(&encoded.reconstruction, &picture),
7620 hits[0],
7621 &hits[1..],
7622 search[0], search[1], search[2],
7623 );
7624 }
7625 }
7626 force_intrabc(None);
7627 }
7628
7629 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
7630 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
7631 /// take a block vector (fire count + DV histogram, class
7632 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
7633 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
7634 /// exactly what the encoder did.
7635 #[test]
7636 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
7637 let fctx = &crate::decode::FrameCtx::new();
7638 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
7639 // superblocks of 64) and tall enough for a source superblock row
7640 // above the blocks that copy from it.
7641 let (width, height) = (512usize, 256usize);
7642 let picture = screen_card(width, height);
7643 let _ = crate::tile::take_intrabc_hits();
7644 // The default is OFF (it measured worse on the real screen capture --
7645 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
7646 // the arm on for its own encode and puts it back straight after.
7647 force_intrabc(Some(true));
7648 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7649 force_intrabc(None);
7650 assert!(
7651 encoded.allow_intrabc,
7652 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
7653 intrabc_source_share() * 100.0
7654 );
7655 let hits = crate::tile::take_intrabc_hits();
7656 eprintln!(
7657 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
7658 hits[0],
7659 &hits[1..],
7660 intrabc_source_share() * 100.0
7661 );
7662 let search = take_intrabc_search();
7663 eprintln!(
7664 "intrabc searches {} found-valid {} won-RD {}",
7665 search[0], search[1], search[2]
7666 );
7667 assert!(
7668 hits[0] > 0,
7669 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
7670 );
7671 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
7672 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
7673 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
7674 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
7675 if !have_ffmpeg() {
7676 eprintln!("SKIP the ffmpeg half: no ffmpeg");
7677 return;
7678 }
7679 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7680 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
7681 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
7682 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
7683 }
7684
7685 /// The minimal repro that isolated the inter-residual desync: a key frame
7686 /// followed by one inter frame whose single superblock carries one
7687 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
7688 /// coefficient, its three sibling blocks all `skip: true`. Before the
7689 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
7690 /// found when processing input") even though every symbol either block
7691 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
7692 /// same coefficient syntax decodes clean on every intra key-frame gate).
7693 #[test]
7694 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
7695 let fctx = &crate::decode::FrameCtx::new();
7696 if !have_ffmpeg() {
7697 eprintln!(
7698 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
7699 );
7700 return;
7701 }
7702 let (width, height) = (64usize, 64usize);
7703 let picture = Picture::grey(width, height);
7704 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7705
7706 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
7707 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
7708
7709 let residual_block = BlockCoeffs {
7710 luma: vec![Coeff {
7711 row: 0,
7712 col: 0,
7713 level: 4,
7714 }],
7715 u: Vec::new(),
7716 v: Vec::new(),
7717 mode: 0,
7718 uv_mode: 0,
7719 skip: false,
7720 eight: None,
7721 dv: None,
7722 palette: None,
7723 palette_uv: None,
7724 tx_depth: 0,
7725 inter: Some(InterInfo {
7726 ref1: None,
7727 mv1: (0, 0),
7728 ref_frame: crate::mvstack::LAST_FRAME,
7729 mode: InterMode::NearestMv,
7730 mv: (0, 0),
7731 ref_mv_idx: 0,
7732 }),
7733 };
7734 let skipped_block = BlockCoeffs {
7735 skip: true,
7736 inter: Some(InterInfo {
7737 ref1: None,
7738 mv1: (0, 0),
7739 ref_frame: crate::mvstack::LAST_FRAME,
7740 mode: InterMode::NearestMv,
7741 mv: (0, 0),
7742 ref_mv_idx: 0,
7743 }),
7744 ..BlockCoeffs::default()
7745 };
7746 let blocks = vec![
7747 Quadrant::Whole(residual_block),
7748 Quadrant::Whole(skipped_block.clone()),
7749 Quadrant::Whole(skipped_block.clone()),
7750 Quadrant::Whole(skipped_block),
7751 ];
7752 let tile =
7753 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
7754 .unwrap();
7755
7756 // `key.stream` is already a temporal delimiter, the sequence header
7757 // and the key frame's own OBU (`encode_key_frame` built it from the
7758 // same `key_frame_headers(width, height, 100)` this test calls), so
7759 // the inter frame's OBU is appended straight onto it rather than
7760 // re-deriving the key frame's tile bytes.
7761 let mut stream = key.stream.clone();
7762 stream.extend_from_slice(&temporal_delimiter());
7763 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
7764
7765 ffmpeg_decode_sequence(&stream, width, height, 2);
7766 }
7767
7768 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
7769 /// frame size an AV1 decoder allocates, not necessarily the render size
7770 /// (see [`a_frame_round_trips_at_its_own_size`]).
7771 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
7772 // Distinct per call, not per process: the test binary runs callers on
7773 // parallel threads, and a shared name lets one test's cleanup delete
7774 // the stream another test's ffprobe is still reading.
7775 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
7776 let path = std::env::temp_dir().join(format!(
7777 "ec-av1-probe-{}-{}.obu",
7778 std::process::id(),
7779 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
7780 ));
7781 let _ = std::fs::remove_file(&path);
7782 std::fs::write(&path, stream).expect("writing the probe stream");
7783 let out = Command::new("ffprobe")
7784 .args([
7785 "-v",
7786 "error",
7787 "-f",
7788 "obu",
7789 "-select_streams",
7790 "v:0",
7791 "-show_entries",
7792 "stream=width,height",
7793 "-of",
7794 "csv=p=0",
7795 ])
7796 .arg(&path)
7797 .output()
7798 .expect("ffprobe failed to run");
7799 let _ = std::fs::remove_file(&path);
7800 assert!(
7801 out.status.success(),
7802 "ffprobe refused the stream: {}",
7803 String::from_utf8_lossy(&out.stderr)
7804 );
7805 let text = String::from_utf8_lossy(&out.stdout);
7806 let mut fields = text.trim().split(',');
7807 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
7808 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
7809 (width, height)
7810 }
7811
7812 /// A key frame at an arbitrary even size round-trips through ffmpeg over
7813 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
7814 /// picture's own size, and what ffmpeg decodes over that same top-left
7815 /// region equals it sample for sample.
7816 ///
7817 /// This does not check that `ffprobe` reports the picture's own size,
7818 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
7819 /// (block-padded) frame size, the same one libaom itself would code for
7820 /// a non-block-aligned picture. `render_width`/`render_height` (which
7821 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
7822 /// decoder is required to crop pixels by, and ffmpeg's does not --
7823 /// checked empirically against ffprobe here and against a real libaom
7824 /// encode separately. So the coded size, not the render size, is what
7825 /// `ffprobe` is asserted to report below.
7826 #[test]
7827 fn a_frame_round_trips_at_its_own_size() {
7828 let fctx = &crate::decode::FrameCtx::new();
7829 if !have_ffmpeg() {
7830 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
7831 return;
7832 }
7833 // 854x480 is covered separately by
7834 // `an_854x480_picture_round_trips_through_its_padding`, which its own
7835 // doc comment explains was worth keeping as its own test.
7836 for &(width, height) in &[
7837 (1920usize, 1080usize),
7838 (640, 352),
7839 (1280, 720),
7840 (64, 56),
7841 (854, 480),
7842 (216, 96),
7843 (192, 120),
7844 ] {
7845 let picture = test_card(width, height);
7846 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7847 assert_eq!(
7848 (encoded.reconstruction.width, encoded.reconstruction.height),
7849 (width, height),
7850 "{width}x{height}: reconstruction is cropped to the picture's own size"
7851 );
7852 assert_eq!(
7853 ffprobe_size(&encoded.stream),
7854 (width as u32, height as u32),
7855 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
7856 );
7857 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7858 assert_eq!(
7859 decoded.y, encoded.reconstruction.y,
7860 "{width}x{height}: luma"
7861 );
7862 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
7863 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
7864 }
7865 }
7866
7867 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
7868 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
7869 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
7870 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
7871 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
7872 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
7873 /// col`) -- different bits of an 8-byte table, one true, one false. The
7874 /// stride libaom indexes by is fixed at its compile-time maximum
7875 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
7876 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
7877 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
7878 /// row/col position within the (correctly 64-relative) superblock stayed
7879 /// right, only the table's own row stride was wrong. Fixed in
7880 /// `Reach::table_stride`; not an arithmetic-coder desync (an
7881 /// EC_RNG-per-symbol trace against the same debug decoder found the
7882 /// bitstream byte-for-byte identical to libaom's across all 51188
7883 /// symbols of this frame before this bug was found).
7884 ///
7885 /// Since the frame header started writing the true (unpadded) display
7886 /// size into `frame_width`/`frame_height` rather than the padded coded
7887 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
7888 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
7889 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
7890 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
7891 /// the header's own size before output).
7892 #[test]
7893 fn an_854x480_picture_round_trips_through_its_padding() {
7894 let fctx = &crate::decode::FrameCtx::new();
7895 if !have_ffmpeg() {
7896 return;
7897 }
7898 let (width, height) = (854usize, 480usize);
7899 let picture = test_card(width, height);
7900 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
7901 let decoded = ffmpeg_decode(&encoded.stream, width, height);
7902 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
7903 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
7904 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
7905 }
7906
7907 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
7908 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
7909 /// superblock, both partition tables:
7910 ///
7911 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
7912 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
7913 /// wiring the TU sites onto it changes no existing stream;
7914 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
7915 /// NULL in libaom because that lookup never happens, and reading a
7916 /// 4x4 row out of the three-row vert tables is what crashed a real
7917 /// `--enable-tx-size-search=1` stream (r2);
7918 /// 3. and it must be the BLOCK's vert answer where the two tables
7919 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
7920 /// row 1, column 0 reads its above-right samples from the 8x8 to its
7921 /// upper right, which a vertical AB partition codes AFTER it
7922 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
7923 #[test]
7924 fn of_tu_follows_the_block_row_including_under_vert_ab() {
7925 let fctx = &crate::decode::FrameCtx::new();
7926 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
7927 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
7928 // above-right answer is the BLOCK's, which is the whole reason a unit
7929 // asks the block instead of looking itself up (the
7930 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
7931 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
7932 assert_eq!(
7933 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
7934 plain.above_right,
7935 "ordinary table: the top-right TX4 unit takes the block's row"
7936 );
7937 let guard = Reach::vert_ab_partition();
7938 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
7939 assert_eq!(
7940 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
7941 vert.above_right,
7942 "vert AB: the unit follows the vert row the block just picked"
7943 );
7944 assert_ne!(
7945 plain.above_right, vert.above_right,
7946 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
7947 );
7948 drop(guard);
7949 }
7950
7951 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
7952 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
7953 /// reconintra.c`), for every 16x16 and 32x32 block position across three
7954 /// superblocks square -- interior and every superblock edge (top row,
7955 /// left column, right column, bottom row) both sizes reach. Written to
7956 /// catch the class the `table_stride` bug was: an index stride silently
7957 /// wrong for one block size while looking plausible for the other.
7958 #[test]
7959 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
7960 let fctx = &crate::decode::FrameCtx::new();
7961 // Transcribed from has_top_right/has_bottom_left's row_off==0,
7962 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
7963 // 128px reference grid) pinned as libaom pins it, independent of the
7964 // 64px superblock this crate actually codes.
7965 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
7966 if y == 0 || x + side >= width {
7967 return false;
7968 }
7969 let (row, col, per_side) = (
7970 (y % SUPERBLOCK) / side,
7971 (x % SUPERBLOCK) / side,
7972 SUPERBLOCK / side,
7973 );
7974 if row == 0 {
7975 return true;
7976 }
7977 if col + 1 == per_side {
7978 return false;
7979 }
7980 let stride = 128 / side;
7981 let index = row * stride + col;
7982 let table = if side == BLOCK {
7983 [95u8, 87].to_vec()
7984 } else {
7985 vec![255, 85, 119, 85, 127, 85, 119, 85]
7986 };
7987 (table[index / 8] >> (index % 8)) & 1 != 0
7988 }
7989
7990 fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool {
7991 if x == 0 || y + side >= height {
7992 return false;
7993 }
7994 let (row, col, per_side) = (
7995 (y % SUPERBLOCK) / side,
7996 (x % SUPERBLOCK) / side,
7997 SUPERBLOCK / side,
7998 );
7999 if col == 0 {
8000 return row * side + side < SUPERBLOCK;
8001 }
8002 if row + 1 == per_side {
8003 return false;
8004 }
8005 let stride = 128 / side;
8006 let index = row * stride + col;
8007 let table = if side == BLOCK {
8008 [4u8, 4].to_vec()
8009 } else {
8010 vec![84, 16, 84, 0, 84, 16, 84, 0]
8011 };
8012 (table[index / 8] >> (index % 8)) & 1 != 0
8013 }
8014
8015 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
8016 for side in [16usize, BLOCK] {
8017 for y in (0..height).step_by(side) {
8018 for x in (0..width).step_by(side) {
8019 let reach = Reach::of(side, x, y, width, height, fctx);
8020 assert_eq!(
8021 reach.above_right,
8022 libaom_top_right(side, x, y, width, height),
8023 "side={side} x={x} y={y}: above_right"
8024 );
8025 assert_eq!(
8026 reach.below_left,
8027 libaom_bottom_left(side, x, y, height, fctx),
8028 "side={side} x={x} y={y}: below_left"
8029 );
8030 }
8031 }
8032 }
8033 }
8034
8035 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
8036 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
8037 /// column inside the superblock) may read the below-left samples the
8038 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
8039 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
8040 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
8041 /// stream that partitions that small first hits the still-refused
8042 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
8043 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
8044 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
8045 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
8046 /// pixels -- lane-palette2 r12: the square multi-TU path used the
8047 /// standalone-block tables instead of this rule and granted a 16x16
8048 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
8049 #[test]
8050 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
8051 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
8052 // *_count_unit = tx size / 4.
8053 fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
8054 let (plane_bw_unit, count) = (bw / 4, tx / 4);
8055 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
8056 let _ = bh;
8057 if row_off_u > 0 {
8058 col_off_u + count < plane_bw_unit
8059 } else if col_off_u + count < plane_bw_unit {
8060 true
8061 } else {
8062 blk
8063 }
8064 }
8065 fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
8066 let (plane_bh_unit, count) = (bh / 4, tx / 4);
8067 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
8068 let _ = bw;
8069 if col_off_u > 0 {
8070 false
8071 } else if row_off_u + count < plane_bh_unit {
8072 true
8073 } else {
8074 blk
8075 }
8076 }
8077 for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
8078 for &tx in &[4usize, 8, 16, 32] {
8079 if tx > bw.min(bh) {
8080 continue;
8081 }
8082 for row_off in (0..bh).step_by(tx) {
8083 for col_off in (0..bw).step_by(tx) {
8084 for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] {
8085 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
8086 assert_eq!(
8087 got.above_right,
8088 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
8089 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
8090 );
8091 assert_eq!(
8092 got.below_left,
8093 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
8094 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
8095 );
8096 }
8097 }
8098 }
8099 }
8100 }
8101 }
8102
8103 #[test]
8104 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
8105 let fctx = &crate::decode::FrameCtx::new();
8106 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
8107 // Interior superblock, so neither the frame edge nor the col == 0 /
8108 // last-row early returns answer instead of the table.
8109 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
8110 let mut flipped = 0;
8111 for row in 0..8 {
8112 for col in 1..8 {
8113 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
8114 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
8115 let vert = {
8116 let _guard = Reach::vert_ab_partition();
8117 Reach::of(8, x, y, width, height, fctx).below_left
8118 };
8119 // The TR square of a VERT_A/_B sits at an even row, odd
8120 // column; every other slot must be untouched by the guard.
8121 if row % 2 == 0 && col % 2 == 1 {
8122 assert!(!raster, "raster below_left at row={row} col={col}");
8123 assert!(vert, "vert below_left at row={row} col={col}");
8124 flipped += 1;
8125 } else {
8126 assert_eq!(raster, vert, "guard moved row={row} col={col}");
8127 }
8128 }
8129 }
8130 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
8131 // The guard is scoped: it must not leak past its own block.
8132 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
8133 }
8134
8135 /// An odd width or height is refused by name, not by however the padder
8136 /// or the block coder would happen to fail on it.
8137 #[test]
8138 fn odd_dimensions_are_refused() {
8139 let fctx = &crate::decode::FrameCtx::new();
8140 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
8141 let picture = Picture::grey(width, height);
8142 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
8143 .expect_err(&format!("{width}x{height} is odd and must be refused"));
8144 assert!(
8145 err.to_string().contains("even"),
8146 "{width}x{height}: error was {err}"
8147 );
8148 }
8149 }
8150
8151 /// A sequence at a size that is not a multiple of the block grid decodes
8152 /// to the right frame count and the right size for every frame,
8153 /// including the inter frames whose reference is the previous frame's
8154 /// own (padded) reconstruction.
8155 #[test]
8156 fn sequence_round_trips_at_a_non_multiple_size() {
8157 let fctx = &crate::decode::FrameCtx::new();
8158 if !have_ffmpeg() {
8159 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
8160 return;
8161 }
8162 let (width, height) = (160usize, 96usize);
8163 let pictures: Vec<Picture> = (0..3)
8164 .map(|i| panned_test_card(width, height, i * 3))
8165 .collect();
8166 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
8167 assert_eq!(encoded.frames.len(), 3);
8168 for (i, frame) in encoded.frames.iter().enumerate() {
8169 assert_eq!(
8170 (frame.reconstruction.width, frame.reconstruction.height),
8171 (width, height),
8172 "frame {i}: reconstruction size"
8173 );
8174 }
8175 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
8176 // true (display) size a sequence's frames share, not the padded one.
8177 assert_eq!(
8178 ffprobe_size(&encoded.stream),
8179 (width as u32, height as u32),
8180 "sequence: ffprobe reports the true (display) size"
8181 );
8182 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
8183 assert_eq!(decoded.len(), 3, "decoded frame count");
8184 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
8185 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
8186 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
8187 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
8188 }
8189 }
8190
8191 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
8192 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
8193 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
8194 /// `pos + side_mi / 2 < bound` boundary), which is the case
8195 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
8196 /// refusing. A key frame alone already covered this size; this proves the
8197 /// inter tile writer's parity with it across a real multi-frame export.
8198 #[test]
8199 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
8200 let fctx = &crate::decode::FrameCtx::new();
8201 if !have_ffmpeg() {
8202 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
8203 return;
8204 }
8205 let (width, height) = (1280usize, 720usize);
8206 let pictures: Vec<Picture> = (0..3)
8207 .map(|i| panned_test_card(width, height, i * 3))
8208 .collect();
8209 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
8210 assert_eq!(encoded.frames.len(), 3);
8211 for (i, frame) in encoded.frames.iter().enumerate() {
8212 assert_eq!(
8213 (frame.reconstruction.width, frame.reconstruction.height),
8214 (width, height),
8215 "frame {i}: reconstruction size"
8216 );
8217 }
8218 assert_eq!(
8219 ffprobe_size(&encoded.stream),
8220 (width as u32, height as u32),
8221 "ffprobe reports the true (display) 1280x720 size"
8222 );
8223 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
8224 assert_eq!(decoded.len(), 3, "decoded frame count");
8225 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
8226 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
8227 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
8228 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
8229 }
8230 }
8231
8232 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
8233 /// leaf's own half (`has_half` at the SUB level) itself straddles the
8234 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
8235 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
8236 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
8237 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
8238 /// straddling-16x16 branch), so an inter frame no longer refuses this
8239 /// size either. This only proves the encoder does not error out -- see
8240 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
8241 /// decoder-clean proof (a 3-frame sequence, so the inter path is
8242 /// actually exercised).
8243 #[test]
8244 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
8245 let fctx = &crate::decode::FrameCtx::new();
8246 let (width, height) = (640usize, 360usize);
8247 let picture = Picture::grey(width, height);
8248 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
8249
8250 // `encode_sequence`'s second frame is the inter path: same size, now
8251 // wired the same way.
8252 let pictures = vec![picture.clone(), picture];
8253 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
8254 .expect("inter frame now codes the mod-32==8 straddle too");
8255 }
8256
8257 /// The r15 fix at production size: three 640x360 key frames (inter is
8258 /// still refused at this size, per the test above, so this stands in for
8259 /// the charter's "3-frame sequence" using three independent key frames of
8260 /// shifted content), each proven decoder-clean through ffmpeg rather than
8261 /// only encoder-clean.
8262 #[test]
8263 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
8264 let fctx = &crate::decode::FrameCtx::new();
8265 if !have_ffmpeg() {
8266 eprintln!(
8267 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
8268 no ffmpeg"
8269 );
8270 return;
8271 }
8272 let (width, height) = (640usize, 360usize);
8273 for shift in [0i64, 7, 19] {
8274 let picture = panned_test_card(width, height, shift);
8275 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8276 let decoded = ffmpeg_decode(&encoded.stream, width, height);
8277 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
8278 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
8279 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
8280 }
8281 }
8282
8283 /// The 640x360 straddle class, but through the inter path an actual
8284 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
8285 /// proves the leaf-8 inter stream this round wires up is not just
8286 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
8287 #[test]
8288 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
8289 let fctx = &crate::decode::FrameCtx::new();
8290 if !have_ffmpeg() {
8291 eprintln!(
8292 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
8293 );
8294 return;
8295 }
8296 let (width, height) = (640usize, 360usize);
8297 let pictures: Vec<Picture> = (0..4)
8298 .map(|i| panned_test_card(width, height, i * 3))
8299 .collect();
8300 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
8301 assert_eq!(encoded.frames.len(), 4);
8302 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
8303 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
8304 }
8305 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
8306 assert_eq!(decoded.len(), 4, "decoded frame count");
8307 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
8308 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
8309 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
8310 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
8311 }
8312 }
8313
8314 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
8315 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
8316 let out = Command::new("ffmpeg")
8317 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
8318 .args(["-vf", &format!("scale={width}:{height}")])
8319 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
8320 .output()
8321 .expect("ffmpeg failed to run");
8322 assert!(
8323 out.status.success(),
8324 "ffmpeg: {}",
8325 String::from_utf8_lossy(&out.stderr)
8326 );
8327 let (luma, chroma) = (width * height, width * height / 4);
8328 assert_eq!(
8329 out.stdout.len(),
8330 luma + 2 * chroma,
8331 "expected one 4:2:0 frame"
8332 );
8333 Picture {
8334 width,
8335 height,
8336 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
8337 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
8338 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
8339 }
8340 }
8341
8342 /// Prints what the mode search saves over DC prediction alone, for the
8343 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
8344 /// weight the search puts on rate can be swept.
8345 #[test]
8346 #[ignore = "a sweep, not a gate"]
8347 fn probe_lambda() {
8348 let fctx = &crate::decode::FrameCtx::new();
8349 let mut pictures = vec![
8350 ("test card".to_string(), test_card(160, 96)),
8351 ("stripes".to_string(), stripes(160, 96, true)),
8352 ];
8353 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
8354 for entry in clips.split(':').filter(|e| !e.is_empty()) {
8355 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
8356 let name = path.rsplit('/').next().unwrap_or(path).to_string();
8357 pictures.push((name, clip_frame(path, skip, 640, 352)));
8358 }
8359 }
8360 for (name, picture) in pictures {
8361 let dc = ladder(&picture, &[DC_PRED], fctx);
8362 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
8363 println!(
8364 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
8365 bd_rate(&dc, &searched) * 100.0,
8366 10f64.powf(searched[1].1),
8367 searched[1].0,
8368 10f64.powf(dc[1].1),
8369 dc[1].0,
8370 );
8371 }
8372 }
8373
8374 /// Prints the whole mode-search ladder, so two builds of the search can be
8375 /// compared against each other rather than each against its own baseline.
8376 #[test]
8377 #[ignore = "a sweep, not a gate"]
8378 fn probe_ladder() {
8379 let fctx = &crate::decode::FrameCtx::new();
8380 for (name, picture) in sweep_pictures() {
8381 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
8382 let points = all
8383 .iter()
8384 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
8385 .collect::<Vec<_>>()
8386 .join(" ");
8387 println!("ladder {name}: {points}");
8388 }
8389 }
8390
8391 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
8392 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
8393 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
8394 #[test]
8395 #[ignore = "a sweep, not a gate"]
8396 fn probe_split() {
8397 let fctx = &crate::decode::FrameCtx::new();
8398 for (name, picture) in sweep_pictures() {
8399 let ladder = |split: bool| {
8400 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
8401 .iter()
8402 .map(|&q| {
8403 let encoded = encode_key_frame_inner(
8404 &picture,
8405 q,
8406 0.5,
8407 &KEY_FRAME_MODES,
8408 split,
8409 (picture.width, picture.height),
8410 unspecified_color_config(), fctx,
8411 )
8412 .unwrap();
8413 (
8414 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
8415 (encoded.stream.len() as f64).log10(),
8416 )
8417 })
8418 .collect();
8419 points.sort_by(|a, b| a.0.total_cmp(&b.0));
8420 points
8421 };
8422 let (whole, split) = (ladder(false), ladder(true));
8423 let blocks = encode_key_frame_inner(
8424 &picture,
8425 90,
8426 0.5,
8427 &KEY_FRAME_MODES,
8428 true,
8429 (picture.width, picture.height),
8430 unspecified_color_config(), fctx,
8431 )
8432 .unwrap()
8433 .modes
8434 .len();
8435 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
8436 println!(
8437 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
8438 bd_rate(&whole, &split) * 100.0
8439 );
8440 }
8441 }
8442
8443 /// A striped picture, running one way or the other. The stripes are what
8444 /// separates a vertical predictor from a horizontal one: a mode search
8445 /// reading a transposed edge would pick the wrong one of the pair, which no
8446 /// symmetric picture would show.
8447 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
8448 let mut picture = Picture::grey(width, height);
8449 for y in 0..height {
8450 for x in 0..width {
8451 let along = if vertical { x } else { y };
8452 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
8453 }
8454 }
8455 picture
8456 }
8457
8458 /// Where two planes first disagree, and by how much: a mismatch reported as
8459 /// a position says which block and which sample of it went wrong, which a
8460 /// pair of thousand-sample arrays does not.
8461 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
8462 let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
8463 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
8464 Some(format!(
8465 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
8466 i % width,
8467 i / width,
8468 ours[i],
8469 theirs[i]
8470 ))
8471 }
8472
8473 /// Every mode the encoder offers has to predict what the decoder predicts,
8474 /// not just the ones a particular picture happens to choose: each is forced
8475 /// over a whole picture and the reconstruction gated against ffmpeg.
8476 #[test]
8477 fn every_mode_decodes_to_what_the_encoder_predicted() {
8478 let fctx = &crate::decode::FrameCtx::new();
8479 if !have_ffmpeg() {
8480 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
8481 return;
8482 }
8483 // 128 wide is a whole number of superblocks and 160 is not: the last
8484 // superblock of a 160-wide row is half a one, whose blocks have no
8485 // above-right samples inside the frame at all.
8486 for (width, height) in [(128, 96), (160, 96)] {
8487 let picture = test_card(width, height);
8488 for mode in KEY_FRAME_MODES {
8489 let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap();
8490 let decoded = ffmpeg_decode(&encoded.stream, width, height);
8491 for (plane, ours, theirs, stride) in [
8492 ("luma", &encoded.reconstruction.y, &decoded.y, width),
8493 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
8494 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
8495 ] {
8496 assert!(
8497 first_difference(ours, theirs, stride).is_none(),
8498 "{width}x{height} mode {mode}, {plane}: {}",
8499 first_difference(ours, theirs, stride).unwrap()
8500 );
8501 }
8502 assert!(
8503 encoded.modes.iter().all(|&m| m == mode),
8504 "mode {mode}: the encoder coded something else"
8505 );
8506 }
8507 }
8508 }
8509
8510 /// The search has to follow the picture: vertical stripes are cheapest
8511 /// predicted from the row above, horizontal ones from the column to the
8512 /// left. Reading the edges the other way round would swap the two answers
8513 /// while leaving every fidelity gate intact.
8514 #[test]
8515 fn the_search_picks_the_direction_the_picture_runs() {
8516 let fctx = &crate::decode::FrameCtx::new();
8517 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
8518 let picture = stripes(128, 96, vertical);
8519 // Only the pair, because on stripes a third mode predicts exactly
8520 // what the right one of the pair does -- PAETH reads the corner and
8521 // the left column, which a striped picture makes equal -- and the
8522 // tie then goes to whichever is cheaper to name, which is not what
8523 // this gate is about.
8524 let encoded =
8525 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
8526 // The first block of the picture has neither neighbour, so it
8527 // cannot tell the modes apart; every other one can.
8528 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
8529 assert!(
8530 picked * 2 > encoded.modes.len() - 1,
8531 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
8532 encoded.modes.len() - 1,
8533 encoded.modes
8534 );
8535 }
8536 }
8537
8538 /// What the search is for: the same picture, at the same quantizer, coded
8539 /// smaller and more faithfully than DC alone can manage.
8540 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
8541 /// between the two rate-distortion curves in log-rate against PSNR, as a
8542 /// fraction of the reference's rate. Negative means the second curve costs
8543 /// less for the same picture.
8544 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
8545 let low = reference[0].0.max(other[0].0);
8546 let high = reference[reference.len() - 1]
8547 .0
8548 .min(other[other.len() - 1].0);
8549 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
8550 // the non-directional one on the synthetic diagonals -- every point
8551 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
8552 // to integrate over any more. A curve that dominates that way has
8553 // saved everything the measure can express (the
8554 // `instrument-at-bound` class: the answer is at the instrument's own
8555 // edge, not undefined), so name it rather than panicking; anything
8556 // less clean than strict dominance still is.
8557 if high <= low {
8558 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
8559 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
8560 let dominates = other[0].0 > reference[reference.len() - 1].0
8561 && other_hi_rate <= ref_lo_rate;
8562 assert!(
8563 dominates,
8564 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
8565 );
8566 return -1.0;
8567 }
8568 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
8569 let i = curve
8570 .windows(2)
8571 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
8572 .unwrap_or(0);
8573 let (x0, y0) = curve[i];
8574 let (x1, y1) = curve[i + 1];
8575 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
8576 };
8577 let steps = 64;
8578 let mut area = 0.0;
8579 for step in 0..steps {
8580 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
8581 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
8582 }
8583 10f64.powf(area / f64::from(steps)) - 1.0
8584 }
8585
8586 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
8587 /// fidelity.
8588 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
8589 // A mode ablation measures the MODE search: the palette would code
8590 // these synthetic two-colour pictures losslessly under every arm and
8591 // leave nothing to compare (see [`force_screen`]).
8592 force_screen(Some(false));
8593 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
8594 .iter()
8595 .map(|&q| {
8596 let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
8597 (
8598 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
8599 (encoded.stream.len() as f64).log10(),
8600 )
8601 })
8602 .collect();
8603 points.sort_by(|a, b| a.0.total_cmp(&b.0));
8604 points
8605 }
8606
8607 /// What the search is for: the same pictures cost less to code at the same
8608 /// fidelity than DC prediction alone can manage. A picture that runs one
8609 /// way saves far more than a busy one, which is the shape a working
8610 /// directional pair has.
8611 #[test]
8612 fn the_search_beats_dc_alone() {
8613 let fctx = &crate::decode::FrameCtx::new();
8614 for (name, picture, want) in [
8615 ("test card", test_card(160, 96), -0.05),
8616 ("stripes", stripes(160, 96, true), -0.40),
8617 ] {
8618 let saved = bd_rate(
8619 &ladder(&picture, &[DC_PRED], fctx),
8620 &ladder(&picture, &NON_DIRECTIONAL, fctx),
8621 );
8622 assert!(
8623 saved < want,
8624 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
8625 saved * 100.0,
8626 -want * 100.0
8627 );
8628 }
8629 }
8630
8631 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
8632 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
8633 fn sweep_pictures() -> Vec<(String, Picture)> {
8634 let mut pictures = vec![
8635 ("test card".to_string(), test_card(160, 96)),
8636 ("stripes".to_string(), stripes(160, 96, true)),
8637 ("diagonal".to_string(), diagonal(160, 96, true)),
8638 ];
8639 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
8640 for entry in clips.split(':').filter(|e| !e.is_empty()) {
8641 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
8642 let name = path.rsplit('/').next().unwrap_or(path).to_string();
8643 pictures.push((name, clip_frame(path, skip, 640, 352)));
8644 }
8645 }
8646 pictures
8647 }
8648
8649 /// What the six directional modes are worth, per picture, at whatever
8650 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
8651 /// no further, and how often the search picks one.
8652 #[test]
8653 #[ignore = "a sweep, not a gate"]
8654 fn probe_directional() {
8655 let fctx = &crate::decode::FrameCtx::new();
8656 for (name, picture) in sweep_pictures() {
8657 let dc = ladder(&picture, &[DC_PRED], fctx);
8658 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
8659 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
8660 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
8661 let directional = encoded
8662 .modes
8663 .iter()
8664 .filter(|&&m| (3..=8).contains(&m))
8665 .count();
8666 // A picture whose ladders sit at different fidelities altogether
8667 // has no BD-rate to report -- see the flat-sample-window class.
8668 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
8669 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
8670 };
8671 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
8672 if overlap(a, b) {
8673 format!("{:+.2}%", bd_rate(a, b) * 100.0)
8674 } else {
8675 "no overlap".to_string()
8676 }
8677 };
8678 println!(
8679 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
8680 against(&flat, &all),
8681 against(&dc, &all),
8682 encoded.modes.len(),
8683 );
8684 }
8685 }
8686
8687 /// A picture whose stripes run along a diagonal, one way or the other.
8688 /// This is to the directional modes what [`stripes`] is to the vertical and
8689 /// horizontal pair: a predictor that walked the edge in the wrong direction
8690 /// would answer the two pictures the same way round.
8691 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
8692 let mut picture = Picture::grey(width, height);
8693 for y in 0..height {
8694 for x in 0..width {
8695 let along = if down_right { x + height - y } else { x + y };
8696 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
8697 }
8698 }
8699 picture
8700 }
8701
8702 /// The mode picked by the most blocks of a picture, ignoring the first
8703 /// block, which has no neighbours to tell the modes apart with.
8704 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
8705 // A mode ablation measures the MODE search: the palette would code
8706 // these synthetic two-colour pictures losslessly under every arm and
8707 // leave nothing to compare (see [`force_screen`]).
8708 force_screen(Some(false));
8709 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
8710 let blocks = &encoded.modes[1..];
8711 let mut counts = [0usize; 13];
8712 for &mode in blocks {
8713 counts[usize::from(mode)] += 1;
8714 }
8715 let (mode, count) = counts
8716 .iter()
8717 .enumerate()
8718 .max_by_key(|&(_, count)| *count)
8719 .expect("thirteen modes");
8720 (mode as u8, *count, blocks.len())
8721 }
8722
8723 /// The search has to follow a diagonal the way it runs: stripes down and to
8724 /// the right are cheapest predicted at 135 degrees, stripes down and to the
8725 /// left at 45. A walk that stepped the wrong way along the edge, or read
8726 /// the above row where it should read the left column, would swap these.
8727 #[test]
8728 fn the_search_picks_the_diagonal_the_picture_runs() {
8729 let fctx = &crate::decode::FrameCtx::new();
8730 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
8731 let picture = diagonal(160, 96, down_right);
8732 let (mode, count, blocks) = favourite_mode(&picture, fctx);
8733 assert_eq!(
8734 mode, want,
8735 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
8736 );
8737 }
8738 }
8739
8740 /// What the directional modes are for: a picture that runs along a diagonal
8741 /// costs far less to code with them than the seven that read only their own
8742 /// edges can manage, and a picture that runs no particular way costs no
8743 /// more. The second half is the one that bites: a mode set the search
8744 /// cannot price is a mode set that loses rate on content that does not want
8745 /// it, which is what costing the mode symbol is for.
8746 #[test]
8747 fn the_diagonals_beat_the_modes_that_read_no_further() {
8748 let fctx = &crate::decode::FrameCtx::new();
8749 for (name, picture, want) in [
8750 ("down-right", diagonal(160, 96, true), -0.20),
8751 ("down-left", diagonal(160, 96, false), -0.20),
8752 ("test card", test_card(160, 96), 0.01),
8753 ] {
8754 let saved = bd_rate(
8755 &ladder(&picture, &NON_DIRECTIONAL, fctx),
8756 &ladder(&picture, &KEY_FRAME_MODES, fctx),
8757 );
8758 assert!(
8759 saved < want,
8760 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
8761 saved * 100.0,
8762 -want * 100.0
8763 );
8764 }
8765 }
8766
8767 /// A mode the encoder cannot predict must be refused rather than coded as
8768 /// something else, and a search with nothing to choose from likewise.
8769 #[test]
8770 fn a_mode_the_encoder_cannot_predict_is_refused() {
8771 let fctx = &crate::decode::FrameCtx::new();
8772 let picture = test_card(64, 64);
8773 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
8774 .unwrap_err()
8775 .to_string();
8776 assert!(
8777 message.contains("intra mode 13"),
8778 "the refusal must name the mode, got {message}"
8779 );
8780 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
8781 }
8782
8783 /// The picture that comes back is the picture that went in, to within the
8784 /// quantizer. A prediction that read the wrong neighbours, or a block
8785 /// written into the wrong place, would still decode to what the encoder
8786 /// reconstructed — it is this gate that says the reconstruction is of the
8787 /// right picture.
8788 #[test]
8789 fn the_encoded_picture_is_the_one_that_went_in() {
8790 let fctx = &crate::decode::FrameCtx::new();
8791 let picture = test_card(160, 96);
8792 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8793 let luma = psnr(&encoded.reconstruction.y, &picture.y);
8794 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
8795 for (plane, (got, want)) in [
8796 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
8797 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
8798 ]
8799 .iter()
8800 .enumerate()
8801 {
8802 let chroma = psnr(got, want);
8803 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
8804 }
8805 }
8806
8807 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
8808 /// does the opposite. Both are monotone, which is what a rate-distortion
8809 /// loop above this will assume.
8810 #[test]
8811 fn fidelity_and_rate_move_with_the_quantizer() {
8812 let fctx = &crate::decode::FrameCtx::new();
8813 let picture = test_card(128, 128);
8814 let mut previous: Option<(usize, f64)> = None;
8815 for &q in &[70u8, 90, 110] {
8816 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
8817 let quality = psnr(&encoded.reconstruction.y, &picture.y);
8818 if let Some((bytes, better)) = previous {
8819 assert!(
8820 encoded.stream.len() < bytes,
8821 "q {q}: {} bytes",
8822 encoded.stream.len()
8823 );
8824 assert!(quality < better, "q {q}: PSNR {quality}");
8825 }
8826 previous = Some((encoded.stream.len(), quality));
8827 }
8828
8829 let mut previous = None;
8830 for &deadzone in &[0.5f64, 0.3, 0.15] {
8831 let encoded = encode_key_frame_with_ctx(&picture, 100, deadzone, fctx).unwrap();
8832 let quality = psnr(&encoded.reconstruction.y, &picture.y);
8833 if let Some((bytes, better)) = previous {
8834 assert!(
8835 encoded.stream.len() < bytes,
8836 "deadzone {deadzone}: {} bytes",
8837 encoded.stream.len()
8838 );
8839 assert!(quality < better, "deadzone {deadzone}: PSNR {quality}");
8840 }
8841 previous = Some((encoded.stream.len(), quality));
8842 }
8843
8844 // Bytes must not jump up across a q-context boundary: a wrong CDF
8845 // table for the far side would show up as a rate discontinuity here,
8846 // even though a coarser quantizer always codes no more than a finer
8847 // one on the same picture.
8848 //
8849 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
8850 // chroma searches its own mode, a coarser quantizer can pick a
8851 // *different* uv_mode on a block whose modes now cost nearly the
8852 // same, and the search prices that symbol against the static default
8853 // CDF while the writer codes it against an adapted one -- 311 -> 319
8854 // bytes at q 120->121 on this picture. The table this gate is really
8855 // watching would move the rate by far more than the mode churn does.
8856 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
8857 // same block can also change transform DEPTH between two neighbouring
8858 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
8859 // symbol is priced off the static CDF row 0 for the same reason the
8860 // uv_mode one is.
8861 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
8862 // path is pricing through the adapting CDF state (what
8863 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
8864 // drift of), after which the exact bound comes back.
8865 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
8866 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
8867 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
8868 assert!(
8869 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
8870 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
8871 );
8872 }
8873 }
8874
8875 /// A flat picture is a flat stream: every block predicts its neighbours'
8876 /// average, which is the picture's own value, and codes nothing.
8877 #[test]
8878 fn a_flat_picture_costs_almost_nothing() {
8879 let fctx = &crate::decode::FrameCtx::new();
8880 let mut picture = Picture::grey(128, 128);
8881 picture.y.fill(97);
8882 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8883 // The first block has no neighbour and predicts 128, so it carries a
8884 // DC; every block after it predicts 97 and carries nothing.
8885 assert!(
8886 encoded.stream.len() < 100,
8887 "{} bytes for a flat picture",
8888 encoded.stream.len()
8889 );
8890 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
8891 assert_eq!(s, 97, "sample {i} of a flat picture");
8892 }
8893 }
8894
8895 /// The sizes the encoder refuses, refused for a reason rather than by
8896 /// panicking somewhere below. Most sizes off the 32x32 block grid encode
8897 /// fine now (see `a_frame_round_trips_at_its_own_size`) -- the true frame
8898 /// edge lands past the halfway point of whichever block it falls in, so
8899 /// `PARTITION_NONE` or a single gathered split flag still says everything
8900 /// the spec needs. lane-av1-rect r7 wires the 8x8-leaf path live, so a
8901 /// 16x16 leaf straddling on exactly one axis (e.g. 40x32, cols mod 32 ==
8902 /// 8) now encodes too (see `a_frame_round_trips_at_its_own_size`'s
8903 /// sibling below). Only a leaf whose true edge cuts *both* axes (e.g.
8904 /// 40x40, both dims mod 32 == 8) needs the rectangular transform neither
8905 /// writer has, so that class is still refused, by name rather than by
8906 /// corrupting the stream.
8907 #[test]
8908 fn a_picture_off_the_block_grid_is_refused() {
8909 let fctx = &crate::decode::FrameCtx::new();
8910 let msg = encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
8911 .expect_err("40x40 straddles both axes of a 16x16 leaf, needs a rectangular transform")
8912 .to_string();
8913 assert!(msg.contains("rectangular"), "refusal: {msg}");
8914
8915 let mut short = Picture::grey(64, 64);
8916 short.u.truncate(10);
8917 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
8918 }
8919
8920 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
8921 /// column half only (`has_half` false on cols, true on rows) -- exactly
8922 /// the single-axis straddle lane-av1-rect r7 wires through
8923 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
8924 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
8925 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
8926 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
8927 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
8928 /// `partition_context_lookup` entry this writer ever produces (no 4x4
8929 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
8930 /// leaf regardless of neighbour state -- our writer already agreed with
8931 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
8932 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
8933 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
8934 /// it does not regress the gate. r11 tell-for-tell traced two further,
8935 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
8936 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
8937 /// leaves, when the second leaf's true above (or left) neighbour is the
8938 /// first leaf itself -- fixed by threading the first leaf's mode into the
8939 /// second leaf's context, mi-precise, like `record_mi` already does for
8940 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
8941 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
8942 /// `reduced_tx_set` is false), but this crate's key frames set
8943 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
8944 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
8945 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
8946 /// symbol bits to desync everything after it. Fixed with a new
8947 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
8948 /// eset/size slot). Both fixes are provably correct against libaom
8949 /// source and each closed part of the gap (leaf0's `eob` went from a
8950 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
8951 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
8952 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
8953 /// (do not reuse r11's committed logs, which predate its own fixes) and
8954 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
8955 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
8956 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
8957 /// every other `write_block` caller at 16x16 and up already passes
8958 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
8959 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
8960 /// different amount of arithmetic range and derailed everything after
8961 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
8962 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
8963 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
8964 /// never updating those coarse arrays itself -- so a *second* straddling
8965 /// 16x16 quadrant stacked above or left of the first (never covered by
8966 /// r11's same-call `prev_leaf` override, which only threads state
8967 /// between the two leaves of one shared quadrant) read whatever stale
8968 /// mode sat in that slot before either leaf ran. Fixed by writing the
8969 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
8970 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
8971 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
8972 /// offset of a single unit; fixing (3)+(4) together still leaves a
8973 /// residual divergence one leaf further in -- the decoder now reads
8974 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
8975 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
8976 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
8977 /// desyncs the stream by exactly the width of one earlier symbol -- not
8978 /// yet isolated to a single named symbol. r15 found the last bug: the
8979 /// header fix from r14 explained the rng skew fully, and the remaining
8980 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
8981 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
8982 /// loop, once per leaf, so the first leaf's write clobbered the true
8983 /// external neighbour mode the second leaf of the *same* straddling
8984 /// quadrant still needed for its non-adjacency axis (a column-straddle
8985 /// case: two leaves share one `outer_at` column index, so leaf 1's
8986 /// write to `left_mode[r]` overwrote the real western neighbour before
8987 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
8988 /// doing it once, after the whole leaf loop, from the last (bottom/
8989 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
8990 #[test]
8991 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
8992 let fctx = &crate::decode::FrameCtx::new();
8993 if !have_ffmpeg() {
8994 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
8995 return;
8996 }
8997 let (width, height) = (40usize, 32usize);
8998 let picture = test_card(width, height);
8999 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
9000 assert_eq!(
9001 (encoded.reconstruction.width, encoded.reconstruction.height),
9002 (width, height)
9003 );
9004 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
9005 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
9006 }
9007 let decoded = ffmpeg_decode(&encoded.stream, width, height);
9008 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
9009 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
9010 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
9011 }
9012
9013 /// A frame of real video, rather than a picture built to be easy.
9014 ///
9015 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
9016 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
9017 /// encoder's reconstruction has to survive the same equality gate as the
9018 /// synthetic pictures — real video reaches contexts a test card does not.
9019 #[test]
9020 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
9021 let fctx = &crate::decode::FrameCtx::new();
9022 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
9023 eprintln!(
9024 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
9025 set EC_AV1_CLIP to a clip"
9026 );
9027 return;
9028 };
9029 if !have_ffmpeg() {
9030 eprintln!(
9031 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
9032 );
9033 return;
9034 }
9035 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
9036 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
9037 // test quick while still spanning many superblocks.
9038 let (width, height) = (640usize, 352usize);
9039 let picture = clip_frame(&clip, &skip, width, height);
9040
9041 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
9042 let decoded = ffmpeg_decode(&encoded.stream, width, height);
9043 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
9044 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
9045 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
9046 eprintln!(
9047 "{} bytes, luma PSNR {:.2} dB",
9048 encoded.stream.len(),
9049 psnr(&decoded.y, &picture.y)
9050 );
9051 }
9052
9053 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
9054 /// sequence of these is a translation a motion search can actually find
9055 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
9056 /// inter frame's rate against the key frame's is measuring the same
9057 /// picture moving, not two different pictures.
9058 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
9059 let mut picture = Picture::grey(width, height);
9060 for y in 0..height {
9061 for x in 0..width {
9062 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
9063 let gradient = sx * 200.0 / width as f64;
9064 let ripple = 30.0
9065 * (sx * std::f64::consts::PI / 23.0).sin()
9066 * (y as f64 * std::f64::consts::PI / 37.0).cos();
9067 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
9068 40.0
9069 } else {
9070 0.0
9071 };
9072 picture.y[y * width + x] =
9073 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
9074 }
9075 }
9076 for y in 0..height / 2 {
9077 for x in 0..width / 2 {
9078 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
9079 let i = y * width / 2 + x;
9080 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
9081 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
9082 }
9083 }
9084 picture
9085 }
9086
9087 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
9088 fn ffmpeg_decode_sequence(
9089 stream: &[u8],
9090 width: usize,
9091 height: usize,
9092 frames: usize,
9093 ) -> Vec<Picture> {
9094 let mut child = Command::new("ffmpeg")
9095 .args([
9096 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
9097 ])
9098 .stdin(Stdio::piped())
9099 .stdout(Stdio::piped())
9100 .stderr(Stdio::piped())
9101 .spawn()
9102 .expect("ffmpeg failed to start");
9103 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
9104 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
9105 // fills before the last input byte is written -- which is exactly what
9106 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
9107 // (measured: 45 min, both processes at 0% CPU). A write error here is
9108 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
9109 // below, are the real diagnosis.
9110 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
9111 let payload = stream.to_vec();
9112 let writer = std::thread::spawn(move || {
9113 let _ = stdin.write_all(&payload);
9114 });
9115 let out = child.wait_with_output().expect("ffmpeg failed to run");
9116 writer.join().expect("ffmpeg stdin writer thread");
9117 assert!(
9118 out.status.success(),
9119 "ffmpeg refused the stream: {}",
9120 String::from_utf8_lossy(&out.stderr)
9121 );
9122 let (luma, chroma) = (width * height, width * height / 4);
9123 let frame_bytes = luma + 2 * chroma;
9124 assert_eq!(
9125 out.stdout.len(),
9126 frame_bytes * frames,
9127 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
9128 String::from_utf8_lossy(&out.stderr)
9129 );
9130 (0..frames)
9131 .map(|i| {
9132 let base = i * frame_bytes;
9133 Picture {
9134 width,
9135 height,
9136 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
9137 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
9138 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
9139 }
9140 })
9141 .collect()
9142 }
9143
9144 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
9145 /// makes for a key frame, extended down the reference chain: each inter
9146 /// frame's reconstruction predicts from the previous frame's own decoded
9147 /// reconstruction, so a single sample of drift anywhere would propagate
9148 /// into every frame after it -- which is why every frame is checked, not
9149 /// just the last one, and why this is an equality and not a tolerance.
9150 #[test]
9151 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
9152 let fctx = &crate::decode::FrameCtx::new();
9153 if !have_ffmpeg() {
9154 eprintln!(
9155 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
9156 );
9157 return;
9158 }
9159 let (width, height) = (128usize, 64usize);
9160 let pictures: Vec<Picture> = (0..5)
9161 .map(|i| panned_test_card(width, height, i * 3))
9162 .collect();
9163 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
9164 assert_eq!(encoded.frames.len(), 5);
9165
9166 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
9167 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
9168 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
9169 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
9170 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
9171 }
9172
9173 eprintln!("frame bytes luma PSNR (dB) inter share");
9174 for (i, frame) in encoded.frames.iter().enumerate() {
9175 eprintln!(
9176 "{i:5} {:5} {:14.2} {:11.2}",
9177 frame.stream.len(),
9178 psnr(&frame.reconstruction.y, &pictures[i].y),
9179 frame.inter_block_share
9180 );
9181 }
9182 }
9183
9184 /// The same sequence through OUR OWN decoder, sample-exact against the
9185 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
9186 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
9187 /// divergence point at all, while our decoder can be traced symbol by
9188 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
9189 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
9190 /// names the first differing frame, plane and position.
9191 #[test]
9192 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
9193 let fctx = &crate::decode::FrameCtx::new();
9194 let (width, height) = (128usize, 64usize);
9195 let pictures: Vec<Picture> =
9196 (0..5).map(|i| panned_test_card(width, height, i * 3)).collect();
9197 let _ = take_inter_tx_split_hits();
9198 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
9199 let split = take_inter_tx_split_hits();
9200 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
9201 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
9202 // content splits -- a green round trip in which the split never fires
9203 // would prove only the flat path.
9204 if tx_select() && tx_select_inter() {
9205 assert!(split[1] > 0, "the inter var-tx split never fired");
9206 }
9207 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
9208 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
9209 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
9210 let recon = &frame.reconstruction;
9211 for (plane, got, want, stride) in [
9212 ("luma", &dec.y, &recon.y, width),
9213 ("U", &dec.u, &recon.u, width / 2),
9214 ("V", &dec.v, &recon.v, width / 2),
9215 ] {
9216 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
9217 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
9218 panic!(
9219 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
9220 reconstruction {} ({} of {} samples differ)",
9221 at % stride,
9222 at / stride,
9223 got[at],
9224 want[at],
9225 got.iter().zip(want).filter(|(a, b)| a != b).count(),
9226 got.len(),
9227 );
9228 }
9229 }
9230 }
9231 }
9232
9233 /// The rate term the mode search ranks every decision by has to be the
9234 /// rate the writer then spends. The search prices a block's coefficients
9235 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
9236 /// against the default CDFs a tile starts from and the contexts of a
9237 /// block whose neighbours coded nothing -- while the tile writer codes
9238 /// them against a state that has been adapting all frame (the
9239 /// price-the-narrowing class). This measures that drift: the sum of what
9240 /// the search paid for the coefficients it kept, against the bytes the
9241 /// writer actually emitted for the whole tile (which also carries the
9242 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
9243 /// expected to be the larger of the two).
9244 #[test]
9245 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
9246 let fctx = &crate::decode::FrameCtx::new();
9247 let (width, height) = (256usize, 128usize);
9248 let pictures: Vec<Picture> = (0..5)
9249 .map(|i| panned_test_card(width, height, i * 2))
9250 .collect();
9251 let _ = take_predicted_bits();
9252 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
9253 let predicted = take_predicted_bits();
9254 assert_eq!(predicted.len(), encoded.frames.len());
9255
9256 eprintln!("frame predicted bits written bits drift");
9257 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
9258 // defect this gate exists to catch), a positive one is the written
9259 // side carrying syntax the coefficient sum leaves out -- and since
9260 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
9261 // on that side, so the two directions no longer share a bound.
9262 let mut worst_over: f64 = 0.0;
9263 let mut worst_under: f64 = 0.0;
9264 for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() {
9265 let written = frame.tile.len() as f64 * 8.0;
9266 let drift = (written - bits) / written;
9267 worst_over = worst_over.max(-drift);
9268 worst_under = worst_under.max(drift);
9269 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
9270 }
9271 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
9272 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
9273 // over-prices every frame but the last (its sum EXCLUDES the
9274 // partition/mode/skip/mv syntax the written side carries, so the true
9275 // coefficient over-price is larger still): the writer's CDFs adapt to
9276 // the content while the search's stay at the defaults. The bound is
9277 // set just above the worst measured point -- a widening drift is the
9278 // thing this gate exists to catch.
9279 assert!(
9280 worst_over <= 0.16,
9281 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
9282 worst_over * 100.0
9283 );
9284 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
9285 // the worst inter frame, where nearly every block now codes an MV
9286 // residual and a reference the coefficient sum never counts. Re-measured
9287 // at +29.6% once the encoder's grid published compound blocks properly
9288 // (compound share 8.8% -> 11.5%): a compound block carries a second
9289 // reference tree, a compound mode symbol and -- for the half-new modes
9290 // -- an MV residual, none of which the coefficient sum counts.
9291 assert!(
9292 worst_under <= 0.32,
9293 "the writer spent {:.2}% more than the search priced -- more than \
9294 the mode/mv syntax outside the coefficient sum explains",
9295 worst_under * 100.0
9296 );
9297 }
9298
9299 /// Low motion has to actually buy something: at least one inter frame of
9300 /// a panning sequence has to cost fewer bytes than the key frame that
9301 /// starts it, and the inter-block share it prints has to be non-zero --
9302 /// a search that never picks an inter mode would still pass a rate gate
9303 /// on a picture with no motion in it (the class this repo calls
9304 /// gate-blind-to-feature), so the share is printed even though it is not
9305 /// asserted on beyond being reachable at all.
9306 #[test]
9307 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
9308 let fctx = &crate::decode::FrameCtx::new();
9309 let (width, height) = (256usize, 128usize);
9310 let pictures: Vec<Picture> = (0..5)
9311 .map(|i| panned_test_card(width, height, i * 2))
9312 .collect();
9313 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
9314
9315 let key_bytes = encoded.frames[0].stream.len();
9316 eprintln!("frame bytes inter share");
9317 for (i, frame) in encoded.frames.iter().enumerate() {
9318 eprintln!(
9319 "{i:5} {:5} {:11.2}",
9320 frame.stream.len(),
9321 frame.inter_block_share
9322 );
9323 }
9324 assert!(
9325 encoded.frames[1..]
9326 .iter()
9327 .any(|f| f.stream.len() < key_bytes),
9328 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
9329 );
9330 assert!(
9331 encoded.frames[1..]
9332 .iter()
9333 .any(|f| f.inter_block_share > 0.0),
9334 "no inter frame coded a single inter block -- the search never fired"
9335 );
9336 }
9337
9338 /// A manual perf probe, not a gate: prints where a key frame's and an
9339 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
9340 /// measures before it optimizes rather than guessing. Run with
9341 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
9342 #[test]
9343 #[ignore = "a perf probe, not a gate"]
9344 fn stage_timing_breakdown() {
9345 let fctx = &crate::decode::FrameCtx::new();
9346 use std::time::Instant;
9347
9348 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
9349 let picture = test_card(width, height);
9350
9351 let t = Instant::now();
9352 let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
9353 let dc_only_t = t.elapsed();
9354
9355 let t = Instant::now();
9356 let non_directional =
9357 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
9358 let non_directional_t = t.elapsed();
9359
9360 let t = Instant::now();
9361 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
9362 let all_modes_t = t.elapsed();
9363
9364 eprintln!(
9365 "\n=== key frame {width}x{height} ===\n\
9366 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
9367 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
9368 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
9369 dc_only.stream.len(),
9370 non_directional.stream.len(),
9371 all_modes.stream.len(),
9372 );
9373
9374 // One inter frame predicting off the key frame's own
9375 // reconstruction, the (256, 256)-padded surface encode_sequence
9376 // itself would hand encode_inter_frame.
9377 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
9378 let padded_pic = picture.padded_to(SUPERBLOCK);
9379 let t = Instant::now();
9380 let inter =
9381 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();
9382 let inter_t = t.elapsed();
9383 eprintln!(
9384 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
9385 {:.2})",
9386 inter.stream.len(),
9387 inter.inter_block_share
9388 );
9389 }
9390
9391 // Isolated per-call cost of the trial pipeline's own stages, at both
9392 // transform sizes the search runs, averaged over enough calls to
9393 // rise above `Instant::now`'s own noise.
9394 for side in [16usize, 32] {
9395 const N: u32 = 20_000;
9396 let residual: Vec<i32> = (0..side * side)
9397 .map(|i| ((i * 37 % 61) as i32) - 30)
9398 .collect();
9399
9400 let t = Instant::now();
9401 let mut levels = Vec::new();
9402 for _ in 0..N {
9403 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
9404 }
9405 let forward_t = t.elapsed() / N;
9406
9407 let t = Instant::now();
9408 for _ in 0..N {
9409 std::hint::black_box(dequant_and_inverse(&levels, side, 8, 100));
9410 }
9411 let inverse_t = t.elapsed() / N;
9412
9413 let set = if side == 32 {
9414 crate::cdf_state::TxbSet::Luma32
9415 } else {
9416 crate::cdf_state::TxbSet::Luma16
9417 };
9418 let t = Instant::now();
9419 for _ in 0..N {
9420 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2));
9421 }
9422 let entropy_t = t.elapsed() / N;
9423
9424 let above = vec![128u8; side * 2];
9425 let left = vec![128u8; side * 2];
9426 let mut prediction = vec![0u8; side * side];
9427 let t = Instant::now();
9428 for _ in 0..N {
9429 intra_predict_u8(
9430 D45_PRED,
9431 0,
9432 Some(&above),
9433 Some(&left),
9434 Some(128),
9435 side,
9436 side,
9437 false,
9438 false,
9439 &mut prediction, fctx,
9440 );
9441 }
9442 let predict_t = t.elapsed() / N;
9443
9444 eprintln!(
9445 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
9446 predict (1 directional mode): {predict_t:>9.2?}\n\
9447 forward_and_quantize: {forward_t:>9.2?}\n\
9448 dequant_and_inverse: {inverse_t:>9.2?}\n\
9449 coeff_bits: {entropy_t:>9.2?}"
9450 );
9451 }
9452 }
9453
9454 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
9455 /// (motion search, [`crate::mc::predict`], transform+quantize,
9456 /// `coeff_bits`), plus what is left over once those are subtracted --
9457 /// the thirteen-mode intra-candidate loop `search_inter_block` still
9458 /// runs on every inter block (its own transform/quant/entropy calls are
9459 /// already inside buckets 2/3, so "left over" here is everything NOT
9460 /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
9461 /// symbol-cost lookups outside `coeff_bits`).
9462 ///
9463 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
9464 #[test]
9465 #[ignore = "a perf probe, not a gate"]
9466 fn stage_timing_breakdown_inter() {
9467 let fctx = &crate::decode::FrameCtx::new();
9468 use std::time::Instant;
9469
9470 let (width, height) = (1280usize, 720);
9471 let picture = test_card(width, height);
9472 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
9473 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
9474 let padded_pic = picture.padded_to(SUPERBLOCK);
9475
9476 stage_reset();
9477 let t = Instant::now();
9478 let inter =
9479 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();
9480 let total_t = t.elapsed();
9481 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
9482 let accounted = motion_search + transform_quant + entropy;
9483 // motion_search already contains interpolation's own time (every
9484 // candidate the search costs calls crate::mc::predict), so it is not
9485 // added again here -- interpolation is reported alongside as "of
9486 // which interpolation", not as a fifth additive bucket.
9487 let other = total_t.saturating_sub(accounted);
9488
9489 eprintln!(
9490 "\n=== inter frame {width}x{height}, one frame ===\n\
9491 total: {total_t:>9.2?} ({} bytes)\n\
9492 motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
9493 {interpolation:>9.2?})\n\
9494 transform + quantize: {transform_quant:>9.2?}\n\
9495 coeff_bits (entropy pricing): {entropy:>9.2?}\n\
9496 everything else (13-mode intra {other:>9.2?}\n\
9497 candidate loop's own predict/bookkeeping, NEARESTMV's own \
9498 predict, RD glue):",
9499 inter.stream.len(),
9500 );
9501 }
9502
9503 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
9504 /// frames (a dark/flat one, a detailed one, a normal film one) at two
9505 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
9506 /// None`, the baseline this same build produces without
9507 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
9508 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
9509 /// go in the lane report, which is where "ship as default" is decided --
9510 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
9511 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
9512 #[test]
9513 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
9514 fn prune_k_quality_sweep() {
9515 let fctx = &crate::decode::FrameCtx::new();
9516 if !have_ffmpeg() {
9517 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
9518 return;
9519 }
9520 let (width, height) = (640usize, 352usize);
9521 let frames: &[(&str, &str, &str)] = &[
9522 // (label, clip, seek) -- a near-black scene, a busy one, and an
9523 // ordinary film frame, each from a different real file.
9524 (
9525 "dark/flat",
9526 "/home/user/Videos/reela.mp4",
9527 "3",
9528 ),
9529 (
9530 "detailed",
9531 "/home/user/Downloads/reelb.mkv",
9532 "1200",
9533 ),
9534 (
9535 "film",
9536 "/home/user/Videos/Films/reelc.mkv",
9537 "600",
9538 ),
9539 ];
9540 for &(label, clip, skip) in frames {
9541 if !std::path::Path::new(clip).exists() {
9542 eprintln!("SKIP {label}: {clip} not present on this machine");
9543 continue;
9544 }
9545 let picture = clip_frame(clip, skip, width, height);
9546 for &q in &[60u8, 150] {
9547 // SAFETY (not literally unsafe, just process-global): this is
9548 // a single-threaded #[ignore] probe, run by hand, never
9549 // alongside other tests that read Search::top_k.
9550 set_test_top_k_override(None);
9551 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
9552 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
9553 eprint!(
9554 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
9555 baseline.stream.len(),
9556 baseline_psnr
9557 );
9558 for &k in &[3usize, 4, 6] {
9559 set_test_top_k_override(Some(k));
9560 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
9561 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
9562 eprint!(
9563 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
9564 pruned.stream.len(),
9565 pruned_psnr,
9566 pruned_psnr - baseline_psnr
9567 );
9568 }
9569 eprintln!();
9570 }
9571 }
9572 set_test_top_k_override(None);
9573 }
9574
9575 /// Two consecutive decoded frames from one clip, for an inter-frame
9576 /// sweep -- [`clip_frame`] alone only ever gives one.
9577 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
9578 let out = Command::new("ffmpeg")
9579 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
9580 .args(["-vf", &format!("scale={width}:{height}")])
9581 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
9582 .output()
9583 .expect("ffmpeg failed to run");
9584 assert!(
9585 out.status.success(),
9586 "ffmpeg: {}",
9587 String::from_utf8_lossy(&out.stderr)
9588 );
9589 let (luma, chroma) = (width * height, width * height / 4);
9590 let frame_len = luma + 2 * chroma;
9591 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
9592 std::array::from_fn(|i| {
9593 let bytes = &out.stdout[i * frame_len..][..frame_len];
9594 Picture {
9595 width,
9596 height,
9597 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
9598 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
9599 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
9600 }
9601 })
9602 }
9603
9604 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
9605 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
9606 /// then one inter frame off it (`search_inter_block`'s own intra
9607 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
9608 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
9609 /// padding step complicates the comparison. Prints bytes and luma PSNR
9610 /// for the inter frame alone, unpruned vs each `K`.
9611 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
9612 #[test]
9613 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
9614 fn prune_k_quality_sweep_inter() {
9615 let fctx = &crate::decode::FrameCtx::new();
9616 if !have_ffmpeg() {
9617 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
9618 return;
9619 }
9620 let (width, height) = (1280usize, 704usize);
9621 let frames: &[(&str, &str, &str)] = &[
9622 (
9623 "dark/flat",
9624 "/home/user/Videos/reela.mp4",
9625 "3",
9626 ),
9627 (
9628 "detailed",
9629 "/home/user/Downloads/reelb.mkv",
9630 "1200",
9631 ),
9632 (
9633 "film",
9634 "/home/user/Videos/Films/reelc.mkv",
9635 "600",
9636 ),
9637 ];
9638 for &(label, clip, skip) in frames {
9639 if !std::path::Path::new(clip).exists() {
9640 eprintln!("SKIP {label}: {clip} not present on this machine");
9641 continue;
9642 }
9643 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
9644 for &q in &[60u8, 150] {
9645 // SAFETY (not literally unsafe, just process-global): a
9646 // single-threaded #[ignore] probe, run by hand, never
9647 // alongside other tests that read Search::top_k.
9648 set_test_top_k_override_inter(None);
9649 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
9650 let baseline = encode_inter_frame(
9651 &inter_source,
9652 &key.reconstruction,
9653 q,
9654 0.5,
9655 1,
9656 flat_order_hints(1, 0, false),
9657 (width, height), None, None, None, fctx, None,
9658 )
9659 .unwrap();
9660 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
9661 eprint!(
9662 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
9663 baseline.stream.len(),
9664 baseline_psnr
9665 );
9666 for &k in &[3usize, 4, 6] {
9667 set_test_top_k_override_inter(Some(k));
9668 let pruned = encode_inter_frame(
9669 &inter_source,
9670 &key.reconstruction,
9671 q,
9672 0.5,
9673 1,
9674 flat_order_hints(1, 0, false),
9675 (width, height), None, None, None, fctx, None,
9676 )
9677 .unwrap();
9678 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
9679 eprint!(
9680 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
9681 pruned.stream.len(),
9682 pruned_psnr,
9683 pruned_psnr - baseline_psnr
9684 );
9685 }
9686 eprintln!();
9687 }
9688 }
9689 set_test_top_k_override_inter(None);
9690 }
9691
9692 /// `frames` consecutive pictures out of a real clip, scaled to a whole
9693 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
9694 /// to an arbitrary count for the fixture regression gate below.
9695 fn clip_frames(
9696 clip: &str,
9697 skip: &str,
9698 width: usize,
9699 height: usize,
9700 frames: usize,
9701 ) -> Vec<Picture> {
9702 let out = Command::new("ffmpeg")
9703 .args(["-v", "error", "-ss", skip, "-i", clip])
9704 .args(["-frames:v", &frames.to_string()])
9705 .args(["-vf", &format!("scale={width}:{height}")])
9706 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
9707 .output()
9708 .expect("ffmpeg failed to run");
9709 assert!(
9710 out.status.success(),
9711 "ffmpeg: {}",
9712 String::from_utf8_lossy(&out.stderr)
9713 );
9714 let (luma, chroma) = (width * height, width * height / 4);
9715 let frame_len = luma + 2 * chroma;
9716 assert_eq!(
9717 out.stdout.len(),
9718 frame_len * frames,
9719 "expected {frames} 4:2:0 frames"
9720 );
9721 (0..frames)
9722 .map(|i| {
9723 let bytes = &out.stdout[i * frame_len..][..frame_len];
9724 Picture {
9725 width,
9726 height,
9727 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
9728 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
9729 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
9730 }
9731 })
9732 .collect()
9733 }
9734
9735 /// The standing regression gate on real content: 12 frames of a real
9736 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
9737 /// this crate's own input regardless of its own source codec), encoded
9738 /// as an AV1 GOP and checked against three numeric floors so a
9739 /// compatibility or quality regression fails the suite instead of
9740 /// waiting for a downstream repo's gate to catch it (as happened for a
9741 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
9742 /// refusal, both caught only that way).
9743 ///
9744 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
9745 /// that geometry is already covered elsewhere), chosen only so encode
9746 /// time and gate numbers are not muddied by an edge-block class this
9747 /// test is not about.
9748 ///
9749 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
9750 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
9751 /// below carry a margin off those measured numbers (PSNR floor =
9752 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
9753 #[test]
9754 fn real_clip_encodes_within_its_quality_and_size_budget() {
9755 let fctx = &crate::decode::FrameCtx::new();
9756 if !have_ffmpeg() {
9757 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
9758 return;
9759 }
9760 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9761 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
9762 if !clip.exists() {
9763 eprintln!(
9764 "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing",
9765 clip.display()
9766 );
9767 return;
9768 }
9769 let (width, height, frame_count) = (640usize, 384usize, 12usize);
9770 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
9771 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
9772 assert_eq!(encoded.frames.len(), frame_count);
9773
9774 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
9775 // stream and hands back every frame -- a stream a downstream
9776 // decoder refuses is the exact class of regression this gate
9777 // exists for.
9778 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
9779 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
9780
9781 // Gate 2: quality vs the source did not silently collapse.
9782 let mean_psnr: f64 = decoded
9783 .iter()
9784 .zip(&source)
9785 .map(|(d, s)| psnr(&d.y, &s.y))
9786 .sum::<f64>()
9787 / frame_count as f64;
9788 assert!(
9789 mean_psnr >= 44.91,
9790 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
9791 );
9792
9793 // Gate 3: the stream did not silently bloat.
9794 assert!(
9795 encoded.stream.len() <= 80_340,
9796 "stream grew to {} bytes, over the 80340-byte ceiling",
9797 encoded.stream.len()
9798 );
9799 }
9800
9801 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
9802 /// straddle size: 640x384 is exact on both axes (32-aligned), so
9803 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
9804 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
9805 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
9806 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
9807 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
9808 /// card; this one is the real-clip gate, same three floors.
9809 ///
9810 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
9811 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
9812 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
9813 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
9814 #[test]
9815 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
9816 let fctx = &crate::decode::FrameCtx::new();
9817 if !have_ffmpeg() {
9818 eprintln!(
9819 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
9820 no ffmpeg"
9821 );
9822 return;
9823 }
9824 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9825 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
9826 if !clip.exists() {
9827 eprintln!(
9828 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
9829 {} missing",
9830 clip.display()
9831 );
9832 return;
9833 }
9834 let (width, height, frame_count) = (704usize, 400usize, 8usize);
9835 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
9836 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
9837 assert_eq!(encoded.frames.len(), frame_count);
9838
9839 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
9840 // stream and hands back every frame.
9841 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
9842 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
9843
9844 // Gate 2: quality vs the source did not silently collapse.
9845 let mean_psnr: f64 = decoded
9846 .iter()
9847 .zip(&source)
9848 .map(|(d, s)| psnr(&d.y, &s.y))
9849 .sum::<f64>()
9850 / frame_count as f64;
9851 assert!(
9852 mean_psnr >= 44.98,
9853 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
9854 );
9855
9856 // Gate 3: the stream did not silently bloat.
9857 assert!(
9858 encoded.stream.len() <= 62_703,
9859 "stream grew to {} bytes, over the 62703-byte ceiling",
9860 encoded.stream.len()
9861 );
9862 }
9863
9864 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
9865 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
9866 /// facade -- timed end to end, so the edith export-time projection is a
9867 /// real number rather than a guess from the isolated key/inter numbers
9868 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
9869 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
9870 #[test]
9871 #[ignore = "a perf probe, not a gate"]
9872 fn sequence_bench_sanity() {
9873 let fctx = &crate::decode::FrameCtx::new();
9874 use std::time::Instant;
9875 let (width, height) = (1280usize, 720usize);
9876 let pictures: Vec<Picture> = (0..24)
9877 .map(|i| panned_test_card(width, height, i * 3))
9878 .collect();
9879 let t = Instant::now();
9880 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
9881 let elapsed = t.elapsed();
9882 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
9883 eprintln!(
9884 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
9885 elapsed / 24
9886 );
9887 }
9888
9889 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
9890 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
9891 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
9892 /// -- --ignored --nocapture`.
9893 #[test]
9894 #[ignore = "a calibration probe, not a gate"]
9895 fn calibration_sweep_base_q_idx() {
9896 let fctx = &crate::decode::FrameCtx::new();
9897 if !have_ffmpeg() {
9898 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
9899 return;
9900 }
9901 let (width, height, frames) = (640usize, 384usize, 12usize);
9902 for clip in [
9903 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
9904 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
9905 ] {
9906 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
9907 .join("../../fixtures/video")
9908 .join(clip);
9909 if !path.exists() {
9910 eprintln!("SKIP {clip}: fixture missing");
9911 continue;
9912 }
9913 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
9914 eprintln!("--- {clip} ---");
9915 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
9916 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
9917 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
9918 let mean_psnr: f64 = decoded
9919 .iter()
9920 .zip(&source)
9921 .map(|(d, s)| psnr(&d.y, &s.y))
9922 .sum::<f64>()
9923 / frames as f64;
9924 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
9925 eprintln!(
9926 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
9927 encoded.stream.len()
9928 );
9929 }
9930 }
9931 }
9932
9933 // -----------------------------------------------------------------------
9934 // The encoder's standing BD-rate baseline against libaom and rav1e.
9935 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
9936 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
9937 // agreeing with our encoder proves nothing about the bitstream.
9938 // -----------------------------------------------------------------------
9939
9940 /// All-plane PSNR of a decoded picture against its source, on the same
9941 /// 8-bit scale [`psnr`] uses.
9942 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
9943 let cat = |p: &Picture| {
9944 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
9945 v.extend_from_slice(&p.y);
9946 v.extend_from_slice(&p.u);
9947 v.extend_from_slice(&p.v);
9948 v
9949 };
9950 psnr(&cat(decoded), &cat(source))
9951 }
9952
9953 /// The pictures back as the planar 8-bit bytes an encoder reads.
9954 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
9955 let mut raw = Vec::new();
9956 for p in source {
9957 for plane in [&p.y, &p.u, &p.v] {
9958 raw.extend(plane.iter().map(|&s| s as u8));
9959 }
9960 }
9961 raw
9962 }
9963
9964 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
9965 /// through ffmpeg: one point per entry of `points`, each a quality flag
9966 /// set. Returns the ladder ordered by fidelity and the total encode wall
9967 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
9968 /// so both curves are measured by the same decoder.
9969 fn external_ladder(
9970 source: &[Picture],
9971 width: usize,
9972 height: usize,
9973 encoder: &str,
9974 points: &[Vec<String>],
9975 ) -> (Vec<(f64, f64)>, f64) {
9976 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
9977 let dir = std::env::temp_dir();
9978 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
9979 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
9980 let mut ladder = Vec::new();
9981 let mut wall = 0.0;
9982 for (i, params) in points.iter().enumerate() {
9983 let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id()));
9984 let start = std::time::Instant::now();
9985 let out = Command::new("ffmpeg")
9986 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
9987 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
9988 .arg(&raw_path)
9989 .args(["-an", "-threads", "1"])
9990 .args(["-g", &source.len().to_string(), "-c:v", encoder])
9991 .args(params)
9992 .args(["-f", "obu"])
9993 .arg(&obu)
9994 .output()
9995 .expect("ffmpeg failed to run");
9996 wall += start.elapsed().as_secs_f64();
9997 assert!(
9998 out.status.success(),
9999 "{encoder} {params:?}: {}",
10000 String::from_utf8_lossy(&out.stderr)
10001 );
10002 let stream = std::fs::read(&obu).expect("reference stream");
10003 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
10004 let mean: f64 = decoded
10005 .iter()
10006 .zip(source)
10007 .map(|(d, s)| psnr_all(d, s))
10008 .sum::<f64>()
10009 / source.len() as f64;
10010 ladder.push((mean, (stream.len() as f64).log10()));
10011 let _ = std::fs::remove_file(&obu);
10012 }
10013 let _ = std::fs::remove_file(&raw_path);
10014 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
10015 (ladder, wall)
10016 }
10017
10018 /// First differing sample between two pictures, as
10019 /// `(plane, index, left, right)` -- so a gate failure names the plane and
10020 /// the sample instead of just "differs". A length difference counts as a
10021 /// mismatch of that plane at the first index past the shorter one.
10022 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
10023 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
10024 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
10025 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
10026 }
10027 if l.len() != r.len() {
10028 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
10029 }
10030 }
10031 None
10032 }
10033
10034 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
10035 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
10036 /// stream is decoded twice -- by ffmpeg and by our own
10037 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
10038 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
10039 /// in Y, U and V over every shown frame in display order. That is itself
10040 /// a gate: it proves the bitstream says what the encoder thinks, in the
10041 /// only two decoders that read it.
10042 fn our_ladder(
10043 name: &str,
10044 source: &[Picture],
10045 width: usize,
10046 height: usize,
10047 fctx: &crate::decode::FrameCtx,
10048 ) -> (Vec<(f64, f64)>, f64) {
10049 let mut ladder = Vec::new();
10050 let mut wall = 0.0;
10051 for &q in &[150u8, 120, 90, 60] {
10052 let start = std::time::Instant::now();
10053 let encoded = encode_sequence_with_ctx(source, q, 0.5, fctx).unwrap();
10054 wall += start.elapsed().as_secs_f64();
10055 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
10056 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
10057 assert_eq!(
10058 ours.len(),
10059 source.len(),
10060 "{name} q={q}: our decoder's display-order frame count"
10061 );
10062 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
10063 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
10064 panic!(
10065 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
10066 {got}, the encoder reconstructed {want}"
10067 );
10068 }
10069 }
10070 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
10071 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
10072 panic!(
10073 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
10074 {got}, the encoder reconstructed {want}"
10075 );
10076 }
10077 }
10078 let mean: f64 = decoded
10079 .iter()
10080 .zip(source)
10081 .map(|(d, s)| psnr_all(d, s))
10082 .sum::<f64>()
10083 / source.len() as f64;
10084 ladder.push((mean, (encoded.stream.len() as f64).log10()));
10085 }
10086 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
10087 (ladder, wall)
10088 }
10089
10090 /// The [`crate::encoder::Pyramid`] this run's ladder is coded under, from
10091 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]`. Unset
10092 /// keeps the flat one-key-then-all-inter ladder the baseline was measured
10093 /// on, so the gate's default recipe is unchanged.
10094 fn pyramid_from_env() -> Option<crate::encoder::Pyramid> {
10095 let spec = std::env::var("EC_AV1_PYRAMID").ok()?;
10096 let mut f = spec.split(':');
10097 let mini_gop = f.next()?.parse().ok()?;
10098 let d = crate::encoder::Pyramid::default();
10099 Some(crate::encoder::Pyramid {
10100 mini_gop,
10101 arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset),
10102 leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset),
10103 })
10104 }
10105
10106 /// [`our_ladder`] through the streaming facade with a coding pyramid: the
10107 /// four points are the same `base_q_idx` ladder, but each stream is
10108 /// reordered (hidden `ALTREF` first, `show_existing_frame` last per
10109 /// group) and each level is coded at its own quantizer offset. Returns
10110 /// the ladder, the wall, and — per pyramid level over the whole ladder —
10111 /// how many frames and how many bytes it spent.
10112 fn our_ladder_pyramid(
10113 name: &str,
10114 source: &[Picture],
10115 width: usize,
10116 height: usize,
10117 pyramid: crate::encoder::Pyramid,
10118 ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4]) {
10119 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
10120 let slot = |l: Level| match l {
10121 Level::Key => 0,
10122 Level::Arf => 1,
10123 Level::Leaf => 2,
10124 Level::ShowExisting => 3,
10125 };
10126 let mut ladder = Vec::new();
10127 let mut wall = 0.0;
10128 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
10129 for &q in &[150u8, 120, 90, 60] {
10130 let config = EncoderConfig {
10131 width,
10132 height,
10133 base_q_idx: q,
10134 gop: source.len(),
10135 colour: Colour::Unspecified,
10136 tile_cols_log2: 0,
10137 tile_rows_log2: 0,
10138 };
10139 let start = std::time::Instant::now();
10140 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
10141 let mut packets = Vec::new();
10142 for picture in source {
10143 packets.extend(enc.encode_frames(picture).unwrap());
10144 }
10145 packets.extend(enc.flush().unwrap());
10146 wall += start.elapsed().as_secs_f64();
10147 let mut stream = Vec::new();
10148 for p in &packets {
10149 counts[slot(p.level)] += 1;
10150 bytes[slot(p.level)] += p.data.len();
10151 stream.extend_from_slice(&p.data);
10152 }
10153 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
10154 // correct if the DISPLAY-order output still has one frame per
10155 // source picture, in the right order -- checked against our own
10156 // decoder as well as ffmpeg's, both below.
10157 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
10158 assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count");
10159 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
10160 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
10161 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
10162 panic!(
10163 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
10164 decoded {got}, our decoder decoded {want}"
10165 );
10166 }
10167 }
10168 let mean: f64 = decoded
10169 .iter()
10170 .zip(source)
10171 .map(|(d, s)| psnr_all(d, s))
10172 .sum::<f64>()
10173 / source.len() as f64;
10174 ladder.push((mean, (stream.len() as f64).log10()));
10175 }
10176 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
10177 (ladder, wall, counts, bytes)
10178 }
10179
10180 /// Byte-exactness gate for encoder work that is meant to change only
10181 /// how long the encoder takes.
10182 ///
10183 /// The BD gate above measures quality, which a speed lane can move by a
10184 /// hair without failing anything; this pins the streams themselves.
10185 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
10186 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
10187 /// in the tile) and again on lane-av1mv's merge of it: an extra
10188 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
10189 /// above, not by this pin.
10190 #[test]
10191 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
10192 if !have_ffmpeg() {
10193 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
10194 return;
10195 }
10196 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
10197 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
10198 if !clip.exists() {
10199 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip");
10200 return;
10201 }
10202 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
10203 // FNV-1a over the stream: a witness that every coded bit is where it
10204 // was, which a byte count alone is not.
10205 let fnv = |b: &[u8]| {
10206 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
10207 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
10208 })
10209 };
10210 let pins: [(u8, usize, u64); 2] =
10211 [(150, 7084, 0xe6a9_2f62_3855_0eee), (60, 26116, 0xa831_9866_b799_80fc)];
10212 for (q, bytes, hash) in pins {
10213 let encoded = encode_sequence(&source, q, 0.5).unwrap();
10214 assert_eq!(
10215 (encoded.stream.len(), fnv(&encoded.stream)),
10216 (bytes, hash),
10217 "q={q}: the encoder's stream moved"
10218 );
10219 }
10220 }
10221
10222 /// A ladder is only a ladder if both axes rise together.
10223 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
10224 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
10225 for w in ladder.windows(2) {
10226 assert!(
10227 w[1].0 > w[0].0 && w[1].1 > w[0].1,
10228 "{name}: not monotone, {ladder:?}"
10229 );
10230 }
10231 }
10232
10233 /// The sweep behind [`screen_content`]'s two constants
10234 /// (`unswept-decision-constants`): the share of 16x16 luma blocks with at
10235 /// most N distinct colours, per gate clip, at the size the gate codes.
10236 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
10237 #[test]
10238 #[ignore = "reads the real library"]
10239 fn probe_screen_detect() {
10240 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
10241 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
10242 for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] {
10243 let path = fixtures.join("video").join(name);
10244 if path.exists() {
10245 clips.push((name.to_string(), path));
10246 }
10247 }
10248 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
10249 && let Some(p) = manifest
10250 .lines()
10251 .skip(1)
10252 .filter_map(|l| l.split('\t').next())
10253 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
10254 {
10255 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
10256 }
10257 let (width, height) = (640usize, 384usize);
10258 for (name, path) in &clips {
10259 let frames = clip_frames(path.to_str().unwrap(), "0", width, height, 4);
10260 for (f, picture) in frames.iter().enumerate() {
10261 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
10262 let mut hist = [0usize; 257];
10263 let mut blocks = 0usize;
10264 for by in (0..height).step_by(16) {
10265 for bx in (0..width).step_by(16) {
10266 let mut seen = [false; 256];
10267 let mut colors = 0usize;
10268 for row in 0..16 {
10269 for col in 0..16 {
10270 let v = usize::from(y[(by + row) * width + bx + col]);
10271 if !seen[v] {
10272 seen[v] = true;
10273 colors += 1;
10274 }
10275 }
10276 }
10277 hist[colors] += 1;
10278 blocks += 1;
10279 }
10280 }
10281 let share = |limit: usize| {
10282 100.0 * hist[2..=limit.min(256)].iter().sum::<usize>() as f64
10283 / blocks.max(1) as f64
10284 };
10285 eprintln!(
10286 "{name} frame {f}: <=4 {:.1}% <=8 {:.1}% <=16 {:.1}% <=32 {:.1}% <=64 {:.1}% <=128 {:.1}%",
10287 share(4),
10288 share(8),
10289 share(16),
10290 share(32),
10291 share(64),
10292 share(128),
10293 );
10294 }
10295 }
10296 }
10297
10298 /// The missing instrument: what this encoder costs against libaom and
10299 /// rav1e at matched fidelity, and how long it takes to get there.
10300 ///
10301 /// Recipe, identical on all three sides: 12 consecutive frames of each
10302 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
10303 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
10304 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
10305 /// it by default), 4:2:0 8-bit in and out. Reference points:
10306 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
10307 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
10308 /// tile_cols=1:tile_rows=1:threads=1`
10309 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
10310 /// ffmpeg-decoded frames of each encoder's own stream.
10311 ///
10312 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
10313 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
10314 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
10315 /// four encodes of that ladder together):
10316 ///
10317 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
10318 /// |---|---|---|---|---|
10319 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
10320 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
10321 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
10322 ///
10323 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
10324 /// the encoder takes -- every stream it writes is byte-identical, so the
10325 /// BD columns are this box's own re-run of the same recipe rather than a
10326 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
10327 /// rav1e). What moved is the wall of the four encodes:
10328 ///
10329 /// | clip | wall ours before | after | instructions:u before -> after |
10330 /// |---|---|---|---|
10331 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
10332 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
10333 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
10334 ///
10335 /// Three exact steps, none of which touches a coded bit: the coefficient
10336 /// rate pricer stopped rebuilding every CDF table per candidate
10337 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
10338 /// tile once per candidate (`decode::FilterReplay`), and the forward
10339 /// transform stopped transforming the all-zero residual that 70% of its
10340 /// calls carry.
10341 ///
10342 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
10343 ///
10344 /// | step | 1080p | 2160p | screen |
10345 /// |---|---|---|---|
10346 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
10347 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
10348 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
10349 ///
10350 /// Loop restoration is NOT in yet: it is the one filter whose parameters
10351 /// are per restoration UNIT inside the tile payload, so it needs both
10352 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
10353 /// buffer to solve against -- neither of which this frame-header-level
10354 /// search reaches.
10355 ///
10356 /// The baseline it replaced, before an inter frame's blocks chose their
10357 /// own partition, was +501.4/+504.4/+440.9 against libaom and
10358 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
10359 ///
10360 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
10361 /// fidelity, while spending far more time than either (the partition
10362 /// search's own cost, uncut: see the two intra-pruning variants measured
10363 /// and rejected in the lane report). No
10364 /// threshold is asserted yet -- this run sets the baseline; the gate
10365 /// asserts four monotone points per ladder, and at EVERY ladder point of
10366 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
10367 /// `crate::stream::decode_stream` -- and asserts the encoder's
10368 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
10369 /// and V over every shown frame in display order. A failure names the
10370 /// clip, the q, the frame, the plane and the first differing sample.
10371 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
10372 /// which exposes no per-packet reconstruction, so that path asserts the
10373 /// two decoders against each other on all three planes.)
10374 ///
10375 /// Run:
10376 /// cargo test -p ec-av1 --release --lib -- --ignored \
10377 /// bd_rate_vs_libaom_and_rav1e --nocapture
10378 #[test]
10379 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
10380 fn bd_rate_vs_libaom_and_rav1e() {
10381 if !have_ffmpeg() {
10382 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
10383 return;
10384 }
10385 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
10386 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
10387 for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] {
10388 let path = fixtures.join("video").join(name);
10389 if path.exists() {
10390 clips.push((name.to_string(), path));
10391 } else {
10392 eprintln!("SKIP clip {name}: missing");
10393 }
10394 }
10395 // Screen capture: the repo carries no screen-capture fixture, so take
10396 // the first OBS recording the real-library manifest names.
10397 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
10398 Ok(manifest) => {
10399 let screen = manifest
10400 .lines()
10401 .skip(1)
10402 .filter_map(|l| l.split('\t').next())
10403 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists());
10404 match screen {
10405 Some(p) => clips.push((
10406 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
10407 std::path::PathBuf::from(p),
10408 )),
10409 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
10410 }
10411 }
10412 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
10413 }
10414 assert!(!clips.is_empty(), "no source clip available");
10415
10416 let (width, height, frames) = (640usize, 384usize, 12usize);
10417 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
10418 .iter()
10419 .map(|q| {
10420 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
10421 .map(String::from)
10422 .to_vec()
10423 })
10424 .collect();
10425 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
10426 .iter()
10427 .map(|q| {
10428 vec![
10429 "-rav1e-params".to_string(),
10430 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
10431 ]
10432 })
10433 .collect();
10434 println!(
10435 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
10436 );
10437 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |");
10438 println!("|---|---|---|---|---|");
10439 for (name, path) in &clips {
10440 let fctx = &crate::decode::FrameCtx::new();
10441 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
10442 let _ = take_partition_hits();
10443 let _ = crate::tile::take_palette_hits();
10444 SCREEN_FRAMES.iter().for_each(|c| {
10445 c.store(0, std::sync::atomic::Ordering::Relaxed);
10446 });
10447 let _ = take_uv_mode_hits();
10448 let _ = crate::tile::take_inter_mode_hits();
10449 let _ = crate::tile::take_drl_hits();
10450 let _ = crate::tile::take_ref_hits();
10451 let _ = crate::tile::take_compound_mode_hits();
10452 let _ = crate::tile::take_compound_pair_hits();
10453 let _ = crate::tile::take_compound_size_hits();
10454 let _ = crate::motion::take_census();
10455 let (ours, ours_wall) = match pyramid_from_env() {
10456 None => our_ladder(name, &source, width, height, fctx),
10457 Some(pyramid) => {
10458 let (ladder, wall, counts, bytes) =
10459 our_ladder_pyramid(name, &source, width, height, pyramid);
10460 eprintln!(
10461 "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \
10462 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
10463 counts[0], counts[1], counts[2], counts[3],
10464 bytes[0], bytes[1], bytes[2], bytes[3],
10465 );
10466 (ladder, wall)
10467 }
10468 };
10469 // How often the inter split actually fired over this clip's four
10470 // encodes, against the whole 32x32 that was the only outcome
10471 // before (gate-blind-to-feature).
10472 let [whole32, split32, whole16, split16] = take_partition_hits();
10473 // Which inter modes actually fired over this clip's four encodes,
10474 // and at which DRL index -- a mode nobody picks is a mode the BD
10475 // number cannot be crediting (gate-blind-to-feature).
10476 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
10477 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
10478 let refs = crate::tile::take_ref_hits();
10479 let modes_total = (nearest + near + global + new).max(1);
10480 eprintln!(
10481 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
10482 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
10483 {drl0}/{drl1}/{drl2}/{drl3}",
10484 100.0 * nearest as f64 / modes_total as f64,
10485 100.0 * near as f64 / modes_total as f64,
10486 100.0 * global as f64 / modes_total as f64,
10487 100.0 * new as f64 / modes_total as f64,
10488 );
10489 // The compound census: what share of the coded inter blocks took
10490 // a compound reference at all, which compound mode they took, and
10491 // which pair (gate-blind-to-feature -- a compound mode nobody
10492 // picks cannot be what a BD number credits).
10493 let comp_modes = crate::tile::take_compound_mode_hits();
10494 let comp_pairs = crate::tile::take_compound_pair_hits();
10495 let comp_sizes = crate::tile::take_compound_size_hits();
10496 let comp_total: usize = comp_modes.iter().sum();
10497 eprintln!(
10498 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
10499 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
10500 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
10501 modes_total + comp_total,
10502 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
10503 comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3],
10504 comp_modes[6], comp_modes[7],
10505 comp_pairs[3], comp_pairs[6],
10506 );
10507 eprintln!(
10508 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
10509 comp_sizes[1], comp_sizes[2], comp_sizes[3],
10510 );
10511 // Where the wall-owning stage actually goes: how many candidate
10512 // evaluations (one `mc::predict` + SAD each) a search spends, how
10513 // many of them are subpel, and how often the winner is the seed
10514 // it started from -- the census the seeded search is judged by.
10515 let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census();
10516 let per = |n: u64| n as f64 / calls.max(1) as f64;
10517 eprintln!(
10518 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
10519 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
10520 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
10521 per(evals),
10522 100.0 * subpel as f64 / evals.max(1) as f64,
10523 per(rounds),
10524 100.0 * near_pred as f64 / calls.max(1) as f64,
10525 100.0 * unmoved as f64 / calls.max(1) as f64,
10526 );
10527 eprintln!(
10528 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
10529 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
10530 );
10531 eprintln!(
10532 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
10533 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
10534 whole32 + split32,
10535 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
10536 whole16 + split16,
10537 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
10538 );
10539 // The deblocking level each of this clip's frames chose
10540 // (lane-av1filt): 0 everywhere would mean the filter never fires.
10541 let levels = crate::filter_search::take_chosen_levels();
10542 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
10543 let mean = |f: fn(&Chosen) -> u8| {
10544 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
10545 };
10546 eprintln!(
10547 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
10548 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
10549 levels.len(),
10550 mean(|l| l.0.0),
10551 mean(|l| l.0.1),
10552 mean(|l| l.1.0),
10553 mean(|l| l.1.1),
10554 mean(|l| l.2.0),
10555 mean(|l| l.2.1),
10556 );
10557 // How many strength presets each frame's CDEF list carried and
10558 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
10559 // everywhere would mean the per-unit choice never fires.
10560 let presets = crate::filter_search::take_cdef_presets();
10561 let mut by_bits = [0usize; 4];
10562 for (b, _) in &presets {
10563 by_bits[usize::from(*b)] += 1;
10564 }
10565 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
10566 let on_extra: usize = presets
10567 .iter()
10568 .flat_map(|(_, c)| c.iter().skip(1))
10569 .sum();
10570 eprintln!(
10571 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
10572 on a non-default preset ({:.1}%)",
10573 by_bits[0],
10574 by_bits[1],
10575 by_bits[2],
10576 by_bits[3],
10577 on_extra,
10578 units,
10579 100.0 * on_extra as f64 / units.max(1) as f64
10580 );
10581 // How the 64x64 luma restoration units split between
10582 // RESTORE_NONE and Wiener (lane-av1lr).
10583 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
10584 eprintln!(
10585 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
10586 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
10587 );
10588 // Which chroma modes the search actually wins with, against the
10589 // unconditional DC_PRED that was the only outcome before
10590 // (gate-blind-to-feature).
10591 // Screen-content detection and the palette it turns on
10592 // (gate-blind-to-feature): how many frames set
10593 // `allow_screen_content_tools`, how many blocks took a palette,
10594 // and of what size. A film clip must print `screen frames on=0`.
10595 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
10596 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
10597 let palette = crate::tile::take_palette_hits();
10598 eprintln!(
10599 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
10600 palette[0],
10601 (2..=8)
10602 .filter(|&n| palette[n] > 0)
10603 .map(|n| format!("{n}={}", palette[n]))
10604 .collect::<Vec<_>>()
10605 .join(" ")
10606 );
10607 let palette_uv = crate::tile::take_palette_uv_hits();
10608 eprintln!(
10609 "{name}: chroma palette blocks {} sizes {}",
10610 palette_uv[0],
10611 (2..=8)
10612 .filter(|&n| palette_uv[n] > 0)
10613 .map(|n| format!("{n}={}", palette_uv[n]))
10614 .collect::<Vec<_>>()
10615 .join(" ")
10616 );
10617 let uv = take_uv_mode_hits();
10618 let uv_total: usize = uv.iter().sum();
10619 eprintln!(
10620 "{name}: uv modes {}",
10621 uv.iter()
10622 .enumerate()
10623 .filter(|&(_, &n)| n > 0)
10624 .map(|(m, &n)| format!(
10625 "{}={n} ({:.1}%)",
10626 UV_MODE_NAMES[m],
10627 100.0 * n as f64 / uv_total.max(1) as f64
10628 ))
10629 .collect::<Vec<_>>()
10630 .join(" ")
10631 );
10632 // Which transform depth the intra blocks of this clip's key
10633 // frames resolved to (lane-av1tx): depth 0 is one transform over
10634 // the whole block, 1 and 2 its halvings.
10635 let depths = take_tx_depth_hits();
10636 let depth_total: usize = depths.iter().sum();
10637 eprintln!(
10638 "{name}: intra tx depths {}",
10639 depths
10640 .iter()
10641 .enumerate()
10642 .map(|(d, &n)| format!(
10643 "{d}={n} ({:.1}%)",
10644 100.0 * n as f64 / depth_total.max(1) as f64
10645 ))
10646 .collect::<Vec<_>>()
10647 .join(" ")
10648 );
10649 // And which var-tx depth this clip's INTER blocks resolved to
10650 // (lane-av1tx2): 0 is one transform over the whole block, 1 its
10651 // four halves.
10652 let splits = take_inter_tx_split_hits();
10653 let split_total: usize = splits.iter().sum();
10654 eprintln!(
10655 "{name}: inter var-tx depths {}",
10656 splits
10657 .iter()
10658 .enumerate()
10659 .map(|(d, &n)| format!(
10660 "{d}={n} ({:.1}%)",
10661 100.0 * n as f64 / split_total.max(1) as f64
10662 ))
10663 .collect::<Vec<_>>()
10664 .join(" ")
10665 );
10666 let (aom, aom_wall) =
10667 external_ladder(&source, width, height, "libaom-av1", &aom_points);
10668 let (rav1e, rav1e_wall) =
10669 external_ladder(&source, width, height, "librav1e", &rav1e_points);
10670 assert_monotone(&format!("{name}: ours"), &ours);
10671 assert_monotone(&format!("{name}: libaom"), &aom);
10672 assert_monotone(&format!("{name}: rav1e"), &rav1e);
10673 let points = ours
10674 .iter()
10675 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
10676 .collect::<Vec<_>>()
10677 .join(", ");
10678 println!(
10679 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
10680 bd_rate(&aom, &ours) * 100.0,
10681 bd_rate(&rav1e, &ours) * 100.0,
10682 );
10683 println!(
10684 "| references | libaom {} | rav1e {} | | |",
10685 aom.iter()
10686 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
10687 .collect::<Vec<_>>()
10688 .join(", "),
10689 rav1e
10690 .iter()
10691 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
10692 .collect::<Vec<_>>()
10693 .join(", "),
10694 );
10695 }
10696 }
10697}