forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB682c080Tahinli2 months ago2434 commits

encode.rs12200 lines, 537.9 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.
85///
86/// The fourth sweep (lane-av1lambda) ran the BD gates themselves rather than
87/// those ladders, and 0.1 was far off the point: the rate term was carrying
88/// roughly twice the weight it is worth. 640x384 gate, BD-rate vs libaom /
89/// vs rav1e for 1080p film, 2160p film, screen capture:
90///
91/// | lambda | 1080p | 2160p | screen |
92/// |--------|-------|-------|--------|
93/// | 0.0125 | +78.0 / +31.3 | +90.8 / +46.5 | +57.2 / -0.3 |
94/// | 0.025 | +71.5 / +28.4 | +87.0 / +46.5 | +50.4 / -3.8 |
95/// | 0.0375 | +71.2 / +28.5 | +84.3 / +45.4 | +48.7 / -4.4 |
96/// | 0.05 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
97/// | 0.075 | +74.8 / +32.7 | +91.3 / +52.8 | +51.4 / -1.3 |
98/// | 0.1 | +79.2 / +36.9 | +97.7 / +58.8 | +53.1 / -0.4 |
99/// | 0.125 | +84.0 / +41.1 | +100.7 / +61.5 | +56.8 / +2.3 |
100/// | 0.15 | +86.0 / +42.9 | +104.4 / +65.2 | +59.5 / +4.2 |
101/// | 0.2 | +89.6 / +45.5 | +109.9 / +69.8 | +62.3 / +7.3 |
102///
103/// and on the native 1920x1024 crops, which is the table that decides:
104///
105/// | lambda | film 1080p | film 2160p | screen |
106/// |--------|------------|------------|--------|
107/// | 0.025 | +17.1 / -0.5 | +49.0 / +21.1 | +51.5 / -15.1 |
108/// | 0.0375 | +16.3 / -1.0 | +47.5 / +19.7 | +50.7 / -15.1 |
109/// | 0.05 | +17.0 / -0.3 | +47.0 / +19.2 | +51.6 / -14.2 |
110/// | 0.1 | +18.1 / +0.9 | +47.1 / +19.0 | +58.3 / -9.8 |
111///
112/// 0.0375 is the best point on two clips of three and costs the 2160p film
113/// +0.4/+0.7, outside the +-0.3 band every other lever here is kept inside,
114/// so 0.05 ships: two clips down on both columns, the 2160p film flat
115/// (-0.1 / +0.2). It also spends ~8% more encode wall, the bits it stopped
116/// refusing.
117const LAMBDA_SCALE: f64 = 0.05;
118
119/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
120/// picks it is the thing running. A release build has no such knob.
121fn lambda_scale() -> f64 {
122 let swept = std::env::var("EC_AV1_LAMBDA")
123 .ok()
124 .and_then(|v| v.parse::<f64>().ok());
125 match swept {
126 Some(scale) if cfg!(test) => scale,
127 _ => LAMBDA_SCALE,
128 }
129}
130
131/// How a key frame's lambda differs from an inter frame's: libaom weighs the
132/// two apart (`rd_frame_type_factor`, key 128 against an inter frame's 144 out
133/// of 128), because every later frame predicts from the key frame, so an error
134/// left in it is paid for over the whole group. This encoder has no temporal
135/// propagation model at all, and this factor is the cheapest stand-in for one.
136/// Swept by `EC_AV1_LAMBDA_KEY` in a test build, like [`lambda_scale`].
137///
138/// MEASURED and NOT KEPT. 640x384 gate at [`LAMBDA_SCALE`] 0.05, BD vs
139/// libaom / vs rav1e:
140///
141/// | k_key | 1080p | 2160p | screen |
142/// |---|---|---|---|
143/// | 1.0 | +71.9 / +29.6 | +87.1 / +49.3 | +48.7 / -4.0 |
144/// | 0.85 | +71.5 / +29.4 | +87.0 / +48.3 | +49.7 / -3.9 |
145/// | 0.7 | +71.3 / +28.9 | +87.2 / +48.6 | +49.4 / -4.1 |
146/// | 0.5 | +71.4 / +28.9 | +88.7 / +49.6 | +50.1 / -3.4 |
147///
148/// The two films want the key frame coded finer and the screen capture wants
149/// the opposite, by about the same amount, and at native the whole lever is
150/// inside the +-0.3 band that decides nothing: k_key 0.7 reads +16.9 / -0.3,
151/// +47.2 / +19.2, +51.4 / -14.7 against 1.0's +17.0 / -0.3, +47.0 / +19.2,
152/// +51.6 / -14.2. A gate whose GOP is one key frame in twelve cannot see a
153/// per-frame-type weight; the real lever here is temporal propagation
154/// (libaom's `tpl`), which weighs each BLOCK by how much of it later frames
155/// predict from, not each frame.
156const KEY_LAMBDA_FACTOR: f64 = 1.0;
157
158/// [`KEY_LAMBDA_FACTOR`], or what `EC_AV1_LAMBDA_KEY` names in a test build.
159fn key_lambda_factor() -> f64 {
160 match std::env::var("EC_AV1_LAMBDA_KEY").ok().and_then(|v| v.parse::<f64>().ok()) {
161 Some(k) if cfg!(test) => k,
162 _ => KEY_LAMBDA_FACTOR,
163 }
164}
165
166// Every frame's predicted coefficient bits since the last
167// `take_predicted_bits`, in coding order -- the encoder half of
168// `predicted_coeff_bits_track_the_tile_the_writer_wrote`'s drift measurement.
169#[cfg(test)]
170thread_local! {
171 static PREDICTED_BITS: std::cell::RefCell<Vec<f64>> = const { std::cell::RefCell::new(Vec::new()) };
172}
173
174/// Records one frame's predicted coefficient bits.
175#[cfg(test)]
176fn record_predicted_bits(bits: f64) {
177 PREDICTED_BITS.with(|p| p.borrow_mut().push(bits));
178}
179
180/// Takes (and clears) what the frames encoded on this thread were predicted to
181/// spend on coefficients.
182#[cfg(test)]
183pub(crate) fn take_predicted_bits() -> Vec<f64> {
184 PREDICTED_BITS.with(|p| std::mem::take(&mut *p.borrow_mut()))
185}
186
187/// Whether a 16x16 inter leaf may split into four 8x8 ones of its own.
188const SPLIT_INTER_8: bool = true;
189
190/// [`SPLIT_INTER_8`], or what `EC_AV1_SPLIT_INTER8` names in a test build.
191/// Whether a key frame codes `tx_mode == TxMode::Select` and searches each
192/// block's transform depth (lane-av1tx). On by default; `EC_AV1_TX_SELECT=0`
193/// turns it off for an A/B on one build.
194/// Whether an INTER frame also carries `TxMode::Select`: an inter block's
195/// residual as one transform over the whole block or as the four transforms
196/// of half the side ([`commit_inter_luma`]), a searched `tx_depth` on every
197/// intra block inside the inter frame. ON since lane-av1tx2, which found why
198/// the streams desynced -- the writer counted the [`crate::decode::
199/// TXFM_CTX_INIT`] band value of a neighbour outside the tile, where the
200/// reader drops the term -- and measured the split search: BD-rate vs libaom
201/// 233.5 -> 226.1 and 170.9 -> 167.4 on two clips, 212.8 -> 213.2 on the
202/// third, for 13% encode wall. `EC_AV1_TX_SELECT_INTER=0` turns it off for an
203/// A/B on one build.
204fn tx_select_inter() -> bool {
205 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
206 *ON.get_or_init(|| {
207 !matches!(
208 std::env::var("EC_AV1_TX_SELECT_INTER").as_deref(),
209 Ok("0") | Ok("off")
210 )
211 })
212}
213
214fn tx_select() -> bool {
215 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
216 *ON.get_or_init(|| {
217 !matches!(
218 std::env::var("EC_AV1_TX_SELECT").as_deref(),
219 Ok("0") | Ok("off")
220 )
221 })
222}
223
224fn split_inter_8() -> bool {
225 match std::env::var("EC_AV1_SPLIT_INTER8").ok() {
226 Some(v) if cfg!(test) => v != "0",
227 _ => SPLIT_INTER_8,
228 }
229}
230
231/// Whether a 16x16 (or 8x8) leaf runs a motion search of its own beside the
232/// NEARESTMV candidate it always had.
233const LEAF_NEW_MV: bool = true;
234
235/// Whether GOLDEN/ALTREF get a `NEWMV` search of their own. Measured on the
236/// BD gate: with the early-out below at its swept margin, -1.7/-2.5/-0.0
237/// points vs libaom and -1.6/-2.3/-0.0 vs rav1e for 4%/4%/0.3% more motion
238/// searches (the census `bd_rate_vs_libaom_and_rav1e` prints).
239const EXTRA_REF_NEW_MV: bool = true;
240
241/// How much cheaper an extra reference's `NEARESTMV` has to be than LAST's
242/// own best vector before that reference's `NEWMV` search is skipped: a
243/// factor on the search cost scale, `1.0` meaning "as good or better".
244/// Swept on the BD gate over 0.15/0.25/0.35/0.5/0.8/1.0/1.5 and off (`0.0`,
245/// never skip): the whole BD gain survives down to 0.35 (+124.8/+150.4/+80.9
246/// vs libaom, against +124.9/+150.3/+81.0 with no early-out at all) while the
247/// extra searches drop from +27% to +4% of the base count -- and on screen
248/// capture, where an extra reference's NEWMV wins nothing, it skips 99.7% of
249/// them. Below 0.35 the gain starts eroding (0.15: +125.3/+151.7).
250const EXTRA_NEW_SKIP_MARGIN: f64 = 0.35;
251
252/// [`EXTRA_NEW_SKIP_MARGIN`], swept by `EC_AV1_MV_SKIP_MARGIN`.
253fn extra_new_skip_margin() -> f64 {
254 match std::env::var("EC_AV1_MV_SKIP_MARGIN").ok() {
255 Some(v) if cfg!(test) => v.parse().unwrap_or(EXTRA_NEW_SKIP_MARGIN),
256 _ => EXTRA_NEW_SKIP_MARGIN,
257 }
258}
259
260/// The margin on a LEAF's SECOND-reference motion search, the same early-out
261/// shape [`EXTRA_NEW_SKIP_MARGIN`] gives a whole block's extra-reference
262/// `NEWMV`: the search is skipped when that reference's own
263/// `NEAREST_NEARESTMV` vector already prices this many times better than the
264/// leaf's `LAST` search found. `0.0` never skips.
265///
266/// Swept on the BD gate over 0.15/0.35/0.6/0.8/1.2 and 0.0, reading BD vs
267/// libaom (1080p/2160p/screen) against the extra `motion::search` calls at
268/// 2160p (38195 with no second-reference search at all):
269/// 0.15 +81.7/+97.4/+54.5 at 41286, 0.35 +81.4/+96.7 at 43093,
270/// 0.6 +80.6/+95.5 at 44843, 0.8 +79.9/+94.6 at 47008, 1.2 +80.2/+94.2 at
271/// 77882, never-skip +79.7/+94.1 at 81801. 0.8 takes the whole gain the
272/// unskipped search buys (-3.1/-5.3 off the +83.0/+99.9 base) for a quarter
273/// of its extra searches; past it the calls double for another -0.3/-0.5.
274/// Screen capture is BYTE-IDENTICAL at every margin -- its leaf compound is
275/// all `NEAREST_NEARESTMV` and no searched second vector ever wins there --
276/// so the margin is pure wall on that content (+10% searches at 0.8).
277const LEAF_SECOND_NEW_MARGIN: f64 = 0.8;
278
279/// [`LEAF_SECOND_NEW_MARGIN`], swept by `EC_AV1_LEAF_SECOND_MARGIN`; the
280/// search itself is switched off by `EC_AV1_LEAF_SECOND_NEWMV=0`.
281fn leaf_second_new_margin() -> f64 {
282 match std::env::var("EC_AV1_LEAF_SECOND_MARGIN").ok() {
283 Some(v) => v.parse().unwrap_or(LEAF_SECOND_NEW_MARGIN),
284 None => LEAF_SECOND_NEW_MARGIN,
285 }
286}
287
288/// Whether a leaf searches its SECOND reference at all (lane-av1comp4).
289fn leaf_second_new_mv() -> bool {
290 match std::env::var("EC_AV1_LEAF_SECOND_NEWMV").ok() {
291 Some(v) => v != "0",
292 None => true,
293 }
294}
295
296/// Whether a 16x16 or 8x8 inter LEAF is offered the compound candidates the
297/// whole 32x32 block is (lane-av1comp3). The writer already codes a compound
298/// block at any leaf size (`tile::write_inter_frame_leaf`/`..._leaf8` both
299/// route through `write_compound_block`, which is sized by `bw4`/`bh4`); what
300/// was missing was the encoder ever forming one below 32x32.
301const LEAF_COMPOUND: bool = true;
302
303/// [`LEAF_COMPOUND`], or what `EC_AV1_LEAF_COMPOUND` names in any build.
304fn leaf_compound() -> bool {
305 match std::env::var("EC_AV1_LEAF_COMPOUND").ok() {
306 Some(v) => v != "0",
307 None => LEAF_COMPOUND,
308 }
309}
310
311/// [`LEAF_NEW_MV`], or what `EC_AV1_LEAF_NEWMV` names in a test build.
312fn leaf_new_mv() -> bool {
313 match std::env::var("EC_AV1_LEAF_NEWMV").ok() {
314 Some(v) if cfg!(test) => v != "0",
315 _ => LEAF_NEW_MV,
316 }
317}
318
319/// Whether an INTER frame's 32x32 block may be split into four 16x16 ones
320/// when the trial says four cost less. Before lane-av1rd2 only a quadrant
321/// the true frame edge cut through was ever split there; inside the frame
322/// every block was coded whole, which left the partition decision the key
323/// frame already makes unmade for eleven frames out of twelve.
324const SPLIT_INTER_BLOCKS: bool = true;
325
326/// [`SPLIT_INTER_BLOCKS`], or what `EC_AV1_SPLIT_INTER` names when the
327/// measurement that keeps it is running (test builds only, like
328/// [`lambda_scale`]).
329fn split_inter_blocks() -> bool {
330 match std::env::var("EC_AV1_SPLIT_INTER").ok() {
331 Some(v) if cfg!(test) => v != "0",
332 _ => SPLIT_INTER_BLOCKS,
333 }
334}
335
336/// Whether the encoder searches loop restoration at all (spec 7.17): one
337/// Wiener filter per 64x64 luma restoration unit, picked from
338/// [`crate::filter_search::WIENER_CANDIDATES`]. Swept by `EC_AV1_LR` in a
339/// test build, like [`lambda_scale`].
340const RESTORATION: bool = true;
341
342/// [`RESTORATION`], or what `EC_AV1_LR` names in a test build.
343fn restoration_enabled() -> bool {
344 match std::env::var("EC_AV1_LR").ok() {
345 Some(v) if cfg!(test) => v != "0",
346 _ => RESTORATION,
347 }
348}
349
350/// libaom's `partition_search_breakout` shape: how many non-zero luma
351/// coefficients per 256 luma samples a block may code and still be judged
352/// well enough predicted that the split below it is not worth trying. `0`
353/// disables the breakout (only the existing all-skip prune applies), which
354/// is the default until the sweep below justifies otherwise.
355///
356/// Swept on the BD gate (`EC_AV1_SPLIT_BREAKOUT`, test builds only), which
357/// is where this lane's wall would have gone: 1 cuts the three clips'
358/// encode wall 6.3/6.0/6.2 s -> 3.6/3.2/4.4 s but costs +18.4/+24.0/+7.9
359/// BD-rate points against libaom; 2 costs +23.4/+29.4/+18.8 and 4 costs
360/// +31.7/+40.6/+27.8, for barely more speed. The split trial is where this
361/// encoder's inter quality lives, so `0` ships and the knob stays for a
362/// future explicit speed preset.
363const SPLIT_BREAKOUT_COEFFS: usize = 0;
364
365/// libaom's `partition_search_breakout_rate_thr` shape, in this encoder's own
366/// currency: a 32x32 inter block whose whole-block RD cost per pixel comes
367/// out under `threshold * lambda` is not offered the split at all, and a
368/// 16x16 leaf under it is not offered the 8x8 split. `0.0` offers both
369/// always, as before this lever.
370///
371/// The census is what points here: the split trial runs on nearly every
372/// non-skip block (15132 leaf searches per ladder point on the 1080p clip)
373/// and wins 7.6% of the time on film, 3.0% on screen -- yet the coefficient
374/// -count breakout ([`SPLIT_BREAKOUT_COEFFS`]) that prunes it costs 18-31 BD
375/// points, so the gate has to read the block's own RD cost, not its levels.
376///
377/// Swept on the BD gate over 0.125/0.25/0.5/1.0 (vs libaom, against a base of
378/// +121.1/+146.1/+79.3): 0.125 is +121.2/+146.4/+79.1 (+0.1/+0.3/-0.2) for
379/// -10.0%/-5.7% instructions (1080p/screen, `perf stat` ABAB x2) and
380/// -7.7/-8.6/-4.5% wall; 0.25 already costs +0.7/+0.6/+0.6, 0.5 costs
381/// +3.5/+4.7/+1.8 for -15% wall, and 1.0 costs +19/+27/+6. So 0.125 ships --
382/// the largest threshold whose BD stays inside the +0.3 keep rule on every
383/// clip.
384const SPLIT_RD_THRESHOLD: f64 = 0.125;
385
386/// [`SPLIT_RD_THRESHOLD`], swept by `EC_AV1_SPLIT_RD` in any build.
387fn split_rd_threshold() -> f64 {
388 static T: std::sync::OnceLock<f64> = std::sync::OnceLock::new();
389 *T.get_or_init(|| {
390 std::env::var("EC_AV1_SPLIT_RD")
391 .ok()
392 .and_then(|v| v.parse().ok())
393 .unwrap_or(SPLIT_RD_THRESHOLD)
394 })
395}
396
397/// Whether `cost` over a `side` x `side` block is cheap enough per pixel that
398/// [`split_rd_threshold`] withholds the split trial.
399fn split_rd_breakout(cost: f64, side: usize, lambda: f64) -> bool {
400 let t = split_rd_threshold();
401 t > 0.0 && cost < t * lambda * (side * side) as f64
402}
403
404/// [`SPLIT_BREAKOUT_COEFFS`], swept by `EC_AV1_SPLIT_BREAKOUT` in a test
405/// build.
406fn split_breakout_coeffs() -> usize {
407 match std::env::var("EC_AV1_SPLIT_BREAKOUT").ok() {
408 Some(v) if cfg!(test) => v.parse().unwrap_or(SPLIT_BREAKOUT_COEFFS),
409 _ => SPLIT_BREAKOUT_COEFFS,
410 }
411}
412
413/// How often each partition decision was taken since the last
414/// [`take_partition_hits`], so a gate can report how often a new partition
415/// fires rather than assume it does (gate-blind-to-feature). Index 0 is an
416/// inter 32x32 block left whole, 1 one split into four 16x16 leaves; 2 is
417/// such a leaf left whole, 3 one split into four 8x8 leaves of its own.
418static PARTITION_HITS: [std::sync::atomic::AtomicUsize; 4] = [
419 std::sync::atomic::AtomicUsize::new(0),
420 std::sync::atomic::AtomicUsize::new(0),
421 std::sync::atomic::AtomicUsize::new(0),
422 std::sync::atomic::AtomicUsize::new(0),
423];
424
425/// Records one such decision.
426fn partition_hit(which: usize) {
427 PARTITION_HITS[which].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
428}
429
430/// Takes (and clears) the counts.
431#[cfg(test)]
432pub(crate) fn take_partition_hits() -> [usize; 4] {
433 [0, 1, 2, 3].map(|i| PARTITION_HITS[i].swap(0, std::sync::atomic::Ordering::Relaxed))
434}
435
436/// Whether the trial-set census (`EC_AV1_CENSUS=1`) is on: how many full
437/// rate-distortion trials the block search actually runs, by kind, and where
438/// the winner sat in the cheap SAD ranking the pruning levers rank by. Off by
439/// default, and a measurement build rather than a speed one -- the census
440/// runs the SAD pre-pass the unpruned search otherwise skips.
441pub fn census_on() -> bool {
442 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
443 *ON.get_or_init(|| matches!(std::env::var("EC_AV1_CENSUS").as_deref(), Ok("1")))
444}
445
446/// What each [`CENSUS`] counter counts.
447pub const CENSUS_KINDS: [&str; 11] = [
448 "intra blocks searched (key frame + inter leaves)",
449 "intra luma mode trials",
450 "chroma searches",
451 "chroma mode trials (each = 2 plane trials)",
452 "tx-depth trials (transform units, depth >= 1)",
453 "inter 32x32 blocks searched",
454 "inter block intra-mode trials",
455 "inter mv candidates (each = 3 mc trials)",
456 "inter leaves searched (intra vs NEARESTMV/NEWMV)",
457 " of those, intra won",
458 " of those, the NEARESTMV trial coded no residual",
459];
460
461/// The census counters themselves, indexed by [`CENSUS_KINDS`].
462static CENSUS: [std::sync::atomic::AtomicUsize; 11] =
463 [const { std::sync::atomic::AtomicUsize::new(0) }; 11];
464
465/// Where the RD winner sat in the SAD ranking, for the luma intra search and
466/// the chroma mode search -- what says whether a top-N prune would have kept
467/// the block the search actually chose.
468static LUMA_RANK: [std::sync::atomic::AtomicUsize; 13] =
469 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
470static CHROMA_RANK: [std::sync::atomic::AtomicUsize; 7] =
471 [const { std::sync::atomic::AtomicUsize::new(0) }; 7];
472
473fn census_add(kind: usize, n: usize) {
474 if census_on() {
475 CENSUS[kind].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
476 }
477}
478
479/// Reads (and clears) the census, so a driver can attribute it to its own encode.
480pub fn take_census() -> ([usize; 11], [usize; 13], [usize; 7]) {
481 let take = |c: &std::sync::atomic::AtomicUsize| c.swap(0, std::sync::atomic::Ordering::Relaxed);
482 (
483 std::array::from_fn(|i| take(&CENSUS[i])),
484 std::array::from_fn(|i| take(&LUMA_RANK[i])),
485 std::array::from_fn(|i| take(&CHROMA_RANK[i])),
486 )
487}
488
489/// The rank of `winner` in `scored` ordered by its cheap score, cheapest
490/// first -- the census's one shared rule, so the luma and chroma histograms
491/// mean the same thing.
492fn sad_rank(scored: &[(f64, u8)], winner: u8) -> usize {
493 scored
494 .iter()
495 .filter(|&&(score, mode)| {
496 mode != winner
497 && score
498 < scored
499 .iter()
500 .find(|&&(_, m)| m == winner)
501 .map_or(f64::INFINITY, |&(s, _)| s)
502 })
503 .count()
504}
505
506/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
507/// four cost less. Set from the measurement in the lane report.
508const SPLIT_BLOCKS: bool = true;
509
510/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
511/// by calling [`encode_key_frame_inner`] both ways.
512pub(crate) fn split_blocks() -> bool {
513 SPLIT_BLOCKS
514}
515
516/// One planar 4:2:0 picture. `y`/`u`/`v` hold one sample per position as
517/// `u16` regardless of bit depth (`crate::decode`'s own `PlaneBuf` has used
518/// `u16` throughout since the round-hbd-r1/r2 widen; this is the last
519/// narrowing boundary that stayed `u8` -- widened lane-hbd r3 so a 10-bit
520/// stream's decode output actually carries 10-bit precision instead of
521/// silently losing its low 2 bits). The encoder only ever produces values in
522/// `0..=255` (it is still 8-bit-only by design, see `encode.rs`'s r2
523/// decision); `Plane::source` narrows right back to `u8` at its two
524/// construction sites, a lossless round trip for that range.
525#[derive(Clone, Debug, PartialEq, Eq)]
526pub struct Picture {
527 /// The picture's width in luma samples.
528 pub width: usize,
529 /// Its height in luma samples.
530 pub height: usize,
531 /// The luma plane, `width * height` samples in raster order.
532 pub y: Vec<u16>,
533 /// The U plane, at half the width and half the height.
534 pub u: Vec<u16>,
535 /// The V plane, the same shape as U.
536 pub v: Vec<u16>,
537}
538
539impl Picture {
540 /// A mid-grey picture of the given size.
541 #[must_use]
542 pub fn grey(width: usize, height: usize) -> Self {
543 Self {
544 width,
545 height,
546 y: vec![128; width * height],
547 u: vec![128; width * height / 4],
548 v: vec![128; width * height / 4],
549 }
550 }
551
552 pub(crate) fn check(&self) -> Result<()> {
553 if self.width == 0
554 || !self.width.is_multiple_of(BLOCK)
555 || !self.height.is_multiple_of(BLOCK)
556 || !self.height.is_multiple_of(BLOCK)
557 {
558 return Err(Error::unsupported(
559 "AV1 encode",
560 "the picture must be a whole number of 32x32 blocks in each direction",
561 ));
562 }
563 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
564 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
565 return Err(Error::unsupported(
566 "AV1 encode",
567 "each plane must carry one sample per position at 4:2:0",
568 ));
569 }
570 Ok(())
571 }
572
573 /// What the public entry points require of the picture they are handed,
574 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
575 /// needs a whole chroma sample per two luma ones) and one sample per
576 /// position on each plane.
577 pub(crate) fn check_even(&self) -> Result<()> {
578 if self.width == 0
579 || self.height == 0
580 || !self.width.is_multiple_of(2)
581 || !self.height.is_multiple_of(2)
582 {
583 return Err(Error::unsupported(
584 "AV1 encode",
585 "the picture's width and height must each be even and nonzero",
586 ));
587 }
588 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
589 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
590 return Err(Error::unsupported(
591 "AV1 encode",
592 "each plane must carry one sample per position at 4:2:0",
593 ));
594 }
595 Ok(())
596 }
597
598 /// This picture, padded by edge replication to the next whole number of
599 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
600 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
601 /// sequence (what the inter tile writer's partition needs on top of
602 /// that). Identity (a plain clone, not a copy through the replication
603 /// loop) when the picture is already that size — the multiple-of-32 (or
604 /// -64) fast path is unchanged.
605 pub(crate) fn padded_to(&self, align: usize) -> Picture {
606 let padded_width = self.width.next_multiple_of(align);
607 let padded_height = self.height.next_multiple_of(align);
608 if padded_width == self.width && padded_height == self.height {
609 return self.clone();
610 }
611 Picture {
612 width: padded_width,
613 height: padded_height,
614 y: pad_plane(
615 &self.y,
616 self.width,
617 self.height,
618 padded_width,
619 padded_height,
620 ),
621 u: pad_plane(
622 &self.u,
623 self.width / 2,
624 self.height / 2,
625 padded_width / 2,
626 padded_height / 2,
627 ),
628 v: pad_plane(
629 &self.v,
630 self.width / 2,
631 self.height / 2,
632 padded_width / 2,
633 padded_height / 2,
634 ),
635 }
636 }
637}
638
639/// lane-hbd r2: the encoder's own reconstruction/source buffers stay `u8`
640/// (8-bit only, unchanged this round -- widening the encoder is out of this
641/// round's scope, see `lanes/hbd-r2.report.md`); this is the local box that
642/// lets it keep calling [`crate::intra::predict`] now that shape is `u16`
643/// in and out. A block-sized round-trip through `u16` is exact for 8-bit
644/// content (every value fits both ways), so this changes no encoder output.
645#[allow(clippy::too_many_arguments)]
646fn intra_predict_u8(
647 mode: u8,
648 angle_delta: i32,
649 above: Option<&[u8]>,
650 left: Option<&[u8]>,
651 corner: Option<u8>,
652 bw: usize,
653 bh: usize,
654 enable_edge_filter: bool,
655 smooth_neighbor: bool,
656 dst: &mut [u8], fctx: &crate::decode::FrameCtx,
657) {
658 // Three heap allocations per call became three stack buffers: this runs
659 // once per mode per trial, and an edge is at most `bw + bh` samples while
660 // a block is at most `BLOCK * BLOCK`. Same samples either way.
661 let mut above_buf = [0u16; 2 * BLOCK];
662 let mut left_buf = [0u16; 2 * BLOCK];
663 let mut dst_buf = [0u16; BLOCK * BLOCK];
664 let widen = |src: &[u8], buf: &mut [u16; 2 * BLOCK]| {
665 for (d, &v) in buf[..src.len()].iter_mut().zip(src) {
666 *d = u16::from(v);
667 }
668 };
669 if let Some(s) = above {
670 widen(s, &mut above_buf);
671 }
672 if let Some(s) = left {
673 widen(s, &mut left_buf);
674 }
675 let above16 = above.map(|s| &above_buf[..s.len()]);
676 let left16 = left.map(|s| &left_buf[..s.len()]);
677 let dst16 = &mut dst_buf[..dst.len()];
678 crate::intra::predict(
679 mode,
680 angle_delta,
681 above16,
682 left16,
683 corner.map(u16::from),
684 bw,
685 bh,
686 enable_edge_filter,
687 smooth_neighbor,
688 dst16, fctx,
689 );
690 for (d, &s) in dst.iter_mut().zip(dst16.iter()) {
691 *d = s as u8;
692 }
693}
694
695/// Pads one plane to `(padded_width, padded_height)` by repeating its last
696/// row and column, so the block coder always sees a whole number of blocks.
697/// [`crop_plane`] undoes this on the way back out.
698fn pad_plane<T: Copy + Default>(
699 source: &[T],
700 width: usize,
701 height: usize,
702 padded_width: usize,
703 padded_height: usize,
704) -> Vec<T> {
705 let mut out = vec![T::default(); padded_width * padded_height];
706 for row in 0..padded_height {
707 let src = source[row.min(height - 1) * width..][..width].as_ref();
708 let dst = &mut out[row * padded_width..][..padded_width];
709 dst[..width].copy_from_slice(src);
710 dst[width..].fill(src[width - 1]);
711 }
712 out
713}
714
715/// The top-left `width` x `height` region of a plane that is `padded_width`
716/// wide, which is the render-size crop [`Picture::padded`]'s replication
717/// exists to let a decoder undo.
718fn crop_plane<T: Copy>(source: &[T], padded_width: usize, width: usize, height: usize) -> Vec<T> {
719 let mut out = Vec::with_capacity(width * height);
720 for row in 0..height {
721 out.extend_from_slice(&source[row * padded_width..][..width]);
722 }
723 out
724}
725
726/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
727/// region a decoder produces, which is the public contract for what a caller
728/// sees back — the padded planes the encoder coded against never leave this
729/// module. Identity when the reconstruction is already that size.
730pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
731 let reconstruction = &encoded.reconstruction;
732 let cropped = if reconstruction.width == width && reconstruction.height == height {
733 reconstruction.clone()
734 } else {
735 Picture {
736 width,
737 height,
738 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
739 u: crop_plane(
740 &reconstruction.u,
741 reconstruction.width / 2,
742 width / 2,
743 height / 2,
744 ),
745 v: crop_plane(
746 &reconstruction.v,
747 reconstruction.width / 2,
748 width / 2,
749 height / 2,
750 ),
751 }
752 };
753 Encoded {
754 stream: encoded.stream.clone(),
755 modes: encoded.modes.clone(),
756 inter_block_share: encoded.inter_block_share,
757 reconstruction: cropped,
758 tile: encoded.tile.clone(),
759 mi_cols: encoded.mi_cols,
760 mi_rows: encoded.mi_rows,
761 base_q_idx: encoded.base_q_idx,
762 tx_select: encoded.tx_select,
763 switchable_motion_mode: encoded.switchable_motion_mode,
764 screen: encoded.screen,
765 start_cdfs: encoded.start_cdfs.clone(),
766 next_cdfs: encoded.next_cdfs.clone(),
767 loop_filter: encoded.loop_filter,
768 loop_restoration: encoded.loop_restoration,
769 allow_intrabc: encoded.allow_intrabc,
770 cdef: encoded.cdef,
771 }
772}
773
774/// A `Cdfs` inside a `Debug` type: the tables are tens of kilobytes of
775/// numbers nobody wants printed, and [`Encoded`] derives `Debug`.
776#[derive(Clone)]
777pub(crate) struct CdfSnapshot(pub(crate) crate::cdf_state::Cdfs);
778
779impl std::fmt::Debug for CdfSnapshot {
780 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
781 f.write_str("CdfSnapshot")
782 }
783}
784
785/// What one call to [`encode_key_frame`] produced.
786#[derive(Clone, Debug)]
787pub struct Encoded {
788 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
789 /// OBU carrying one tile.
790 pub stream: Vec<u8>,
791 /// What a decoder will produce from `stream` — the encoder's own
792 /// reconstruction, which its prediction was built on.
793 pub reconstruction: Picture,
794 /// The luma intra mode each block was coded under, in the order the blocks
795 /// are coded — raster order among the quadrants of each superblock, and
796 /// among the four 16x16 blocks of a quadrant that was split.
797 pub modes: Vec<u8>,
798 /// The fraction of this frame's 32x32 blocks that were coded inter (any
799 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
800 /// for a key frame, which has no such choice — so a caller can tell a
801 /// frame with no motion worth coding from one that never got the chance.
802 pub inter_block_share: f64,
803 /// The tile payload alone, undecorated by any OBU framing, and the frame
804 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
805 /// `crate::decode`'s tests are the only reader; a real decoder gets these
806 /// off the wire by parsing `stream`'s OBUs instead.
807 pub(crate) tile: Vec<u8>,
808 pub(crate) mi_cols: u32,
809 pub(crate) mi_rows: u32,
810 pub(crate) base_q_idx: u8,
811 /// This frame header's `tx_mode == TxMode::Select` ([`tx_select`], and
812 /// [`tx_select_inter`] on an inter frame) — a decoder of `tile` needs it,
813 /// and reading it off `stream`'s header is what `decode_stream` does. A
814 /// test that decodes `tile` directly must pass this one along, or it reads
815 /// a `tx_depth` frame as a `TxMode::Largest` one and desyncs at the first
816 /// block.
817 pub(crate) tx_select: bool,
818 /// This frame header's `is_motion_mode_switchable` (spec 5.9.2) -- the
819 /// bit that makes every eligible single-reference inter block carry a
820 /// `motion_mode` symbol. Same contract as `tx_select` above: a test
821 /// decoding `tile` directly must pass it along or it desyncs at the
822 /// first eligible block.
823 pub(crate) switchable_motion_mode: bool,
824 /// The CDF state this frame's tile writer started from -- the defaults
825 /// for a key frame and for the first inter frame, and the previous
826 /// frame's stored tables after that. A test that decodes `tile` directly
827 /// must feed the decoder this, exactly as `decode_stream` feeds it what
828 /// the frame's `primary_ref_frame` slot holds (same class as
829 /// `tx_select`: a header bit a raw tile decode cannot guess).
830 pub(crate) start_cdfs: CdfSnapshot,
831 /// What this frame stores into the slots it refreshes (spec 7.20,
832 /// `crate::stream::stored_cdfs_for`): its end-of-tile tables with the
833 /// counts reset when `disable_frame_end_update_cdf` is off, and what it
834 /// started from when it is on.
835 pub(crate) next_cdfs: CdfSnapshot,
836 /// This frame header's chosen deblocking parameters
837 /// ([`crate::filter_search::pick_deblock`]) — `reconstruction` is the
838 /// picture the decoder produces UNDER them, so a test that decodes
839 /// `tile` directly must pass these along, exactly as it must `tx_select`
840 /// (class: test asserts against a stale header).
841 pub(crate) loop_filter: LoopFilterParams,
842 /// This frame header's chosen CDEF parameters, threaded for the same
843 /// reason as `loop_filter`.
844 pub(crate) cdef: CdefParams,
845 /// This frame header's `allow_screen_content_tools`
846 /// ([`screen_content`]) -- every intra block of the tile carries the two
847 /// palette-mode symbols under it, so a raw tile decode that guessed
848 /// `false` would desync at the first block (same class as `tx_select`).
849 pub(crate) screen: bool,
850 /// This frame header's chosen loop restoration parameters, threaded for
851 /// the same reason as `loop_filter` -- and doubly so: the per-unit
852 /// filters themselves are coded in `tile`, so a decode of it under a
853 /// stale `RESTORE_NONE` header desyncs at the first superblock.
854 pub(crate) loop_restoration: LoopRestorationParams,
855 /// This frame header's `allow_intrabc` -- every intra block of the tile
856 /// carries a `use_intrabc` symbol under it, so a raw tile decode that
857 /// guessed `false` would desync at the first block (same class as
858 /// `screen`/`tx_select`).
859 pub(crate) allow_intrabc: bool,
860}
861
862thread_local! {
863 /// The share of 16x16 source blocks [`intrabc_worth_it`] found a repeat
864 /// for on the last key frame encoded on this thread -- read by the gates,
865 /// which print it beside the block counts (class `gate-blind-to-feature`).
866 static IBC_SHARE: std::cell::Cell<f64> = const { std::cell::Cell::new(0.0) };
867}
868
869/// [`IBC_SHARE`] for the last key frame encoded on this thread.
870#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
871pub(crate) fn intrabc_source_share() -> f64 {
872 IBC_SHARE.with(std::cell::Cell::get)
873}
874
875thread_local! {
876 /// This SEQUENCE's `seq_force_screen_content_tools`: whether the sequence
877 /// header offers the per-frame `allow_screen_content_tools` bit at all.
878 /// Armed once by the key frame ([`encode_key_frame_inner`], from
879 /// [`screen_content`]) and read by every header builder after it, so that
880 /// the inter frames of a screen sequence lay their headers out the same
881 /// way the sequence header the key frame wrote says they do -- a per-call
882 /// parameter would have to thread through `inter_frame_headers`' four
883 /// public entry points and every hand-built-stream test that calls them.
884 /// A sequence with no screen content leaves this false and writes exactly
885 /// the bits it wrote before this lane.
886 static SEQ_SCREEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
887}
888
889thread_local! {
890 /// Overrides [`screen_content`] for the calling thread, which is what the
891 /// intra-MODE ablations use: on a two-colour synthetic picture the palette
892 /// codes every block losslessly, so both arms of a mode ablation reach
893 /// infinite PSNR and the ablation measures nothing at all (the
894 /// `fixture-proves-the-symbol-not-the-signal` class). An environment
895 /// variable cannot do this -- the tests run in one process, in parallel.
896 static SCREEN_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
897}
898
899#[cfg(test)]
900pub(crate) fn force_screen(value: Option<bool>) {
901 SCREEN_FORCE.with(|c| c.set(value));
902}
903
904pub(crate) fn arm_seq_screen(on: bool) {
905 SEQ_SCREEN.with(|c| c.set(on));
906}
907
908fn seq_screen() -> bool {
909 SEQ_SCREEN.with(std::cell::Cell::get)
910}
911
912/// How many distinct colours a 16x16 luma block may hold and still count as
913/// screen content ([`screen_content`]), `EC_AV1_SCREEN_COLORS`. libaom's own
914/// `av1_set_screen_content_options` bound is 4, which separates NOTHING on a
915/// real (lossily coded, so noisy) desktop capture: `probe_screen_detect`
916/// measures the share of 16x16 blocks under each bound on the gate's own
917/// three clips, and only at 32 do the populations part -- film 20.3..21.9%,
918/// his OBS capture 51.1..51.5%.
919fn screen_colors() -> usize {
920 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
921 *N.get_or_init(|| {
922 std::env::var("EC_AV1_SCREEN_COLORS")
923 .ok()
924 .and_then(|v| v.parse().ok())
925 .unwrap_or(32)
926 })
927}
928
929/// The reciprocal of the frame area those blocks must cover, in tenths --
930/// libaom's own `counts * blk_h * blk_w * 10 > width * height` is 10 (one
931/// tenth). 3 (a third) is the midpoint of the two populations
932/// `probe_screen_detect` measured at the colour bound above.
933/// `EC_AV1_SCREEN_PCT`.
934fn screen_pct() -> usize {
935 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
936 *N.get_or_init(|| {
937 std::env::var("EC_AV1_SCREEN_PCT")
938 .ok()
939 .and_then(|v| v.parse().ok())
940 .unwrap_or(3)
941 })
942}
943
944/// How many frames [`screen_content`] said yes/no to, so a gate can print
945/// whether the detector fired at all (class `gate-blind-to-feature`).
946pub(crate) static SCREEN_FRAMES: [std::sync::atomic::AtomicUsize; 2] =
947 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
948
949/// `av1_set_screen_content_options` (av1/encoder/encoder.c), luma only: count
950/// the distinct colours of every 16x16 block and turn the screen-content
951/// tools on when the blocks holding between 2 and [`screen_colors`] of them
952/// cover more than a [`screen_pct`]th of the frame. `width` is the plane's
953/// stride, `true_*` the frame's real (decodable) extent.
954fn screen_content(y: &[u8], width: usize, true_width: usize, true_height: usize) -> bool {
955 if let Some(forced) = SCREEN_FORCE.with(std::cell::Cell::get) {
956 SCREEN_FRAMES[usize::from(forced)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
957 return forced;
958 }
959 if let Ok(v) = std::env::var("EC_AV1_SCREEN") {
960 let on = v != "0";
961 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
962 return on;
963 }
964 let (blk, limit) = (16usize, screen_colors());
965 let mut counted = 0usize;
966 for by in (0..true_height).step_by(blk) {
967 for bx in (0..true_width).step_by(blk) {
968 let (h, w) = ((true_height - by).min(blk), (true_width - bx).min(blk));
969 let mut seen = [false; 256];
970 let mut colors = 0usize;
971 for row in 0..h {
972 for col in 0..w {
973 let v = usize::from(y[(by + row) * width + bx + col]);
974 if !seen[v] {
975 seen[v] = true;
976 colors += 1;
977 }
978 }
979 }
980 if colors > 1 && colors <= limit {
981 counted += 1;
982 }
983 }
984 }
985 let on = counted * blk * blk * screen_pct() > true_width * true_height;
986 SCREEN_FRAMES[usize::from(on)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
987 on
988}
989
990/// The sequence and frame headers a picture of this size is coded under: one
991/// tile, one transform size per block, no in-loop filter parameters yet
992/// (`crate::encode::pick_and_apply_filters` fills the deblocking levels and
993/// CDEF strengths in once the tile is coded), no CDF adaptation
994/// and no tool the tile writer does not code.
995///
996/// # Errors
997/// Returns an error when the picture is larger than the 16-bit frame size the
998/// sequence header carries.
999pub fn key_frame_headers(
1000 width: usize,
1001 height: usize,
1002 base_q_idx: u8,
1003) -> Result<(SequenceHeader, FrameHeader)> {
1004 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
1005}
1006
1007/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
1008/// studio (limited) range: what this crate's sequence header carried before
1009/// [`crate::encoder`]'s facade could configure it, and what
1010/// [`key_frame_headers`] still asks for.
1011fn unspecified_color_config() -> ColorConfig {
1012 ColorConfig {
1013 bit_depth: 8,
1014 mono_chrome: false,
1015 num_planes: 3,
1016 color_primaries: 2,
1017 transfer_characteristics: 2,
1018 matrix_coefficients: 2,
1019 color_range: false,
1020 subsampling_x: 1,
1021 subsampling_y: 1,
1022 chroma_sample_position: ChromaSamplePosition::Unknown,
1023 separate_uv_delta_q: false,
1024 }
1025}
1026
1027/// [`key_frame_headers`] with the sequence header's colour config named
1028/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
1029/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
1030/// which is all a player picks a colour transform from and which
1031/// [`crate::encoder::Colour`] is the facade's own name for.
1032///
1033/// # Errors
1034/// The same as [`key_frame_headers`].
1035pub(crate) fn key_frame_headers_colour(
1036 width: usize,
1037 height: usize,
1038 base_q_idx: u8,
1039 color_config: ColorConfig,
1040) -> Result<(SequenceHeader, FrameHeader)> {
1041 let bits = |n: usize| -> Result<u32> {
1042 let n = u32::try_from(n).map_err(|_| too_large())?;
1043 if n == 0 || n > 1 << 16 {
1044 return Err(too_large());
1045 }
1046 Ok((32 - (n - 1).leading_zeros()).max(1))
1047 };
1048 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
1049 let (w, h) = (width as u32, height as u32);
1050 let seq = SequenceHeader {
1051 seq_profile: 0,
1052 operating_points: vec![OperatingPoint {
1053 seq_level_idx: 8,
1054 ..OperatingPoint::default()
1055 }],
1056 frame_width_bits,
1057 frame_height_bits,
1058 max_frame_width: w,
1059 max_frame_height: h,
1060 use_128x128_superblock: false,
1061 enable_filter_intra: false,
1062 enable_intra_edge_filter: false,
1063 enable_order_hint: true,
1064 order_hint_bits: 7,
1065 enable_superres: false,
1066 // spec 5.9.19: with the sequence bit set every frame header carries
1067 // `cdef_params`. This encoder writes `cdef_bits == 0` -- one strength
1068 // pair for the whole frame, chosen by `crate::filter_search` -- so no
1069 // `cdef_idx` literal is coded in the tile and a frame that wants no
1070 // CDEF simply carries zero strengths.
1071 enable_cdef: true,
1072 enable_restoration: true,
1073 // SELECT (2) when this sequence's key frame detected screen content
1074 // ([`screen_content`]): the per-frame `allow_screen_content_tools` bit
1075 // is then coded in every frame header, and only the frames that want
1076 // the palette syntax set it. 0 -- the forced-off form, no bit at all
1077 // -- otherwise, which is what every non-screen stream this encoder
1078 // writes still carries.
1079 seq_force_screen_content_tools: if seq_screen() {
1080 ec_av1_syntax::sequence::SELECT_SCREEN_CONTENT_TOOLS
1081 } else {
1082 0
1083 },
1084 seq_force_integer_mv: 0,
1085 color_config,
1086 still_picture: false,
1087 reduced_still_picture_header: false,
1088 timing_info: None,
1089 decoder_model_info: None,
1090 initial_display_delay_present_flag: false,
1091 operating_point: 0,
1092 operating_point_idc: 0,
1093 frame_id_numbers_present_flag: false,
1094 delta_frame_id_length: 0,
1095 additional_frame_id_length: 0,
1096 enable_interintra_compound: false,
1097 enable_masked_compound: false,
1098 // lane-av1obmc2: the sequence bit `allow_warped_motion` is gated on
1099 // (spec 5.5.2). Set only under the warp knob, so the DEFAULT sequence
1100 // header is byte-identical to the streams before this lane.
1101 enable_warped_motion: crate::envflags::env_flag!("EC_AV1_WARP"),
1102 enable_dual_filter: false,
1103 enable_jnt_comp: false,
1104 enable_ref_frame_mvs: false,
1105 film_grain_params_present: false,
1106 };
1107 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
1108 // own (true, unpadded) width and height, not from any block-grid
1109 // alignment — a decoder derives these straight from `frame_width`/
1110 // `frame_height` below, so this must match it exactly.
1111 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
1112 let header = FrameHeader {
1113 frame_type: FrameType::Key,
1114 frame_is_intra: true,
1115 show_frame: true,
1116 error_resilient_mode: true,
1117 // The tile writer keeps the same CDF state the decoder does and
1118 // updates it in the same order, so the frame lets the decoder adapt.
1119 disable_cdf_update: false,
1120 // Nothing reads the state this frame leaves behind: a key frame always
1121 // starts from the defaults, and this encoder emits one frame.
1122 disable_frame_end_update_cdf: true,
1123 force_integer_mv: true,
1124 refresh_frame_flags: 0xFF,
1125 primary_ref_frame: PRIMARY_REF_NONE,
1126 frame_width: w,
1127 frame_height: h,
1128 upscaled_width: w,
1129 render_width: w,
1130 render_height: h,
1131 mi_cols,
1132 mi_rows,
1133 tile_info: TileInfo {
1134 uniform_spacing: true,
1135 cols: 1,
1136 rows: 1,
1137 mi_col_starts: vec![0, mi_cols],
1138 mi_row_starts: vec![0, mi_rows],
1139 tile_size_bytes: 1,
1140 ..TileInfo::default()
1141 },
1142 quantization: QuantizationParams {
1143 base_q_idx,
1144 ..QuantizationParams::default()
1145 },
1146 tx_mode: TxMode::Largest,
1147 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
1148 // intra transform below 32x32, not only 16x16 -- the set this crate
1149 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
1150 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
1151 // so a decoder honouring the header picks the same CDF the writer
1152 // used only if this is set here too, not only on the inter variant
1153 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
1154 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
1155 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
1156 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
1157 // the arithmetic coder's `rng` register from the very first 8x8-leaf
1158 // luma transform onward with no symbol value ever differing.
1159 reduced_tx_set: true,
1160 ..FrameHeader::default()
1161 };
1162 Ok((seq, header))
1163}
1164
1165/// The DPB slot `GOLDEN_FRAME` names in every frame this encoder writes: the
1166/// key frame refreshes all eight slots, each inter frame only slot 0, so slot
1167/// 1 still holds the key frame however long the GOP runs.
1168pub const GOLDEN_SLOT: u8 = 1;
1169
1170/// The frame header for a shown inter frame that predicts from the single
1171/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
1172/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
1173/// reused verbatim: an inter frame never changes the sequence.
1174///
1175/// # Errors
1176/// Returns an error under the same conditions as [`key_frame_headers`].
1177pub fn inter_frame_headers(
1178 width: usize,
1179 height: usize,
1180 base_q_idx: u8,
1181 order_hint: u32,
1182 last_slot: u8,
1183) -> Result<(SequenceHeader, FrameHeader)> {
1184 inter_frame_headers_slots(width, height, base_q_idx, order_hint, last_slot, last_slot, last_slot)
1185}
1186
1187/// [`inter_frame_headers`] with the three slots named apart: the one read as
1188/// `LAST_FRAME`, the one this frame refreshes, and the one read as
1189/// `ALTREF_FRAME`. The encoder alternates the refreshed slot between 0 and 2
1190/// so that the frame two back is still intact in the slot this one is about
1191/// to overwrite -- read before write, spec 7.20's decode order.
1192///
1193/// # Errors
1194/// As [`inter_frame_headers`].
1195pub fn inter_frame_headers_slots(
1196 width: usize,
1197 height: usize,
1198 base_q_idx: u8,
1199 order_hint: u32,
1200 last_slot: u8,
1201 self_slot: u8,
1202 altref_slot: u8,
1203) -> Result<(SequenceHeader, FrameHeader)> {
1204 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
1205 let header = FrameHeader {
1206 frame_type: FrameType::Inter,
1207 frame_is_intra: false,
1208 show_frame: true,
1209 error_resilient_mode: false,
1210 disable_cdf_update: false,
1211 // The tile writer hands its end-of-tile tables to the next frame
1212 // (`encode_sequence_with_ctx`), so the frame stores them the way the
1213 // decoder will load them (spec 7.20).
1214 disable_frame_end_update_cdf: false,
1215 force_integer_mv: false,
1216 order_hint,
1217 primary_ref_frame: 0,
1218 refresh_frame_flags: 1 << self_slot,
1219 // Every reference but `GOLDEN_FRAME` (index 3 of `ref_frame_idx`)
1220 // names the slot this frame both predicts from and refreshes;
1221 // GOLDEN names slot 1, which the key frame wrote when it refreshed
1222 // all eight and which no inter frame ever overwrites, so it holds
1223 // the key frame's own picture for the whole GOP.
1224 ref_frame_idx: {
1225 let mut idx = [last_slot; ec_av1_syntax::REFS_PER_FRAME];
1226 idx[3] = GOLDEN_SLOT;
1227 idx[6] = altref_slot;
1228 idx
1229 },
1230 allow_high_precision_mv: false,
1231 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
1232 // lane-av1obmc: with this bit set every single-reference inter block
1233 // libaom's `motion_mode_allowed` accepts carries a `motion_mode`
1234 // symbol (`crate::tile::write_motion_mode`); `allow_warped_motion`
1235 // stays false, so the alphabet is the 2-symbol `obmc_cdf`. It is tied
1236 // to the OBMC knob rather than always on: with every block choosing
1237 // SIMPLE_TRANSLATION the symbol is pure cost (+0.07% / +0.02% on the
1238 // gate clip), so the DEFAULT path writes no motion_mode syntax at all
1239 // and stays byte-identical to the streams before this lane.
1240 // lane-av1obmc2: the warp knob joins that disjunction, and turns on
1241 // `allow_warped_motion` besides -- which is what makes an eligible
1242 // block read the 3-symbol `motion_mode_cdf` alphabet instead of the
1243 // 2-symbol `obmc_cdf` one (libaom `motion_mode_allowed`).
1244 is_motion_mode_switchable: crate::envflags::env_flag!("EC_AV1_OBMC")
1245 || crate::envflags::env_flag!("EC_AV1_WARP"),
1246 allow_warped_motion: crate::envflags::env_flag!("EC_AV1_WARP"),
1247 use_ref_frame_mvs: false,
1248 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
1249 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
1250 // set this crate carries a table for at 16x16 (see
1251 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
1252 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
1253 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
1254 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
1255 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
1256 // path) -- with this flag set, `get_tx_set`'s intra branch returns
1257 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
1258 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
1259 reduced_tx_set: true,
1260 ..key
1261 };
1262 Ok((seq, header))
1263}
1264
1265fn too_large() -> Error {
1266 Error::unsupported(
1267 "AV1 encode",
1268 "the picture is larger than a frame size can carry",
1269 )
1270}
1271
1272/// One plane of the picture being coded, and the reconstruction being built
1273/// beside it.
1274/// What one committed 4x4 cell left behind for the coefficient contexts of
1275/// the blocks that read it as a neighbour -- tile.rs `neighbour_state`, which
1276/// is the same state decode.rs records.
1277#[derive(Clone, Copy, Default, PartialEq, Eq)]
1278struct CoefCtx {
1279 /// spec `cul_level`: the sum of the unit's coded magnitudes, clamped to 7.
1280 level: u8,
1281 /// The DC sign this cell votes with: `-1` negative, `1` positive, `0` when
1282 /// the DC itself was zero (tile.rs `dc_vote`).
1283 dc: i8,
1284}
1285
1286/// One plane's coefficient contexts, committed in CODING ORDER: the search
1287/// prices partition TREES, so the neighbour state a candidate reads has to be
1288/// whatever the blocks coded before it left -- the parent's committed
1289/// neighbours for a tree's first child, the just-committed sibling for the
1290/// later ones. Keeping the map as a full per-4x4-cell grid rather than the
1291/// writer's two running bands is what makes that fall out: a trial commits
1292/// over its own rectangle ([`Plane::commit`]) and a losing trial is undone
1293/// with the pixels ([`Plane::restore`]), so what a candidate reads above and
1294/// to its left is exactly what the tile writer's `Neighbours` bands will hold
1295/// when it gets there.
1296///
1297/// Before this map the pricer took both contexts as zero, which is exact for
1298/// a luma transform covering its whole block and the largest remaining row of
1299/// the pricer census everywhere else (all-zero chroma under-priced 41-81%).
1300#[derive(Default)]
1301struct CoefCtxMap {
1302 cells: Vec<CoefCtx>,
1303 stride: usize,
1304 /// Whether the transforms being priced right now are SMALLER than the
1305 /// block they sit in -- a `TxMode::Select` depth split
1306 /// ([`Plane::code_tx_depth`]) or an inter var-tx split
1307 /// ([`commit_inter_luma`]). That is the one thing the (x, y, side) of a
1308 /// trial cannot tell, and it is what decides whether luma reads context 0
1309 /// or `SKIP_CONTEXTS` (tile.rs `write_luma_tus`).
1310 tu_split: bool,
1311}
1312
1313struct Plane<'a> {
1314 source: &'a [u8],
1315 reconstruction: Vec<u8>,
1316 width: usize,
1317 height: usize,
1318 /// The frame's true, decodable extent in this plane's own units --
1319 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
1320 /// not `width`/`height` above, which is the padded coding-surface size.
1321 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
1322 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
1323 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
1324 /// this bound, even though the padded reconstruction buffer holds real
1325 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
1326 /// those instead of stopping here is what desyncs prediction at the true
1327 /// edge.
1328 true_width: usize,
1329 true_height: usize,
1330 /// This plane's own tile's pixel bounds, in this plane's units -- the
1331 /// encoder side of the decoder's `PlaneBuf::set_tile_origin`: intra
1332 /// prediction never reaches across a tile edge even though the
1333 /// neighbouring tile's real samples sit right there in the shared
1334 /// reconstruction. `(0, 0, width, height)` is the single-tile case and
1335 /// leaves every edge exactly as it was before tiles existed.
1336 tile_x0: usize,
1337 tile_y0: usize,
1338 tile_x1: usize,
1339 tile_y1: usize,
1340 /// [`CoefCtxMap`]: what the blocks already committed left for the
1341 /// coefficient contexts of the ones still being priced. Sized on the
1342 /// first commit, so a plane literal does not have to know its own extent
1343 /// twice.
1344 ctx: CoefCtxMap,
1345}
1346
1347impl Plane<'_> {
1348 /// Clips this plane's edge reads to one tile ([`Self::tile_x0`]),
1349 /// called at every superblock of the frame-raster search with the rect
1350 /// of the tile that superblock belongs to.
1351 fn set_tile(&mut self, x0: usize, y0: usize, x1: usize, y1: usize) {
1352 self.tile_x0 = x0;
1353 self.tile_y0 = y0;
1354 self.tile_x1 = x1.min(self.width);
1355 self.tile_y1 = y1.min(self.height);
1356 }
1357 /// The reconstructed samples a block at `(x, y)` predicts from: the row
1358 /// above it, the column to its left and the sample between them, each
1359 /// missing where the block sits against an edge of the frame.
1360 ///
1361 /// `reach` says whether the samples above the block's right and below its
1362 /// left are decoded, which is what a directional mode reads into; where
1363 /// they are not, or where the frame ends first, the edge is shorter and
1364 /// the predictor repeats its last sample, exactly as the decoder's clamp
1365 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
1366 fn edges(
1367 &self,
1368 x: usize,
1369 y: usize,
1370 side: usize,
1371 reach: Reach,
1372 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
1373 // Even a block's *own* edge is clamped to the true frame bound, not
1374 // just a `reach` extension: libaom's `av1_predict_intra_block`
1375 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
1376 // this block's own right/bottom to the frame edge -- from
1377 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
1378 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
1379 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
1380 // samples the row/column above/left holds before the decoder starts
1381 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
1382 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
1383 // extent straddles that edge legally (`has_half`) -- the transform
1384 // still covers the whole block, but prediction does not get to read
1385 // real reconstructed pixels past the true edge for its own row/column,
1386 // only for the padded tail it invents.
1387 let own_across = x + side.min(self.true_width.saturating_sub(x));
1388 let across = if reach.above_right {
1389 own_across + side.min(self.true_width.saturating_sub(own_across))
1390 } else {
1391 own_across
1392 }
1393 .min(self.width);
1394 let own_down = y + side.min(self.true_height.saturating_sub(y));
1395 let down = if reach.below_left {
1396 own_down + side.min(self.true_height.saturating_sub(own_down))
1397 } else {
1398 own_down
1399 }
1400 .min(self.height);
1401 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
1402 // whose own origin already sits past the true edge -- only reachable
1403 // through a partition trial priced for comparison on a split this
1404 // frame's straddling quadrant will go on to refuse (see
1405 // `a_picture_off_the_block_grid_is_refused`), never through a block
1406 // this encoder actually commits. Such a block has no true-edge
1407 // samples above or left of it at all, same as `y == 0`/`x == 0`.
1408 let across = across.min(self.tile_x1);
1409 let down = down.min(self.tile_y1);
1410 let above = (y > self.tile_y0 && across > x)
1411 .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec());
1412 let left = (x > self.tile_x0 && down > y).then(|| {
1413 (y..down)
1414 .map(|row| self.reconstruction[row * self.width + x - 1])
1415 .collect::<Vec<_>>()
1416 });
1417 let corner = (x > self.tile_x0 && y > self.tile_y0)
1418 .then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
1419 (above, left, corner)
1420 }
1421
1422 /// Codes one block under one mode without committing it: hands back the
1423 /// levels, the block the decoder would reconstruct, the squared error
1424 /// against the source and an estimate of what the levels cost in bits.
1425 fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Trial {
1426 self.trial_typed(at, mode, base_q_idx, deadzone, TxType::DctDct, fctx)
1427 }
1428
1429 /// [`Self::trial`] under a named transform type -- what an intra chroma
1430 /// block gets, since chroma codes no `tx_type` symbol and the decoder
1431 /// derives the type from the chroma mode itself (`Intra_Mode_To_Tx_Type`,
1432 /// spec 9.3, [`crate::decode::default_intra_tx_type`]). Luma keeps
1433 /// `DCT_DCT`, which is the one type this writer's `tx_type` symbol names.
1434 #[allow(clippy::too_many_arguments)]
1435 /// Sum of absolute differences between the source block at `(x, y)` and a
1436 /// `side x side` prediction, as the whole number it is.
1437 ///
1438 /// Bit-identical to the `f64` accumulation it replaces: every partial sum
1439 /// is an integer below `255 * 64 * 64` (under 2^21), which `f64` holds
1440 /// exactly, so no add here rounds and the order of the adds cannot change
1441 /// the result. Dropping the per-pixel `i / side` and `i % side` -- an
1442 /// integer division per sample -- is what lets the row walk vectorize.
1443 fn block_sad(&self, x: usize, y: usize, side: usize, prediction: &[u8]) -> f64 {
1444 let mut sad = 0u32;
1445 for row in 0..side {
1446 let source = &self.source[(y + row) * self.width + x..][..side];
1447 for (&s, &p) in source.iter().zip(&prediction[row * side..][..side]) {
1448 sad += u32::from(s.abs_diff(p));
1449 }
1450 }
1451 f64::from(sad)
1452 }
1453
1454 /// Squared error between the source block at `(x, y)` and a reconstruction
1455 /// of it. Exact for the same reason [`Self::block_sad`] is: the largest
1456 /// total is `255^2 * 64 * 64`, under 2^28.
1457 fn block_sse(&self, x: usize, y: usize, side: usize, reconstruction: &[u8]) -> f64 {
1458 let mut sse = 0u64;
1459 for row in 0..side {
1460 let source = &self.source[(y + row) * self.width + x..][..side];
1461 for (&s, &r) in source.iter().zip(&reconstruction[row * side..][..side]) {
1462 let d = u32::from(s.abs_diff(r));
1463 sse += u64::from(d * d);
1464 }
1465 }
1466 sse as f64
1467 }
1468
1469 fn trial_typed(
1470 &self,
1471 at: At,
1472 mode: u8,
1473 base_q_idx: u8,
1474 deadzone: f64,
1475 tx_type: TxType,
1476 fctx: &crate::decode::FrameCtx,
1477 ) -> Trial {
1478 let At {
1479 x, y, side, reach, ..
1480 } = at;
1481 let (above, left, corner) = self.edges(x, y, side, reach);
1482 // Per-candidate scratch on the search's hottest path, so both buffers
1483 // live on the stack -- `side` is at most `BLOCK` -- rather than
1484 // costing a malloc/free pair per trial (`mc_trial` already does this).
1485 let mut prediction = [0u8; BLOCK * BLOCK];
1486 let prediction = &mut prediction[..side * side];
1487 intra_predict_u8(
1488 mode,
1489 0,
1490 above.as_deref(),
1491 left.as_deref(),
1492 corner,
1493 side,
1494 side,
1495 false,
1496 false,
1497 prediction, fctx,
1498 );
1499
1500 let mut residual = [0i32; BLOCK * BLOCK];
1501 let residual = &mut residual[..side * side];
1502 for row in 0..side {
1503 for col in 0..side {
1504 residual[row * side + col] =
1505 i32::from(self.source[(y + row) * self.width + x + col])
1506 - i32::from(prediction[row * side + col]);
1507 }
1508 }
1509 #[cfg(test)]
1510 let t = std::time::Instant::now();
1511 let levels =
1512 forward_and_quantize_typed(residual, side, 8, i32::from(base_q_idx), deadzone, tx_type);
1513 let coded =
1514 dequant_and_inverse_typed(&levels, side, 8, i32::from(base_q_idx), 0, 0, tx_type);
1515 #[cfg(test)]
1516 stage_add(2, t.elapsed());
1517
1518 let reconstruction: Vec<u8> = prediction
1519 .iter()
1520 .zip(&coded)
1521 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
1522 .collect();
1523 let sse = self.block_sse(x, y, side, &reconstruction);
1524 // What the levels cost is priced through the same CDFs the tile writer
1525 // will code them with, so the search ranks modes -- and the partition
1526 // trial ranks trees -- by the bits they actually spend.
1527 #[cfg(test)]
1528 let t = std::time::Instant::now();
1529 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
1530 // What the search used before it could price a block exactly: a
1531 // level costs its magnitude's width plus a sign and a run. Kept
1532 // reachable from the sweep so the two rate terms can be compared
1533 // on one build.
1534 levels
1535 .iter()
1536 .filter(|&&level| level != 0)
1537 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
1538 .sum()
1539 } else {
1540 {
1541 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, at.set);
1542 crate::tile::coeff_bits(
1543 &levels,
1544 at.set,
1545 crate::decode::q_ctx_of(base_q_idx),
1546 skip_ctx,
1547 sign_ctx,
1548 )
1549 }
1550 };
1551 #[cfg(test)]
1552 stage_add(3, t.elapsed());
1553 Trial {
1554 levels,
1555 reconstruction,
1556 sse,
1557 bits,
1558 }
1559 }
1560
1561 /// [`Self::trial`] with the prediction already built, so that an inter
1562 /// block's motion-compensated prediction can go through the same
1563 /// residual/quantize/reconstruct path an intra block's does. `skip`
1564 /// takes the prediction as the reconstruction outright, coding no
1565 /// residual at all — what a `NEARESTMV` block that names no coefficients
1566 /// codes.
1567 #[allow(clippy::too_many_arguments)]
1568 fn code_from_prediction(
1569 &self,
1570 x: usize,
1571 y: usize,
1572 side: usize,
1573 prediction: &[u8],
1574 skip: bool,
1575 base_q_idx: u8,
1576 deadzone: f64,
1577 set: TxbSet,
1578 ) -> Trial {
1579 if skip {
1580 let sse = self.block_sse(x, y, side, prediction);
1581 return Trial {
1582 levels: vec![0i32; side * side],
1583 reconstruction: prediction.to_vec(),
1584 sse,
1585 bits: 0.0,
1586 };
1587 }
1588 let mut residual = [0i32; BLOCK * BLOCK];
1589 let residual = &mut residual[..side * side];
1590 for row in 0..side {
1591 for col in 0..side {
1592 residual[row * side + col] =
1593 i32::from(self.source[(y + row) * self.width + x + col])
1594 - i32::from(prediction[row * side + col]);
1595 }
1596 }
1597 #[cfg(test)]
1598 let t = std::time::Instant::now();
1599 let levels = forward_and_quantize(residual, side, 8, i32::from(base_q_idx), deadzone);
1600 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
1601 #[cfg(test)]
1602 stage_add(2, t.elapsed());
1603 let reconstruction: Vec<u8> = prediction
1604 .iter()
1605 .zip(&coded)
1606 .map(|(&p, &c)| (i32::from(p) + c).clamp(0, 255) as u8)
1607 .collect();
1608 let sse = self.block_sse(x, y, side, &reconstruction);
1609 #[cfg(test)]
1610 let t = std::time::Instant::now();
1611 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
1612 levels
1613 .iter()
1614 .filter(|&&level| level != 0)
1615 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
1616 .sum()
1617 } else {
1618 {
1619 let (skip_ctx, sign_ctx) = self.coef_ctx(x, y, side, set);
1620 crate::tile::coeff_bits(
1621 &levels,
1622 set,
1623 crate::decode::q_ctx_of(base_q_idx),
1624 skip_ctx,
1625 sign_ctx,
1626 )
1627 }
1628 };
1629 #[cfg(test)]
1630 stage_add(3, t.elapsed());
1631 Trial {
1632 levels,
1633 reconstruction,
1634 sse,
1635 bits,
1636 }
1637 }
1638
1639 /// Codes this block's luma at transform depth `depth`: the
1640 /// `(side >> depth)^2` transform units in raster order, each predicted
1641 /// from the reconstruction the units before it left behind -- exactly
1642 /// what the decoder's multi-transform-unit branch does (decode.rs
1643 /// `decode_block`, `tu_reach`) -- and each transformed, quantised and
1644 /// reconstructed on its own. Commits the result and hands back the
1645 /// block-coordinate levels, the block's squared error and what its
1646 /// coefficients cost.
1647 fn code_tx_depth(
1648 &mut self,
1649 at: At,
1650 mode: u8,
1651 depth: usize,
1652 search: &Search, fctx: &crate::decode::FrameCtx,
1653 ) -> (Vec<i32>, f64, f64) {
1654 let At { x, y, side, reach, .. } = at;
1655 let tx = side >> depth;
1656 let n = 1usize << depth;
1657 let set = match tx {
1658 32 => TxbSet::Luma32,
1659 16 => TxbSet::Luma16,
1660 8 => TxbSet::Luma8,
1661 _ => TxbSet::Luma4,
1662 };
1663 let mut levels = vec![0i32; side * side];
1664 census_add(4, n * n);
1665 // A unit smaller than its block reads the neighbour magnitude table
1666 // for its `txb_skip` context, not context 0 ([`Plane::coef_ctx`]).
1667 self.ctx.tu_split = n > 1;
1668 let (mut sse, mut bits) = (0.0, 0.0);
1669 for tu_row in 0..n {
1670 for tu_col in 0..n {
1671 let (col_off, row_off) = (tu_col * tx, tu_row * tx);
1672 let tu = At {
1673 x: x + col_off,
1674 y: y + row_off,
1675 side: tx,
1676 reach: Reach::of_tu(side, side, col_off, row_off, tx, tx, reach),
1677 set,
1678 };
1679 let trial = self.trial(tu, mode, search.base_q_idx, search.deadzone, fctx);
1680 sse += trial.sse;
1681 bits += trial.bits;
1682 self.commit(tu.x, tu.y, tx, &trial);
1683 for row in 0..tx {
1684 levels[(row_off + row) * side + col_off..][..tx]
1685 .copy_from_slice(&trial.levels[row * tx..][..tx]);
1686 }
1687 }
1688 }
1689 self.ctx.tu_split = false;
1690 (levels, sse, bits)
1691 }
1692
1693 /// Writes a trial's reconstruction back into the plane, and the
1694 /// coefficient context it leaves for its neighbours ([`CoefCtxMap`]).
1695 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
1696 for row in 0..side {
1697 self.reconstruction[(y + row) * self.width + x..][..side]
1698 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
1699 }
1700 self.commit_ctx(x, y, side, &trial.levels);
1701 }
1702
1703 /// Publishes one committed transform's own context over every 4x4 cell it
1704 /// covers -- tile.rs `neighbour_state` + `Neighbours::record_planes`,
1705 /// which is what the writer will read when it reaches the next block.
1706 fn commit_ctx(&mut self, x: usize, y: usize, side: usize, levels: &[i32]) {
1707 if self.ctx.cells.is_empty() {
1708 self.ctx.stride = self.width.div_ceil(4);
1709 self.ctx.cells = vec![CoefCtx::default(); self.ctx.stride * self.height.div_ceil(4)];
1710 }
1711 let cul = levels.iter().map(|l| l.unsigned_abs()).sum::<u32>().min(7) as u8;
1712 let state = CoefCtx {
1713 level: cul,
1714 dc: match levels[0].signum() {
1715 0 => 0,
1716 -1 => -1,
1717 _ => 1,
1718 },
1719 };
1720 let n = (side / 4).max(1);
1721 // Only up to the frame's TRUE extent: the writer's own
1722 // `Neighbours::record_planes` clamps to `blocks_wide`/`blocks_high`
1723 // (spec `av1_set_entropy_contexts`, off the true `mi_cols`/`mi_rows`)
1724 // and leaves the cells past it uncoded even mid-block, so a
1725 // straddling block publishes context for its inside part only.
1726 let rows = n.min(self.true_height.saturating_sub(y).div_ceil(4));
1727 let cols = n.min(self.true_width.saturating_sub(x).div_ceil(4));
1728 for row in 0..rows {
1729 let start = (y / 4 + row) * self.ctx.stride + x / 4;
1730 let end = (start + cols).min(self.ctx.cells.len());
1731 if start < end {
1732 self.ctx.cells[start..end].fill(state);
1733 }
1734 }
1735 }
1736
1737 /// A block committed without any residual at all ([`ibc_commit`]): the
1738 /// cells it covers coded nothing, and leaving an earlier trial's state
1739 /// there would price its neighbours off a block that was never coded.
1740 fn commit_ctx_zero(&mut self, x: usize, y: usize, side: usize) {
1741 self.commit_ctx(x, y, side, &[0i32]);
1742 }
1743
1744 /// The `txb_skip` and `dc_sign` contexts a transform at `(x, y)` of this
1745 /// plane reads, off what the blocks before it in coding order committed
1746 /// ([`CoefCtxMap`]) -- the writer's own derivation: chroma reads whether
1747 /// the above/left neighbours coded anything (tile.rs
1748 /// `write_block_planes`), luma reads context 0 when its transform covers
1749 /// its whole block and decode.rs `SKIP_CONTEXTS` off the neighbour
1750 /// magnitude tiers when it does not (tile.rs `write_luma_tus` /
1751 /// `Neighbours::luma_skip_ctx`), and both planes read the DC sign vote of
1752 /// the same neighbours (tile.rs `dc_sign_ctx`).
1753 ///
1754 /// A neighbour outside this plane's own TILE does not exist, exactly as
1755 /// the writer's per-tile `Neighbours` bands start blank.
1756 ///
1757 /// CLOSED (lane-av1straddle): the decisions this price changes used to
1758 /// make `decode_stream_round_trips_an_odd_size_gop` and
1759 /// `an_odd_size_gop_round_trips_bit_exact_against_the_encoder_reconstruction`
1760 /// fail at 216x96. Never this map: the writer coded the phantom
1761 /// transform units of a right-edge-straddling 32x32 (tile.rs
1762 /// `write_luma_tus`, now clipped to the frame's true `mi_cols`/`mi_rows`
1763 /// like decode.rs and libaom), which libdav1d and libaom both refused
1764 /// outright while a decision change was what first walked into it.
1765 fn coef_ctx(&self, x: usize, y: usize, side: usize, set: TxbSet) -> (usize, usize) {
1766 if self.ctx.cells.is_empty() {
1767 return (0, 0);
1768 }
1769 let n = (side / 4).max(1);
1770 let (cx, cy) = (x / 4, y / 4);
1771 let (mut top, mut left) = (0u8, 0u8);
1772 let mut vote = 0i32;
1773 if y > self.tile_y0 && cy > 0 {
1774 for cell in &self.ctx.cells[(cy - 1) * self.ctx.stride + cx..][..n] {
1775 top |= cell.level;
1776 vote += i32::from(cell.dc);
1777 }
1778 }
1779 if x > self.tile_x0 && cx > 0 {
1780 for row in 0..n {
1781 let cell = self.ctx.cells[(cy + row) * self.ctx.stride + cx - 1];
1782 left |= cell.level;
1783 vote += i32::from(cell.dc);
1784 }
1785 }
1786 let skip_ctx = if set.is_chroma() {
1787 usize::from(top != 0) + usize::from(left != 0)
1788 } else if self.ctx.tu_split {
1789 crate::decode::SKIP_CONTEXTS[usize::from(top).min(4)][usize::from(left).min(4)]
1790 } else {
1791 0
1792 };
1793 let sign_ctx = match vote.signum() {
1794 0 => 0,
1795 -1 => 1,
1796 _ => 2,
1797 };
1798 (skip_ctx, sign_ctx)
1799 }
1800
1801 /// The source samples of one square, contiguous — what a motion search
1802 /// compares its candidates' predictions against ([`motion::search`]'s
1803 /// `source`), since [`Self::source`] itself is the whole plane, strided
1804 /// by [`Self::width`].
1805 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
1806 rows_of(self.source, self.width, x, y, side)
1807 }
1808
1809 /// The reconstructed samples of one square, so that a partition trial can
1810 /// be undone.
1811 /// The reconstructed samples of one square AND the coefficient contexts
1812 /// its cells hold, so that a partition trial can be undone whole: a
1813 /// losing trial that left its own nz/DC state behind would price the
1814 /// blocks after it off a block the tile writer never codes.
1815 fn snapshot(&self, x: usize, y: usize, side: usize) -> (Vec<u8>, Vec<CoefCtx>) {
1816 (
1817 rows_of(&self.reconstruction, self.width, x, y, side),
1818 self.ctx_rows(x, y, side),
1819 )
1820 }
1821
1822 fn ctx_rows(&self, x: usize, y: usize, side: usize) -> Vec<CoefCtx> {
1823 if self.ctx.cells.is_empty() {
1824 return Vec::new();
1825 }
1826 let n = (side / 4).max(1);
1827 (0..n)
1828 .flat_map(|row| {
1829 let start = (y / 4 + row) * self.ctx.stride + x / 4;
1830 self.ctx.cells[start..(start + n).min(self.ctx.cells.len())].to_vec()
1831 })
1832 .collect()
1833 }
1834
1835 /// Puts a snapshot back.
1836 fn restore(&mut self, x: usize, y: usize, side: usize, saved: &(Vec<u8>, Vec<CoefCtx>)) {
1837 for row in 0..side {
1838 self.reconstruction[(y + row) * self.width + x..][..side]
1839 .copy_from_slice(&saved.0[row * side..][..side]);
1840 }
1841 if saved.1.is_empty() {
1842 return;
1843 }
1844 let n = (side / 4).max(1);
1845 for row in 0..n {
1846 let start = (y / 4 + row) * self.ctx.stride + x / 4;
1847 let end = (start + n).min(self.ctx.cells.len());
1848 if start < end {
1849 self.ctx.cells[start..end].copy_from_slice(&saved.1[row * n..][..end - start]);
1850 }
1851 }
1852 }
1853
1854 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
1855 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
1856 /// prescreen by the identical rule rather than a second one that could
1857 /// drift from it.
1858 fn intra_scores(
1859 &self,
1860 at: At,
1861 modes: &[u8],
1862 mode_bits: &[f64; 13],
1863 lambda: f64, fctx: &crate::decode::FrameCtx,
1864 ) -> Vec<(f64, u8)> {
1865 let At {
1866 x, y, side, reach, ..
1867 } = at;
1868 let (above, left, corner) = self.edges(x, y, side, reach);
1869 modes
1870 .iter()
1871 .map(|&mode| {
1872 let mut prediction = vec![0u8; side * side];
1873 intra_predict_u8(
1874 mode,
1875 0,
1876 above.as_deref(),
1877 left.as_deref(),
1878 corner,
1879 side,
1880 side,
1881 false,
1882 false,
1883 &mut prediction, fctx,
1884 );
1885 let sad = self.block_sad(x, y, side, &prediction);
1886 (sad + lambda * mode_bits[usize::from(mode)], mode)
1887 })
1888 .collect()
1889 }
1890
1891 /// Codes one block under every mode the search offers (or, when
1892 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
1893 /// pre-pass plus DC) and commits the one whose squared error and
1894 /// estimated rate come out cheapest.
1895 ///
1896 /// The prediction is built once per mode regardless -- the full RD trial
1897 /// needs it too -- so ranking modes by SAD on that same prediction before
1898 /// running the expensive part (forward transform, quantize, reconstruct,
1899 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
1900 /// only to sum.
1901 fn search_block(
1902 &mut self,
1903 at: At,
1904 search: &Search,
1905 mode_bits: &[f64; 13], fctx: &crate::decode::FrameCtx,
1906 ) -> (Vec<Coeff>, u8, f64) {
1907 let At {
1908 x, y, side, reach, ..
1909 } = at;
1910 let (above, left, corner) = self.edges(x, y, side, reach);
1911 // Nothing ranks by the SAD pre-pass unless `top_k` prunes by it (or
1912 // the census reports it), so summing it under the default unpruned
1913 // search is `side * side` absolute differences per mode spent on a
1914 // number no one reads.
1915 let want_sad = search.top_k.is_some() || census_on();
1916 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
1917 .modes
1918 .iter()
1919 .map(|&mode| {
1920 let mut prediction = vec![0u8; side * side];
1921 intra_predict_u8(
1922 mode,
1923 0,
1924 above.as_deref(),
1925 left.as_deref(),
1926 corner,
1927 side,
1928 side,
1929 false,
1930 false,
1931 &mut prediction, fctx,
1932 );
1933 let sad = if want_sad {
1934 self.block_sad(x, y, side, &prediction)
1935 } else {
1936 0.0
1937 };
1938 (
1939 sad + search.lambda * mode_bits[usize::from(mode)],
1940 mode,
1941 prediction,
1942 )
1943 })
1944 .collect();
1945 if let Some(k) = search.top_k {
1946 if k < scored.len() {
1947 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
1948 let dc_entry = dc_pos.map(|i| scored.remove(i));
1949 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
1950 scored.truncate(if dc_entry.is_some() {
1951 k.saturating_sub(1)
1952 } else {
1953 k
1954 });
1955 if let Some(dc_entry) = dc_entry {
1956 scored.push(dc_entry);
1957 }
1958 }
1959 }
1960 let ranking: Vec<(f64, u8)> = if census_on() {
1961 scored.iter().map(|&(score, mode, _)| (score, mode)).collect()
1962 } else {
1963 Vec::new()
1964 };
1965 census_add(0, 1);
1966 census_add(1, scored.len());
1967 let mut best: Option<(f64, u8, Trial)> = None;
1968 for (_, mode, prediction) in scored {
1969 let trial = self.code_from_prediction(
1970 x,
1971 y,
1972 side,
1973 &prediction,
1974 false,
1975 search.base_q_idx,
1976 search.deadzone,
1977 at.set,
1978 );
1979 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
1980 if best
1981 .as_ref()
1982 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
1983 {
1984 best = Some((cost, mode, trial));
1985 }
1986 }
1987 let (cost, mode, trial) = best.expect("the search offers at least one mode");
1988 if census_on() {
1989 LUMA_RANK[sad_rank(&ranking, mode).min(12)]
1990 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1991 }
1992 self.commit(x, y, side, &trial);
1993 (coeffs(&trial.levels, side), mode, cost)
1994 }
1995}
1996
1997/// Where one block sits in its plane, and how far past its own edges its
1998/// prediction may read.
1999#[derive(Clone, Copy)]
2000struct At {
2001 x: usize,
2002 y: usize,
2003 side: usize,
2004 reach: Reach,
2005 /// Which of the tile writer's coefficient tables this block's levels are
2006 /// coded with, and so which the search prices them through.
2007 set: TxbSet,
2008}
2009
2010/// Which of the samples past a block's own edges the decoder has decoded by
2011/// the time it predicts the block, and so which a directional mode may read.
2012///
2013/// The decoder derives these from its `BlockDecoded` flags, which are cleared
2014/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
2015/// that map, this reads the answer the same way libaom and rav1e do: for a
2016/// block whose transform covers it whole, whether the samples above its right
2017/// (or below its left) are decoded depends only on where the block sits inside
2018/// its 64x64 superblock, which is a pinned table per block size.
2019#[derive(Clone, Copy, Debug, PartialEq, Eq)]
2020pub(crate) struct Reach {
2021 pub(crate) above_right: bool,
2022 pub(crate) below_left: bool,
2023}
2024
2025/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
2026/// libaom): for a block that is neither in the superblock's top row nor its
2027/// rightmost column, whether the block above and to its right is coded before
2028/// it. Indexed by the block's position in the superblock, in blocks of its own
2029/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
2030/// 128, not this crate's 64 superblock -- bit by bit from the low end.
2031const HAS_TOP_RIGHT: [&[u8]; 4] = [
2032 &[255, 85, 119, 85, 127, 85, 119, 85],
2033 &[95, 87],
2034 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
2035 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
2036 &[
2037 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
2038 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
2039 ],
2040
2041 // has_tr_4x4 (libaom av1/common/reconintra.c, transcribed verbatim) --
2042 // table_stride(4) == 32 (128 / 4), so 32 bits per row, 32 rows, 128
2043 // bytes. Sub-8x8 leaves (lane-sub8) are the only blocks that reach here
2044 // with side 4 outside a TX4 split; without their own row they clamped
2045 // into the 8x8 table and read above-right samples the decoder has not
2046 // written yet (all-zero pixels in the bottom-right triangle of a
2047 // directional 4x4 leaf).
2048 &[
2049 255, 255, 255, 255, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127,
2050 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127, 85, 85, 85, 85,
2051 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119,
2052 85, 85, 85, 85, 255, 255, 255, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85,
2053 127, 127, 127, 127, 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 255, 127, 255, 127,
2054 85, 85, 85, 85, 119, 119, 119, 119, 85, 85, 85, 85, 127, 127, 127, 127, 85, 85, 85, 85,
2055 119, 119, 119, 119, 85, 85, 85, 85,
2056 ],
2057];
2058
2059/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
2060/// left.
2061const HAS_BOTTOM_LEFT: [&[u8]; 4] = [
2062 &[84, 16, 84, 0, 84, 16, 84, 0],
2063 &[4, 4],
2064 // has_bl_8x8 (libaom av1/common/reconintra.c)
2065 &[
2066 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
2067 84, 85, 16, 17, 84, 85, 0, 0,
2068 ],
2069
2070 // has_bl_4x4 (same source, same order).
2071 &[
2072 84, 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17,
2073 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,
2074 85, 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 0, 0, 0, 84, 85, 85, 85, 16, 17, 17, 17, 84,
2075 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,
2076 85, 85, 16, 17, 17, 17, 84, 85, 85, 85, 0, 1, 1, 1, 84, 85, 85, 85, 16, 17, 17, 17, 84, 85,
2077 85, 85, 0, 0, 0, 0,
2078 ],
2079];
2080
2081/// `has_tr_vert_*` (libaom `reconintra.c`, `has_tr_vert_tables`), indexed by
2082/// [`Reach::table`] exactly like [`HAS_TOP_RIGHT`]: inside a
2083/// `PARTITION_VERT_A`/`_B` the square sub-blocks are visited TL, BL, TR, BR
2084/// rather than in raster order, so the bottom-left square's top-right
2085/// neighbour is the partition's own right-hand rectangle -- not yet decoded.
2086/// libaom switches tables on the partition type (`get_has_tr_table`); the
2087/// ordinary table says 1 where this one says 0 (32x32 at row 1 col 0:
2088/// `95` bit 4 = 1 vs `15` bit 4 = 0), which is exactly the case
2089/// lane-part32 r5 caught reading undecoded samples.
2090const HAS_TOP_RIGHT_VERT: [&[u8]; 3] = [
2091 // has_tr_vert_16x16
2092 &[255, 0, 119, 0, 127, 0, 119, 0],
2093 // has_tr_vert_32x32
2094 &[15, 7],
2095 // has_tr_vert_8x8
2096 &[
2097 255, 255, 0, 0, 119, 119, 0, 0, 127, 127, 0, 0, 119, 119, 0, 0, 255, 127, 0, 0, 119, 119,
2098 0, 0, 127, 127, 0, 0, 119, 119, 0, 0,
2099 ],
2100];
2101
2102/// [`HAS_TOP_RIGHT_VERT`]'s sibling, `has_bl_vert_tables`.
2103const HAS_BOTTOM_LEFT_VERT: [&[u8]; 3] = [
2104 // has_bl_vert_16x16
2105 &[254, 16, 254, 0, 254, 16, 254, 0],
2106 // has_bl_vert_32x32
2107 &[14, 14],
2108 // has_bl_vert_8x8
2109 &[
2110 254, 255, 16, 17, 254, 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0, 254, 255, 16, 17, 254,
2111 255, 0, 1, 254, 255, 16, 17, 254, 255, 0, 0,
2112 ],
2113];
2114
2115thread_local! {
2116 /// Set for the duration of a `PARTITION_VERT_A`/`_B`'s own sub-blocks
2117 /// (see [`Reach::vert_ab_partition`]) -- libaom carries the partition
2118 /// type down into `has_top_right`/`has_bottom_left` as an argument, and
2119 /// threading one bool through this crate's already twenty-argument
2120 /// `decode_block` would touch every call site instead of the two arms
2121 /// that need it.
2122 static VERT_AB_PARTITION: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
2123}
2124
2125/// Restores [`VERT_AB_PARTITION`] to what it was when the guard was made.
2126pub(crate) struct VertAbGuard(bool);
2127
2128impl Drop for VertAbGuard {
2129 fn drop(&mut self) {
2130 VERT_AB_PARTITION.with(|c| c.set(self.0));
2131 }
2132}
2133
2134/// The `has_tr_*` / `has_bl_*` tables for every rectangular shape this
2135/// decoder codes (libaom `reconintra.c`, generated from the oracle's source
2136/// so no byte is retyped). Each is indexed by
2137/// `(blk_row_in_sb << (5 - log2(bw / 4))) + blk_col_in_sb`, i.e. row stride
2138/// `128 / bw` bits ([`Reach::table_stride`]) on libaom's 128-pixel
2139/// superblock grid; on this crate's 64-pixel superblock the highest index a
2140/// shape can reach stays inside its own table, so no wrap is involved.
2141///
2142/// lane-tx4x8 r3: the previous two-row `HAS_TOP_RIGHT_RECT`/
2143/// `HAS_BOTTOM_LEFT_RECT` pair held 32x16/16x32 only and a `_` arm routed
2144/// every other shape -- 16x8 strips among them -- to the 32x16 row, wrong at
2145/// 10 of the 21 reachable superblock positions for above-right and 7 for
2146/// below-left.
2147/// `has_tr_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
2148const 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];
2149/// `has_bl_4x8` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 32 bits (`128 / 4`).
2150const 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];
2151/// `has_tr_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
2152const 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];
2153/// `has_bl_8x4` (`reconintra.c`), transcribed verbatim: 64 bytes, row stride 16 bits (`128 / 8`).
2154const 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];
2155/// `has_tr_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
2156const HAS_TR_8X16: [u8; 16] = [255, 255, 119, 119, 127, 127, 119, 119, 255, 127, 119, 119, 127, 127, 119, 119];
2157/// `has_bl_8x16` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 16 bits (`128 / 8`).
2158const HAS_BL_8X16: [u8; 16] = [16, 17, 0, 1, 16, 17, 0, 0, 16, 17, 0, 1, 16, 17, 0, 0];
2159/// `has_tr_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
2160const HAS_TR_16X8: [u8; 16] = [255, 0, 85, 0, 119, 0, 85, 0, 127, 0, 85, 0, 119, 0, 85, 0];
2161/// `has_bl_16x8` (`reconintra.c`), transcribed verbatim: 16 bytes, row stride 8 bits (`128 / 16`).
2162const HAS_BL_16X8: [u8; 16] = [254, 84, 254, 16, 254, 84, 254, 0, 254, 84, 254, 16, 254, 84, 254, 0];
2163/// `has_tr_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
2164const HAS_TR_16X32: [u8; 4] = [255, 119, 127, 119];
2165/// `has_bl_16x32` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 8 bits (`128 / 16`).
2166const HAS_BL_16X32: [u8; 4] = [16, 0, 16, 0];
2167/// `has_tr_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
2168const HAS_TR_32X16: [u8; 4] = [15, 5, 7, 5];
2169/// `has_bl_32x16` (`reconintra.c`), transcribed verbatim: 4 bytes, row stride 4 bits (`128 / 32`).
2170const HAS_BL_32X16: [u8; 4] = [78, 14, 78, 14];
2171/// `has_tr_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
2172const HAS_TR_32X64: [u8; 1] = [127];
2173/// `has_bl_32x64` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 4 bits (`128 / 32`).
2174const HAS_BL_32X64: [u8; 1] = [0];
2175/// `has_tr_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
2176const HAS_TR_64X32: [u8; 1] = [19];
2177/// `has_bl_64x32` (`reconintra.c`), transcribed verbatim: 1 bytes, row stride 2 bits (`128 / 64`).
2178const HAS_BL_64X32: [u8; 1] = [34];
2179/// `has_tr_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
2180const 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];
2181/// `has_bl_4x16` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 32 bits (`128 / 4`).
2182const 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];
2183/// `has_tr_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
2184const 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];
2185/// `has_bl_16x4` (`reconintra.c`), transcribed verbatim: 32 bytes, row stride 8 bits (`128 / 16`).
2186const 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];
2187/// `has_tr_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
2188const HAS_TR_8X32: [u8; 8] = [255, 255, 127, 127, 255, 127, 127, 127];
2189/// `has_bl_8x32` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 16 bits (`128 / 8`).
2190const HAS_BL_8X32: [u8; 8] = [0, 1, 0, 0, 0, 1, 0, 0];
2191/// `has_tr_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
2192const HAS_TR_32X8: [u8; 8] = [15, 0, 5, 0, 7, 0, 5, 0];
2193/// `has_bl_32x8` (`reconintra.c`), transcribed verbatim: 8 bytes, row stride 4 bits (`128 / 32`).
2194const HAS_BL_32X8: [u8; 8] = [238, 78, 238, 14, 238, 78, 238, 14];
2195/// `has_tr_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
2196const HAS_TR_16X64: [u8; 2] = [255, 127];
2197/// `has_bl_16x64` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 8 bits (`128 / 16`).
2198const HAS_BL_16X64: [u8; 2] = [0, 0];
2199/// `has_tr_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
2200const HAS_TR_64X16: [u8; 2] = [3, 1];
2201/// `has_bl_64x16` (`reconintra.c`), transcribed verbatim: 2 bytes, row stride 2 bits (`128 / 64`).
2202const HAS_BL_64X16: [u8; 2] = [42, 42];
2203
2204/// The `has_tr_*`/`has_bl_*` row for one rectangular block shape.
2205fn rect_reach_tables(bw: usize, bh: usize) -> (&'static [u8], &'static [u8]) {
2206 match (bw, bh) {
2207 (4, 8) => (&HAS_TR_4X8, &HAS_BL_4X8),
2208 (8, 4) => (&HAS_TR_8X4, &HAS_BL_8X4),
2209 (8, 16) => (&HAS_TR_8X16, &HAS_BL_8X16),
2210 (16, 8) => (&HAS_TR_16X8, &HAS_BL_16X8),
2211 (16, 32) => (&HAS_TR_16X32, &HAS_BL_16X32),
2212 (32, 16) => (&HAS_TR_32X16, &HAS_BL_32X16),
2213 (32, 64) => (&HAS_TR_32X64, &HAS_BL_32X64),
2214 (64, 32) => (&HAS_TR_64X32, &HAS_BL_64X32),
2215 (4, 16) => (&HAS_TR_4X16, &HAS_BL_4X16),
2216 (16, 4) => (&HAS_TR_16X4, &HAS_BL_16X4),
2217 (8, 32) => (&HAS_TR_8X32, &HAS_BL_8X32),
2218 (32, 8) => (&HAS_TR_32X8, &HAS_BL_32X8),
2219 (16, 64) => (&HAS_TR_16X64, &HAS_BL_16X64),
2220 (64, 16) => (&HAS_TR_64X16, &HAS_BL_64X16),
2221 _ => unreachable!("no libaom has_tr/has_bl table for a {bw}x{bh} block"),
2222 }
2223}
2224
2225impl Reach {
2226 /// `has_top_right`/`has_bottom_left` (libaom `reconintra.c`) for a
2227 /// transform unit at `(col_off, row_off)` INSIDE a `bw`x`bh` block whose
2228 /// own answer is `block` -- a different rule from the standalone-block
2229 /// tables, because a unit's neighbours are mostly its own block's
2230 /// already-reconstructed units:
2231 /// * top-right: available while the unit to the right is still inside
2232 /// the block (`col_off + tx < bw`); otherwise only the block's top row
2233 /// of units reaches past it, through the block-level answer
2234 /// (libaom's `row_off > 0` branch returns exactly
2235 /// `col_off + txw < plane_bw`).
2236 /// * bottom-left: a unit outside the block's left column has none
2237 /// (libaom returns 0 for `col_off > 0`); inside the block
2238 /// (`row_off + tx < bh`) they are the left unit's, already
2239 /// reconstructed; the bottom row falls back to the block-level answer.
2240 pub(crate) fn of_tu(
2241 bw: usize,
2242 bh: usize,
2243 col_off: usize,
2244 row_off: usize,
2245 // The unit's own width and height in pixels; equal for a square
2246 // transform, different for the rect unit a 1:4 strip's first split
2247 // produces (lane-rectsplitx r1).
2248 tx_w: usize,
2249 tx_h: usize,
2250 block: Self,
2251 ) -> Self {
2252 // A block wider than 64 is coded in 64x64 "mu" chunks in raster
2253 // order, so both libaom predicates special-case it (lane-sb128c r10);
2254 // without this the last unit column of every chunk of a 128x64 block
2255 // predicts from a chunk libaom has not decoded yet.
2256 let wide = bw > 64;
2257 Self {
2258 above_right: if row_off > 0 {
2259 // `has_top_right`'s `row_off > 0` branch: the offset is taken
2260 // modulo the 64-wide chunk, except for the one unit whose
2261 // top-right corner is the centre of a 128x128 block.
2262 if wide {
2263 (row_off == 64 && col_off + tx_w == 64) || (col_off % 64) + tx_w < 64
2264 } else {
2265 col_off + tx_w < bw
2266 }
2267 } else if col_off + tx_w < bw {
2268 true
2269 } else {
2270 block.above_right
2271 },
2272 below_left: if wide && col_off > 0 && col_off % 64 == 0 {
2273 // `has_bottom_left`: at the left edge of a right-hand chunk
2274 // the bottom-left pixels are in the already-coded left chunk,
2275 // provided they stay inside it.
2276 (row_off % 64) + tx_h < bh.min(64)
2277 } else if col_off > 0 {
2278 false
2279 } else if row_off + tx_h < bh {
2280 true
2281 } else {
2282 block.below_left
2283 },
2284 }
2285 }
2286
2287 /// What a block of `side` samples at `(x, y)` may read past its own edges,
2288 /// in a frame of `width` by `height`.
2289 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize, fctx: &crate::decode::FrameCtx) -> Self {
2290 Self {
2291 above_right: y > 0 && x + side < width && Self::top_right(side, x, y, fctx),
2292 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y, fctx),
2293 }
2294 }
2295
2296 /// [`Self::of`] for a true `bw`x`bh` rectangular block (lane-intradisp
2297 /// r1) -- `libaom`'s `has_top_right`/`has_bottom_left` index by the
2298 /// block's own width for the row stride and by its own height for the
2299 /// row/column position (`reconintra.c`'s `bw_in_mi_log2`/`bh_in_mi_log2`),
2300 /// unlike the square [`Self::of`] which uses one `side` for everything.
2301 pub(crate) fn of_rect(
2302 bw: usize,
2303 bh: usize,
2304 x: usize,
2305 y: usize,
2306 width: usize,
2307 height: usize, fctx: &crate::decode::FrameCtx,
2308 ) -> Self {
2309 Self {
2310 above_right: y > 0 && x + bw < width && Self::top_right_rect(bw, bh, x, y, fctx),
2311 below_left: x > 0 && y + bh < height && Self::bottom_left_rect(bw, bh, x, y, fctx),
2312 }
2313 }
2314
2315 /// [`Self::of`] for one transform unit of a square block whose transform
2316 /// is smaller than itself (libaom `has_top_right`/`has_bottom_left` with
2317 /// non-zero `row_off`/`col_off`): interior units answer from the block's
2318 /// own geometry, and only a unit on the block's top row (resp. left
2319 /// column) reaches the table -- which is the BLOCK's table read at the
2320 /// BLOCK's position, never a table row for the transform's size. Letting
2321 /// the unit stand in for a block of its own size agrees with libaom for
2322 /// the ordinary tables, but the `has_tr_vert_*`/`has_bl_vert_*` pair has
2323 /// no 4x4 row at all (`has_tr_vert_tables[BLOCK_4X4]` is NULL), so a TX4
2324 /// unit inside an 8x8 square of a `PARTITION_VERT_A`/`_B` panicked on a
2325 /// real `--enable-tx-size-search=1` stream (lane-ab16 r2).
2326 /// libaom `has_top_right` at block granularity (`row_off`/`col_off` 0,
2327 /// the transform covering the whole block, luma): everything before the
2328 /// table lookup is that function's own early-exit ladder.
2329 fn top_right_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2330 let sb_mi: usize = reach_sb_px(fctx) / 4;
2331 let (mi_row, mi_col) = (y / 4, x / 4);
2332 let bw_log2 = (bw / 4).trailing_zeros() as usize;
2333 let bh_log2 = (bh / 4).trailing_zeros() as usize;
2334 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
2335 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
2336 // Top row of the superblock: the top-right pixels are in the (already
2337 // decoded) superblock above.
2338 if blk_row == 0 {
2339 return true;
2340 }
2341 // Rightmost column: they fall in the superblock to the right.
2342 if ((blk_col + 1) << bw_log2) >= sb_mi {
2343 return false;
2344 }
2345 let table = rect_reach_tables(bw, bh).0;
2346 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
2347 }
2348
2349 /// libaom `has_top_right`'s own index arithmetic:
2350 /// `(blk_row << (MAX_MIB_SIZE_LOG2 - bw_in_mi_log2)) + blk_col`, and
2351 /// `MAX_MIB_SIZE_LOG2` is 5 (`enums.h`: libaom's tables are laid out for a
2352 /// 128x128 superblock = 32 mi), NOT this crate's 64x64 = 16. lane-rectx r5:
2353 /// r4 wrote `4 - bw_log2`, halving the row stride -- every table row but
2354 /// the first then read the wrong byte (16x8 wrong at 80 mi positions in a
2355 /// 64-wide SB, 8x16 at 16, 32x16 at 64, a regression against main).
2356 /// [`tests::rect_reach_tables_are_indexed_with_a_32_mi_row_stride`] pins it.
2357 fn rect_table_index(bw_log2: usize, blk_row: usize, blk_col: usize) -> usize {
2358 (blk_row << (5 - bw_log2)) + blk_col
2359 }
2360
2361 /// libaom `has_bottom_left`, same granularity as [`Self::top_right_rect`].
2362 fn bottom_left_rect(bw: usize, bh: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2363 let sb_mi: usize = reach_sb_px(fctx) / 4;
2364 let (mi_row, mi_col) = (y / 4, x / 4);
2365 let bw_log2 = (bw / 4).trailing_zeros() as usize;
2366 let bh_log2 = (bh / 4).trailing_zeros() as usize;
2367 let blk_row = (mi_row & (sb_mi - 1)) >> bh_log2;
2368 let blk_col = (mi_col & (sb_mi - 1)) >> bw_log2;
2369 // Leftmost column of the superblock: the bottom-left pixels are in
2370 // the left superblock iff they stay inside its height.
2371 if blk_col == 0 {
2372 return (blk_row << bh_log2) + (bh / 4) < sb_mi;
2373 }
2374 // Bottom row (and not the leftmost column): they fall in the
2375 // superblock below, which is not decoded yet.
2376 if ((blk_row + 1) << bh_log2) >= sb_mi {
2377 return false;
2378 }
2379 let table = rect_reach_tables(bw, bh).1;
2380 Self::bit(table, Self::rect_table_index(bw_log2, blk_row, blk_col))
2381 }
2382
2383 /// Marks every [`Reach::of`] made until the returned guard drops as being
2384 /// inside a `PARTITION_VERT_A`/`_B` (libaom's `get_has_tr_table` /
2385 /// `get_has_bl_table` partition argument). Rectangular sub-blocks are
2386 /// unaffected: libaom's own comment says vertical rectangles keep their
2387 /// non-vert table, which is what [`Reach::of_rect`] already reads.
2388 /// Whether a `PARTITION_VERT_A`/`_B`'s sub-blocks are being decoded
2389 /// right now ([`Self::vert_ab_partition`]'s guard is alive), so a caller
2390 /// can count the sub-block work that partition creates (lane-ab16).
2391 pub(crate) fn in_vert_ab() -> bool {
2392 VERT_AB_PARTITION.with(std::cell::Cell::get)
2393 }
2394
2395 pub(crate) fn vert_ab_partition() -> VertAbGuard {
2396 VertAbGuard(VERT_AB_PARTITION.with(|c| c.replace(true)))
2397 }
2398
2399 /// Neither, which is all a mode that reads no further than its own edges
2400 /// needs.
2401 pub(crate) fn none() -> Self {
2402 Self {
2403 above_right: false,
2404 below_left: false,
2405 }
2406 }
2407
2408 /// `has_top_right` for a block whose transform covers it whole: the top
2409 /// row of a superblock reads into the superblock above, which is decoded;
2410 /// the rightmost column would read into the superblock to the right, which
2411 /// is not; and everything between is the table's to answer.
2412 fn top_right(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2413 let (row, col, per_side) = Self::position(side, x, y, fctx);
2414 if row == 0 {
2415 return true;
2416 }
2417 if col + 1 == per_side {
2418 return false;
2419 }
2420 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
2421 // (the clamp corner-cut that used to live here is gone); sides
2422 // 16/32/64 share row 0 exactly as libaom's tables repeat.
2423 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
2424 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
2425 // -- a reach over-estimate (extra above-right reference pixels),
2426 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
2427 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
2428 // NB: named `table_row`, not `row` -- `row` above is the block's
2429 // position inside the superblock and is what the bit index below
2430 // steps by (a merge that shadowed it desynced every block size).
2431 let table_row = Self::table(side);
2432 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_TOP_RIGHT_VERT.len() {
2433 HAS_TOP_RIGHT_VERT[table_row]
2434 } else {
2435 HAS_TOP_RIGHT[table_row]
2436 };
2437 Self::bit(
2438 table,
2439 (row * Self::table_stride(side) + col) % (table.len() * 8),
2440 )
2441 }
2442
2443 /// `has_bottom_left` for such a block: the leftmost column of a superblock
2444 /// reads into the superblock to its left, which is decoded only as far
2445 /// down as its own bottom; the bottom row would read into the superblock
2446 /// below, which is not decoded at all; and the table answers the rest.
2447 fn bottom_left(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> bool {
2448 let (row, col, per_side) = Self::position(side, x, y, fctx);
2449 if col == 0 {
2450 return row * side + side < reach_sb_px(fctx);
2451 }
2452 if row + 1 == per_side {
2453 return false;
2454 }
2455 // lane-sub8 r4: side 4 now has its own `has_tr_4x4`/`has_bl_4x4` row
2456 // (the clamp corner-cut that used to live here is gone); sides
2457 // 16/32/64 share row 0 exactly as libaom's tables repeat.
2458 // corner-cut: libaom transcribes no vert 4x4 row, so a side-4 block
2459 // inside a `PARTITION_VERT_A`/`_B` falls back to the ordinary table
2460 // -- a reach over-estimate (extra above-right reference pixels),
2461 // never a stream desync. Ceiling: transcribe `has_tr_vert_4x4` /
2462 // `has_bl_vert_4x4` and extend the VERT tables to four rows.
2463 // NB: named `table_row`, not `row` -- `row` above is the block's
2464 // position inside the superblock and is what the bit index below
2465 // steps by (a merge that shadowed it desynced every block size).
2466 let table_row = Self::table(side);
2467 let table = if VERT_AB_PARTITION.with(std::cell::Cell::get) && table_row < HAS_BOTTOM_LEFT_VERT.len() {
2468 HAS_BOTTOM_LEFT_VERT[table_row]
2469 } else {
2470 HAS_BOTTOM_LEFT[table_row]
2471 };
2472 Self::bit(
2473 table,
2474 (row * Self::table_stride(side) + col) % (table.len() * 8),
2475 )
2476 }
2477
2478 /// Where a block sits inside its superblock, in blocks of its own size,
2479 /// and how many of them a superblock is across.
2480 fn position(side: usize, x: usize, y: usize, fctx: &crate::decode::FrameCtx) -> (usize, usize, usize) {
2481 let sb = reach_sb_px(fctx);
2482 ((y % sb) / side, (x % sb) / side, sb / side)
2483 }
2484
2485 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
2486 /// these tables to its compile-time maximum superblock (128, spec
2487 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
2488 /// size an encode actually uses, so a block's row in the bit index steps
2489 /// by 128 / `side` even though this crate only ever codes a 64
2490 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
2491 /// here instead indexes the wrong bit for every block size but the one
2492 /// where 64 and 128 give the same stride.
2493 fn table_stride(side: usize) -> usize {
2494 128 / side
2495 }
2496
2497 /// Which of the three block sizes the encoder codes a table row is for.
2498 fn table(side: usize) -> usize {
2499 if side == BLOCK {
2500 1
2501 } else if side == 8 {
2502 2
2503 } else if side == 4 {
2504 3
2505 } else {
2506 0
2507 }
2508 }
2509
2510 /// One bit of a table, counting from the low end of its first byte.
2511 fn bit(table: &[u8], index: usize) -> bool {
2512 (table[index / 8] >> (index % 8)) & 1 != 0
2513 }
2514}
2515
2516/// What one symbol costs against a CDF, in bits.
2517/// The smallest LEAF an OBMC candidate is offered for, so the census can
2518/// attribute the tool's effect by footprint (`EC_AV1_OBMC_MIN`, default 8 --
2519/// every leaf; 16 or 32 turn the smaller leaves off). Only read when
2520/// `EC_AV1_OBMC` is on, and never by the 32x32 whole-block candidate.
2521///
2522/// MEASURED at native, `EC_AV1_OBMC=1` throughout, BD vs libaom / vs rav1e
2523/// (12 frames, four quantizers, the standing keep table):
2524///
2525/// | min side | film 1080p | film 2160p | screen |
2526/// |---|---|---|---|
2527/// | OBMC off | +18.0 / +0.7 | +47.3 / +19.2 | +59.4 / -10.0 |
2528/// | 32 (32x32 only) | +18.4 / +1.1 | +47.3 / +19.2 | +59.1 / -10.0 |
2529/// | 16 | +18.4 / +1.1 | +47.3 / +19.2 | +59.3 / -10.0 |
2530/// | 8 (every leaf) | +18.7 / +1.4 | +47.3 / +19.2 | +59.3 / -10.0 |
2531///
2532/// So the leaves are not the thing that was holding OBMC back: at 8x8 the
2533/// candidate WINS 9704 of the 11462 leaves that code the symbol on the 1080p
2534/// film -- 85% of them, far past libaom's own rate -- and costs another 0.3
2535/// BD points on top of the 0.4 the 32x32 candidate already costs. A tool
2536/// that wins the local RD on five blocks in six and loses ladder bytes is
2537/// the `local-RD-on-references` class again, not a missing footprint.
2538///
2539/// RE-MEASURED on lane-av1lambda at [`LAMBDA_SCALE`] 0.05 (min side 8):
2540/// +16.7 / -0.5, +47.1 / +19.2, +51.8 / -14.2 against the same build with
2541/// the knob off (+17.0 / -0.3, +47.0 / +19.2, +51.6 / -14.2). The 0.7-point
2542/// loss on the 1080p film became a 0.3-point win and the other two rows went
2543/// 0.1-0.2 the other way, so OBMC is now neutral rather than a loss -- half
2544/// of the "local win, ladder loss" it was charged with was the rate weight.
2545/// It still does not meet the keep rule (two down, one flat, both columns).
2546/// The tool stays OFF by default; the upgrade path is the price, not the size
2547/// (the 640x384 arm reads +78.9/+36.4, +94.9/+56.3, +54.2/+0.8 at min side 8
2548/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1 off -- two rows down, the
2549/// 1080p film up, i.e. the same disagreement between the two gates).
2550fn obmc_min_side() -> usize {
2551 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2552 *N.get_or_init(|| {
2553 std::env::var("EC_AV1_OBMC_MIN")
2554 .ok()
2555 .and_then(|v| v.parse().ok())
2556 .unwrap_or(8)
2557 })
2558}
2559
2560/// What the `motion_mode`/`obmc` symbol costs (spec 5.11.24), off the tables
2561/// this frame's writer really starts from (`tile::obmc_symbol_bits`) -- the
2562/// same frame-CDF price the coefficients of a non-screen frame are estimated
2563/// with, not the static default table.
2564/// The same price for whichever alphabet the writer will really use for this
2565/// block: `warp_alphabet` is `motion_mode_allowed`'s 3-symbol choice
2566/// (`allow_warped_motion` and at least one warp sample), otherwise the
2567/// 2-symbol `obmc` one. Both sides of every motion-mode comparison in the
2568/// search pay it, so the alphabet cancels out of a comparison and only its
2569/// per-value spread decides.
2570fn motion_mode_bits(write_w: usize, write_h: usize, motion: u8, warp_alphabet: bool) -> f64 {
2571 let Some(row) = crate::decode::motion_mode_cdf_row(write_w, write_h) else {
2572 return 0.0;
2573 };
2574 match warp_alphabet {
2575 true => crate::tile::motion_mode_symbol_bits(row, motion),
2576 false => crate::tile::obmc_symbol_bits(row, motion == 1),
2577 }
2578}
2579
2580/// MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_WARP=1` turns the
2581/// candidate, the header's `allow_warped_motion` and the sequence's
2582/// `enable_warped_motion` on together). BD vs libaom / vs rav1e, the standing
2583/// native keep table, against the same build with the knob off:
2584///
2585/// | clip | warp on | off |
2586/// |---|---|---|
2587/// | film 1080p | +18.7 / +1.6 | +18.0 / +0.7 |
2588/// | film 2160p | +47.3 / +19.2 | +47.3 / +19.2 |
2589/// | screen | +59.2 / -9.9 | +59.4 / -10.0 |
2590///
2591/// One row flat, one 0.2 down against libaom and 0.1 up against rav1e, and
2592/// the 1080p film 0.7/0.9 UP -- the keep rule wants two down and one flat, so
2593/// it stays off. The 640x384 arm reads +78.7/+36.5, +95.1/+56.4, +54.7/+1.2
2594/// against +78.8/+36.1, +95.1/+56.4, +54.5/+1.1. The census says the tool
2595/// fires: 7.0% / 2.7% / 2.4% of the blocks that code a motion_mode symbol
2596/// take WARPED_CAUSAL at native (197+91+2441 blocks on the 1080p film), so
2597/// this is a measured loss, not an inert knob. Same shape as the OBMC
2598/// candidate above it (`obmc_min_side`): a local RD win that does not convert
2599/// into ladder bytes.
2600///
2601/// RE-MEASURED on lane-av1lambda, after [`LAMBDA_SCALE`] moved 0.1 -> 0.05,
2602/// because a tool whose gain is local and whose cost is the rate it adds is
2603/// exactly what a halved rate weight re-judges. The verdict FLIPS SIGN:
2604///
2605/// | clip | warp on | off (both at lambda 0.05) |
2606/// |---|---|---|
2607/// | film 1080p | +16.7 / -0.5 | +17.0 / -0.3 |
2608/// | film 2160p | +47.0 / +19.1 | +47.0 / +19.2 |
2609/// | screen | +51.3 / -14.3 | +51.6 / -14.2 |
2610///
2611/// two rows down against libaom (0.3 each) with the third flat, and the rav1e
2612/// column inside 0.1 everywhere -- which reads as a keep rather than the
2613/// 0.7/0.9 loss it was. The knob still ships OFF here: the margin is 0.3 BD
2614/// points on a table whose other levers move whole points, and turning warp
2615/// on by default is a stream-feature change (`enable_warped_motion` in the
2616/// sequence header) that wants its own conformance pass, not a lambda lane's
2617/// side effect.
2618///
2619/// The WARPED_CAUSAL prediction of one square single-reference block: the
2620/// decoder's own warp-sample walk (`decode::find_samples` +
2621/// `warp::select_samples`), least-squares model (`warp::find_projection`) and
2622/// affine predictor (`warp::warp_affine`), driven off the encoder's own mi
2623/// grid -- never a second implementation of any of the three. `None` when the
2624/// block would code no motion_mode symbol at all, when it has no warp sample
2625/// (the writer then codes the 2-symbol alphabet, which has no WARPED value),
2626/// or when the projection is not filter-representable (the decoder would then
2627/// predict translationally, so the mode is pure cost).
2628#[allow(clippy::too_many_arguments)]
2629fn warp_prediction(
2630 grid: &MiGrid,
2631 (mi_row, mi_col): (usize, usize),
2632 (mi_rows, mi_cols): (usize, usize),
2633 (x, y): (usize, usize),
2634 side: usize,
2635 mv: (i32, i32),
2636 ref_frame: i8,
2637 ref_planes: [(&[u16], usize, usize, usize); 3],
2638 fctx: &crate::decode::FrameCtx,
2639) -> Option<[Vec<u8>; 3]> {
2640 let n4 = side / 4;
2641 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
2642 return None;
2643 }
2644 let mut samples = crate::decode::find_samples(
2645 grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows, ref_frame, fctx,
2646 );
2647 if samples.is_empty() {
2648 return None;
2649 }
2650 if samples.len() > 1 {
2651 crate::warp::select_samples(mv, &mut samples, side as i32, side as i32);
2652 }
2653 let params = crate::warp::find_projection(
2654 &samples,
2655 side as i32,
2656 side as i32,
2657 mv.1,
2658 mv.0,
2659 mi_row as i32,
2660 mi_col as i32,
2661 )?;
2662 let mut pred = [
2663 vec![0u16; side * side],
2664 vec![0u16; side * side / 4],
2665 vec![0u16; side * side / 4],
2666 ];
2667 // The translational prediction first, exactly as the decoder builds it,
2668 // then the affine one over the planes whose OWN block is at least 8x8
2669 // (libaom `av1_init_warp_params` bails below that, so an 8x8 luma block's
2670 // 4x4 chroma stays translational).
2671 for (i, r) in ref_planes.into_iter().enumerate() {
2672 let luma_plane = i == 0;
2673 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
2674 let s = if luma_plane { side } else { side / 2 };
2675 mc::predict(
2676 r.0,
2677 r.1,
2678 r.2,
2679 r.3,
2680 mv_to_q4(px, mv.1, luma_plane),
2681 mv_to_q4(py, mv.0, luma_plane),
2682 s,
2683 s,
2684 &mut pred[i],
2685 fctx,
2686 );
2687 if crate::decode::warp_plane_allowed(s, s) {
2688 let (sub, cside) = (usize::from(!luma_plane) as i32, s as i32);
2689 crate::warp::warp_affine(
2690 &params,
2691 r.0,
2692 r.2 as i32,
2693 r.3 as i32,
2694 r.1 as i32,
2695 &mut pred[i],
2696 px as i32,
2697 py as i32,
2698 cside,
2699 cside,
2700 cside,
2701 sub,
2702 sub,
2703 fctx,
2704 );
2705 }
2706 }
2707 let [py_buf, pu_buf, pv_buf] = pred;
2708 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
2709 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
2710}
2711
2712pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
2713 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
2714 let width = cdf[symbol] - low;
2715 // lane-av1speed: a CDF interval is a 15-bit width, so there are only
2716 // 32769 prices a symbol can carry; the `log2` behind each is computed
2717 // once instead of per call (libm's `__log2_fma` was 5% of the encoder's
2718 // profile -- this function is called for every symbol of every candidate
2719 // the RD search prices). Each entry is exactly the expression this used
2720 // to evaluate, so every price is bit-identical.
2721 static PRICES: std::sync::OnceLock<Vec<f64>> = std::sync::OnceLock::new();
2722 PRICES.get_or_init(|| {
2723 (0..=32768u32)
2724 .map(|w| -(f64::from(w) / 32768.0).log2())
2725 .collect()
2726 })[usize::from(width)]
2727}
2728
2729/// What the tile writer spends to say a block is coded in each of the thirteen
2730/// modes, given the modes of the blocks above it and to its left: the luma mode
2731/// symbol against the CDF those two neighbours pick, the angle delta a
2732/// directional mode carries, and the chroma mode symbol, whose CDF the luma
2733/// mode itself indexes.
2734///
2735/// Without this the search is blind to what a mode costs to name, which is not
2736/// a rounding error: a directional mode on a picture that does not run that way
2737/// is a rate loss the squared error never sees.
2738/// Codes one square of the picture as a single block: searches the luma mode,
2739/// codes both chroma planes DC, and hands back the block and what it cost --
2740/// squared error plus lambda times the bits its symbols spend.
2741/// How many halvings of a `side`-square block's transform the `tx_depth`
2742/// symbol can name (libaom's per-size depth cap, `cdf::TX_SIZE_CAT0`'s two
2743/// symbols against `CAT1`..`CAT3`'s three), floored at the 4x4 transform.
2744fn max_tx_depth(side: usize) -> usize {
2745 match side {
2746 8 => 1,
2747 16 | 32 => 2,
2748 _ => 0,
2749 }
2750}
2751
2752/// What the `tx_depth` symbol itself costs, off the size category's own CDF.
2753/// Priced at context row 0 -- the writer picks the real row from its
2754/// neighbours' transform sizes, which the search has no view of; the term is
2755/// the same for every depth of one block either way, so it only shifts the
2756/// depth-0-versus-split margin, never the ordering between two splits.
2757fn tx_depth_bits(side: usize, depth: usize) -> f64 {
2758 match side {
2759 8 => symbol_bits(&cdf::TX_SIZE_CAT0[0], depth),
2760 16 => symbol_bits(&cdf::TX_SIZE_CAT1[0], depth),
2761 32 => symbol_bits(&cdf::TX_SIZE_CAT2[0], depth),
2762 _ => symbol_bits(&cdf::TX_SIZE_CAT3[0], depth),
2763 }
2764}
2765
2766/// How many blocks resolved to each `tx_depth`, the fire count that says
2767/// whether the depth search below reaches its candidates at all.
2768static TX_DEPTH_HITS: [std::sync::atomic::AtomicUsize; 3] =
2769 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
2770
2771/// Reads [`TX_DEPTH_HITS`] and zeroes it, so a gate can attribute the counts
2772/// to its own encode.
2773#[cfg(test)]
2774pub(crate) fn take_tx_depth_hits() -> [usize; 3] {
2775 std::array::from_fn(|d| TX_DEPTH_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
2776}
2777
2778/// How many inter blocks resolved to each var-tx depth (0 = one transform
2779/// over the whole block, 1 = its four halves), the fire count a gate prints
2780/// to see the split search reach its candidates at all.
2781static INTER_TX_SPLIT_HITS: [std::sync::atomic::AtomicUsize; 2] =
2782 [const { std::sync::atomic::AtomicUsize::new(0) }; 2];
2783
2784/// How many 32x32-and-below inter blocks each reference frame won, indexed by
2785/// `ref_frame` (`crate::mvstack::LAST_FRAME` = 1 .. `ALTREF_FRAME` = 7), the
2786/// fire count a gate prints to see an extra reference reach a block at all
2787/// ([[gate-blind-to-feature]]: a pyramid whose backward `ALTREF` is never
2788/// chosen is a pyramid that costs bytes and buys nothing).
2789static REF_FRAME_HITS: [std::sync::atomic::AtomicUsize; 8] =
2790 [const { std::sync::atomic::AtomicUsize::new(0) }; 8];
2791
2792/// Reads [`REF_FRAME_HITS`] and zeroes it.
2793#[cfg(test)]
2794pub(crate) fn take_ref_frame_hits() -> [usize; 8] {
2795 std::array::from_fn(|r| REF_FRAME_HITS[r].swap(0, std::sync::atomic::Ordering::Relaxed))
2796}
2797
2798/// Reads [`INTER_TX_SPLIT_HITS`] and zeroes it.
2799#[cfg(test)]
2800pub(crate) fn take_inter_tx_split_hits() -> [usize; 2] {
2801 std::array::from_fn(|d| INTER_TX_SPLIT_HITS[d].swap(0, std::sync::atomic::Ordering::Relaxed))
2802}
2803
2804/// What the `txfm_split` symbols of one inter block cost at `depth`, priced
2805/// off the neighbour-free context row the way [`tx_depth_bits`] is: depth 0
2806/// is one flag, depth 1 is a split root plus one unsplit flag per child
2807/// (decode.rs `read_var_tx_size` stops symbol-free only at `MAX_VARTX_DEPTH`
2808/// or a 4x4 sub-size).
2809fn txfm_split_bits(side: usize, depth: usize) -> f64 {
2810 let max_tx = side.min(64);
2811 let ctx = |tx: usize| {
2812 crate::decode::txfm_partition_ctx_rect(
2813 crate::decode::TXFM_CTX_INIT,
2814 crate::decode::TXFM_CTX_INIT,
2815 side,
2816 tx,
2817 tx,
2818 )
2819 };
2820 if depth == 0 {
2821 return symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 0);
2822 }
2823 symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx)], 1)
2824 + 4.0 * symbol_bits(&cdf::TXFM_PARTITION[ctx(max_tx / 2)], 0)
2825}
2826
2827/// The inter block's own var-tx decision, once its motion vector is settled:
2828/// its residual as ONE transform over the whole block, or as the four
2829/// transforms of half the side the tree's first halving names. The prediction
2830/// is the same motion compensation either way, so the split trial
2831/// re-transforms the identical residual in four pieces -- it wins where four
2832/// small transforms carry a locally varying residual cheaper than one big
2833/// one. Commits the winner into `luma` and hands back its block-coordinate
2834/// levels, the depth the writer codes and the cost the winner adds to (or
2835/// takes off) the caller's already-computed flat cost.
2836///
2837/// Only for a block wholly inside the frame: past the true edge the reader's
2838/// var-tx recursion skips the units that fall outside
2839/// (decode.rs `read_var_tx_size`'s `max_w_mi`/`max_h_mi` guard), which would
2840/// leave the residual units this writes unpaired.
2841#[allow(clippy::too_many_arguments)]
2842fn commit_inter_luma(
2843 luma: &mut Plane,
2844 (x, y): (usize, usize),
2845 side: usize,
2846 mv: (i32, i32),
2847 reference: (&[u16], usize, usize, usize),
2848 search: &Search,
2849 flat: &Trial,
2850 skip: bool, fctx: &crate::decode::FrameCtx,
2851) -> (Vec<i32>, u8, f64) {
2852 let eligible = tx_select()
2853 && tx_select_inter()
2854 && !skip
2855 && side >= 16
2856 && x + side <= luma.true_width
2857 && y + side <= luma.true_height;
2858 if !eligible {
2859 luma.commit(x, y, side, flat);
2860 return (flat.levels.clone(), 0, 0.0);
2861 }
2862 let tx = side / 2;
2863 let set = if tx >= 16 { TxbSet::Luma16Inter } else { TxbSet::Luma8Inter };
2864 let mut levels = vec![0i32; side * side];
2865 let (mut sse, mut bits) = (0.0, 0.0);
2866 let mut units = Vec::with_capacity(4);
2867 // The split units are smaller than their block, so their `txb_skip`
2868 // context is the neighbour magnitude table ([`Plane::coef_ctx`]) -- and
2869 // each unit's own commit publishes what the next one reads, coding order.
2870 luma.ctx.tu_split = true;
2871 for tu_row in 0..2 {
2872 for tu_col in 0..2 {
2873 let (tu_x, tu_y) = (x + tu_col * tx, y + tu_row * tx);
2874 let trial = mc_trial(
2875 luma, tu_x, tu_y, tx, mv, true, reference.0, reference.1, reference.2,
2876 reference.3, false, search.base_q_idx, search.deadzone, set, fctx,
2877 );
2878 sse += trial.sse;
2879 bits += trial.bits;
2880 for row in 0..tx {
2881 levels[(tu_row * tx + row) * side + tu_col * tx..][..tx]
2882 .copy_from_slice(&trial.levels[row * tx..][..tx]);
2883 }
2884 units.push((tu_x, tu_y, trial));
2885 }
2886 }
2887 luma.ctx.tu_split = false;
2888 let split_cost = sse + search.lambda * (bits + txfm_split_bits(side, 1));
2889 let flat_cost = flat.sse + search.lambda * (flat.bits + txfm_split_bits(side, 0));
2890 if split_cost < flat_cost {
2891 for (tu_x, tu_y, trial) in &units {
2892 luma.commit(*tu_x, *tu_y, tx, trial);
2893 }
2894 INTER_TX_SPLIT_HITS[1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2895 return (levels, 1, split_cost - flat_cost);
2896 }
2897 INTER_TX_SPLIT_HITS[0].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2898 luma.commit(x, y, side, flat);
2899 (flat.levels.clone(), 0, 0.0)
2900}
2901
2902/// The largest distinct-colour count a block may hold and still be offered a
2903/// palette candidate at all: past it the k-means quantisation costs more
2904/// error than the map saves rate, and every trial is wasted wall.
2905///
2906/// Swept on the gate's own screen capture (lane-av1pal2, the
2907/// `unswept-decision-constants` class): 32 (the value this lane inherited)
2908/// finds 515 palette blocks and scores +66.4%/+10.3% vs libaom/rav1e, 64
2909/// finds 1264 and scores +57.1%/+3.2%, 128 finds 1102 and scores
2910/// +56.9%/+2.3%, and 256 is byte-identical to 128 -- above 128 the bound
2911/// binds on nothing this content holds. 128 ships: best BD against both
2912/// references and no wall cost at all (6.1s, the same as at 32, because the
2913/// blocks it newly admits are ones the RD then keeps).
2914/// `EC_AV1_PAL_MAXCOLORS`.
2915fn palette_max_colors() -> usize {
2916 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
2917 *N.get_or_init(|| {
2918 std::env::var("EC_AV1_PAL_MAXCOLORS")
2919 .ok()
2920 .and_then(|v| v.parse().ok())
2921 .unwrap_or(128)
2922 })
2923}
2924
2925/// The palettes worth trying for one block's luma, in the shape libaom's
2926/// `av1_k_means` picks them: a block holding at most `PALETTE_MAX_SIZE`
2927/// distinct colours takes them ALL (the prediction is then exact and the
2928/// residual empty), and a busier one is quantised to 8 and to 4 colours by a
2929/// one-dimensional Lloyd iteration seeded evenly across its range -- both
2930/// offered, because which wins is an RD question the caller answers.
2931/// `block` is `side*side` source samples, row-major.
2932fn palette_candidates(block: &[u8]) -> Vec<crate::tile::PaletteY> {
2933 let mut histogram = [0u32; 256];
2934 for &v in block {
2935 histogram[usize::from(v)] += 1;
2936 }
2937 let present: Vec<u16> = (0..256u16).filter(|&v| histogram[usize::from(v)] > 0).collect();
2938 if present.len() < 2 {
2939 return Vec::new();
2940 }
2941 let exact = |colors: &[u16]| -> crate::tile::PaletteY {
2942 let mut base = [0u16; 8];
2943 base[..colors.len()].copy_from_slice(colors);
2944 let map = block
2945 .iter()
2946 .map(|&v| {
2947 colors
2948 .iter()
2949 .enumerate()
2950 .min_by_key(|&(_, &c)| (i32::from(c) - i32::from(v)).abs())
2951 .map(|(i, _)| i as u8)
2952 .expect("a palette holds at least two colours")
2953 })
2954 .collect();
2955 crate::tile::PaletteY { size: colors.len() as u8, colors: base, map }
2956 };
2957 if present.len() <= 8 {
2958 return vec![exact(&present)];
2959 }
2960 if present.len() > palette_max_colors() {
2961 return Vec::new();
2962 }
2963 let (lo, hi) = (
2964 i32::from(present[0]),
2965 i32::from(present[present.len() - 1]),
2966 );
2967 let mut out = Vec::with_capacity(2);
2968 for n in [8usize, 4] {
2969 // Even seeding across the block's own range, then four Lloyd passes
2970 // over the histogram (256 bins, not `side*side` pixels).
2971 let mut centres: Vec<f64> = (0..n)
2972 .map(|i| f64::from(lo) + f64::from(hi - lo) * (i as f64 + 0.5) / n as f64)
2973 .collect();
2974 for _ in 0..4 {
2975 let mut sums = vec![0f64; n];
2976 let mut counts = vec![0u32; n];
2977 for (v, &count) in histogram.iter().enumerate() {
2978 if count == 0 {
2979 continue;
2980 }
2981 let k = (0..n)
2982 .min_by(|&a, &b| {
2983 (centres[a] - v as f64)
2984 .abs()
2985 .total_cmp(&(centres[b] - v as f64).abs())
2986 })
2987 .expect("n >= 2");
2988 sums[k] += (v as u32 * count) as f64;
2989 counts[k] += count;
2990 }
2991 for k in 0..n {
2992 if counts[k] > 0 {
2993 centres[k] = sums[k] / f64::from(counts[k]);
2994 }
2995 }
2996 }
2997 let mut colors: Vec<u16> = centres
2998 .iter()
2999 .map(|&c| c.round().clamp(0.0, 255.0) as u16)
3000 .collect();
3001 colors.sort_unstable();
3002 colors.dedup();
3003 if colors.len() >= 2 {
3004 out.push(exact(&colors));
3005 }
3006 }
3007 out
3008}
3009
3010#[allow(clippy::too_many_arguments)]
3011// ---------------------------------------------------------------------------
3012// lane-av1ibc: intra block copy (spec 5.11.13 `use_intrabc`, 7.11.4 DV
3013// validity). A key frame that detected screen content and finds enough exact
3014// repeats in its own source sets `allow_intrabc`, which the spec forces every
3015// in-loop filter OFF for (frame.rs:194/210/252/272) -- so the bit only earns
3016// its place when the copied blocks pay back the deblock/CDEF/LR the frame
3017// gives up. `EC_AV1_INTRABC=0` turns the whole arm off.
3018// ---------------------------------------------------------------------------
3019
3020/// Whether intra block copy is offered at all. **Off by default** --
3021/// `EC_AV1_INTRABC=1` turns it on. The syntax is complete and proven against
3022/// ffmpeg (`a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly`),
3023/// but on the gate's real screen capture it MEASURED WORSE: setting
3024/// `allow_intrabc` costs the key frame its deblocking, CDEF and loop
3025/// restoration (spec 5.9.11/5.9.19/5.9.20) and the copied blocks do not pay
3026/// that back -- screen BD +59.1/+5.1 against the +54.5/+1.1 base (lane-av1ibc,
3027/// `probe_intrabc_key_frame` has the per-key-frame table). Also off on a frame
3028/// that detected no screen content.
3029fn intrabc_enabled() -> bool {
3030 if let Some(forced) = INTRABC_FORCE.with(std::cell::Cell::get) {
3031 return forced;
3032 }
3033 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
3034 *ON.get_or_init(|| std::env::var("EC_AV1_INTRABC").ok().as_deref() == Some("1"))
3035}
3036
3037thread_local! {
3038 /// Overrides [`intrabc_enabled`] for the calling thread -- the ablation
3039 /// probe runs both arms in one process, and the suite is one process, so
3040 /// an environment variable cannot separate them (same reason
3041 /// [`SCREEN_FORCE`] exists).
3042 static INTRABC_FORCE: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
3043}
3044
3045#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3046pub(crate) fn force_intrabc(value: Option<bool>) {
3047 INTRABC_FORCE.with(|c| c.set(value));
3048}
3049
3050/// How many of a screen frame's 16x16 blocks must have an exact repeat
3051/// somewhere else in the source before `allow_intrabc` is worth the in-loop
3052/// filters it costs, in percent (`EC_AV1_INTRABC_PCT`). Unswept-decision-
3053/// constant class: `probe_intrabc_threshold` measures the arm at several
3054/// values.
3055fn intrabc_pct() -> usize {
3056 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
3057 *N.get_or_init(|| {
3058 std::env::var("EC_AV1_INTRABC_PCT")
3059 .ok()
3060 .and_then(|v| v.parse().ok())
3061 .unwrap_or(10)
3062 })
3063}
3064
3065/// The pixel grid intrabc source positions are hashed on
3066/// (`EC_AV1_INTRABC_STEP`): every DV this encoder writes is a multiple of it,
3067/// which keeps the block-hash table (and so the search) linear in the frame
3068/// at a `step`-th of the density. It must stay EVEN -- a chroma plane copies
3069/// at `dv / 2` full pel, so an odd DV would land half-pel and need the
3070/// bilinear interpolation decode.rs applies but this encoder does not.
3071fn intrabc_step() -> usize {
3072 static N: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
3073 *N.get_or_init(|| {
3074 let n: usize = std::env::var("EC_AV1_INTRABC_STEP")
3075 .ok()
3076 .and_then(|v| v.parse().ok())
3077 .unwrap_or(4);
3078 if n % 2 == 0 { n.max(2) } else { 4 }
3079 })
3080}
3081
3082/// The side of the luma square the block-hash table is keyed on.
3083const IBC_HASH: usize = 16;
3084
3085/// libaom `INTRABC_DELAY_PIXELS / 64` -- how many 64x64 superblocks behind
3086/// the current one the source's bottom-right corner must already be.
3087const INTRABC_DELAY_SB64: i32 = 4;
3088
3089/// FNV-1a over one `IBC_HASH`-square of `plane` at `(x, y)`.
3090fn ibc_hash(plane: &[u8], width: usize, x: usize, y: usize) -> u64 {
3091 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
3092 for row in 0..IBC_HASH {
3093 let base = (y + row) * width + x;
3094 for &v in &plane[base..base + IBC_HASH] {
3095 h ^= u64::from(v);
3096 h = h.wrapping_mul(0x100_0000_01b3);
3097 }
3098 }
3099 h
3100}
3101
3102/// Every `intrabc_step()`-aligned position of `plane` inside
3103/// `(x0, y0)..(x1, y1)`, keyed by [`ibc_hash`].
3104fn ibc_index(
3105 table: &mut std::collections::HashMap<u64, Vec<(u32, u32)>>,
3106 plane: &[u8],
3107 width: usize,
3108 (x0, y0): (usize, usize),
3109 (x1, y1): (usize, usize),
3110) {
3111 let step = intrabc_step();
3112 if x1 < x0 + IBC_HASH || y1 < y0 + IBC_HASH {
3113 return;
3114 }
3115 let mut y = y0.next_multiple_of(step);
3116 while y + IBC_HASH <= y1 {
3117 let mut x = x0.next_multiple_of(step);
3118 while x + IBC_HASH <= x1 {
3119 table
3120 .entry(ibc_hash(plane, width, x, y))
3121 .or_default()
3122 .push((x as u32, y as u32));
3123 x += step;
3124 }
3125 y += step;
3126 }
3127}
3128
3129/// Whether `screen`-detected source `y` repeats itself enough to be worth
3130/// `allow_intrabc` -- the share of its 16-aligned 16x16 blocks whose exact
3131/// content appears at some other position, against [`intrabc_pct`]. Returns
3132/// the share as well, for the gate's own print.
3133fn intrabc_worth_it(y: &[u8], width: usize, true_width: usize, true_height: usize) -> (bool, f64) {
3134 if true_width < 4 * 64 || true_height < 2 * 64 {
3135 return (false, 0.0);
3136 }
3137 let mut table = std::collections::HashMap::new();
3138 ibc_index(&mut table, y, width, (0, 0), (true_width, true_height));
3139 let (mut total, mut matched) = (0usize, 0usize);
3140 let mut by = 0;
3141 while by + IBC_HASH <= true_height {
3142 let mut bx = 0;
3143 while bx + IBC_HASH <= true_width {
3144 total += 1;
3145 if let Some(hits) = table.get(&ibc_hash(y, width, bx, by)) {
3146 if hits.iter().any(|&(hx, hy)| (hx as usize, hy as usize) != (bx, by)) {
3147 matched += 1;
3148 }
3149 }
3150 bx += IBC_HASH;
3151 }
3152 by += IBC_HASH;
3153 }
3154 let share = if total == 0 { 0.0 } else { matched as f64 / total as f64 };
3155 (share * 100.0 >= intrabc_pct() as f64, share)
3156}
3157
3158/// One tile's intrabc search state: a block-hash table over the part of the
3159/// tile's own reconstruction that is already final (whole superblock rows --
3160/// the in-loop filters are off on this frame, so a coded superblock row never
3161/// changes again), plus the last DV chosen, which the RD price uses as its
3162/// predictor estimate.
3163struct Ibc {
3164 /// Keyed on the SOURCE, exactly as libaom's `av1_intrabc_hash` is: the
3165 /// source repeats exactly where a lossily coded reconstruction only
3166 /// nearly does, so an exact-match table over the reconstruction finds
3167 /// almost nothing. The candidate is then SCORED against the
3168 /// reconstruction ([`ibc_sse`]), which is what a decoder will copy.
3169 table: std::collections::HashMap<u64, Vec<(u32, u32)>>,
3170 /// The tile's own luma rect, in samples.
3171 tile: (usize, usize, usize, usize),
3172 /// The DV the previous intrabc block of this tile took -- the *estimate*
3173 /// of decode.rs `read_intrabc_dv`'s predictor the RD price is taken
3174 /// against. The writer computes the true predictor off its own mi grid
3175 /// (`crate::tile::intrabc_dv_pred`); a wrong estimate here can only cost
3176 /// a slightly mispriced candidate, never a wrong bitstream.
3177 last_dv: Option<(i32, i32)>,
3178 /// How many blocks took intrabc, and how many hash lookups found at least
3179 /// one valid candidate -- the gate's own fire counts.
3180 hits: usize,
3181 lookups: usize,
3182 found: usize,
3183}
3184
3185impl Ibc {
3186 fn new(tile: (usize, usize, usize, usize), source: &[u8], width: usize) -> Self {
3187 let mut table = std::collections::HashMap::new();
3188 ibc_index(&mut table, source, width, (tile.0, tile.1), (tile.2, tile.3));
3189 Self {
3190 table,
3191 tile,
3192 last_dv: None,
3193 hits: 0,
3194 lookups: 0,
3195 found: 0,
3196 }
3197 }
3198
3199 /// libaom `av1_is_dv_valid` for a `w`x`h` block at `(x, y)` under `dv`
3200 /// (1/8 pel), with this lane's own extra restriction on top: the source
3201 /// must lie entirely in a COMPLETED superblock row, which is exactly the
3202 /// region [`Self::fill_to`] indexes and a strict subset of what the spec
3203 /// allows. corner-cut, ceiling named: same-superblock-row sources (the
3204 /// wavefront's own diagonal) are legal and not searched; the upgrade path
3205 /// is to index the current row's finished superblocks too.
3206 fn dv_valid(&self, x: usize, y: usize, w: usize, h: usize, dv: (i32, i32)) -> bool {
3207 let (dr, dc) = (dv.0 / 8, dv.1 / 8);
3208 if dv.0 % 8 != 0 || dv.1 % 8 != 0 || dr % 2 != 0 || dc % 2 != 0 {
3209 return false;
3210 }
3211 let (tx0, ty0, tx1, ty1) = (
3212 self.tile.0 as i32,
3213 self.tile.1 as i32,
3214 self.tile.2 as i32,
3215 self.tile.3 as i32,
3216 );
3217 let (sx, sy) = (x as i32 + dc, y as i32 + dr);
3218 let (w, h) = (w as i32, h as i32);
3219 if sx < tx0 || sy < ty0 || sx + w > tx1 || sy + h > ty1 {
3220 return false;
3221 }
3222 let active_sb_row = (y as i32 - ty0) >> 6;
3223 let active_sb_col = (x as i32 - tx0) >> 6;
3224 let src_sb_row = (sy + h - 1 - ty0) >> 6;
3225 let src_sb_col = (sx + w - 1 - tx0) >> 6;
3226 // This lane's own restriction (see the doc comment).
3227 if src_sb_row >= active_sb_row {
3228 return false;
3229 }
3230 let total = ((tx1 - tx0 - 1) >> 6) + 1;
3231 if src_sb_row * total + src_sb_col >= active_sb_row * total + active_sb_col - INTRABC_DELAY_SB64
3232 {
3233 return false;
3234 }
3235 // libaom's wavefront: only the top-left cone of the frame is legal.
3236 let wf = (1 + INTRABC_DELAY_SB64) * (active_sb_row - src_sb_row);
3237 src_sb_col < active_sb_col - INTRABC_DELAY_SB64 + wf
3238 }
3239}
3240
3241/// How many block searches ran, how many found at least one VALID candidate,
3242/// and how many won on rate-distortion -- the hash hit rate a gate prints
3243/// (class `gate-blind-to-feature`: "the search ran" and "the search found
3244/// something" and "the block took it" are three different claims).
3245static IBC_SEARCH: [std::sync::atomic::AtomicUsize; 3] =
3246 [const { std::sync::atomic::AtomicUsize::new(0) }; 3];
3247
3248impl Drop for Ibc {
3249 fn drop(&mut self) {
3250 for (slot, n) in [self.lookups, self.found, self.hits].into_iter().enumerate() {
3251 IBC_SEARCH[slot].fetch_add(n, std::sync::atomic::Ordering::Relaxed);
3252 }
3253 }
3254}
3255
3256/// Reads [`IBC_SEARCH`] and zeroes it, so a gate can attribute the counts to
3257/// its own encode.
3258#[allow(dead_code)] // read only from the `#[cfg(test)]` gates
3259pub(crate) fn take_intrabc_search() -> [usize; 3] {
3260 std::array::from_fn(|i| IBC_SEARCH[i].swap(0, std::sync::atomic::Ordering::Relaxed))
3261}
3262
3263/// [`crate::tile::write_dv_component`]'s static price -- the same shape as
3264/// [`mv_component_bits`] without the `mv_fr` symbol, which `force_integer_mv`
3265/// infers rather than codes.
3266fn dv_component_bits(diff: i32) -> f64 {
3267 let z = diff.unsigned_abs() as i32 - 1;
3268 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
3269 let class = mv_class_of(z);
3270 bits += symbol_bits(&cdf::MV_CLASS, class);
3271 let local = z - mv_class_base(class);
3272 if class == 0 {
3273 bits += symbol_bits(&cdf::MV_CLASS0_BIT, ((local >> 3) & 1) as usize);
3274 } else {
3275 let d = local >> 3;
3276 for i in 0..class {
3277 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
3278 }
3279 }
3280 bits
3281}
3282
3283/// What one block vector costs against `pred`, plus the `skip` and
3284/// `use_intrabc` flags the block carries and the ordinary intra block does
3285/// not pay in this currency.
3286fn dv_bits(dv: (i32, i32), pred: (i32, i32)) -> f64 {
3287 let diff = (dv.0 - pred.0, dv.1 - pred.1);
3288 let joint = match (diff.0 != 0, diff.1 != 0) {
3289 (false, false) => 0,
3290 (false, true) => 1,
3291 (true, false) => 2,
3292 (true, true) => 3,
3293 };
3294 let mut bits = symbol_bits(&cdf::MV_JOINT, joint) + 2.0;
3295 if diff.0 != 0 {
3296 bits += dv_component_bits(diff.0);
3297 }
3298 if diff.1 != 0 {
3299 bits += dv_component_bits(diff.1);
3300 }
3301 bits
3302}
3303
3304/// The squared error of copying the `side`-square block at `(sx, sy)` of each
3305/// plane's reconstruction onto the source block at `(x, y)`, luma and both
3306/// chroma planes together -- what an intrabc block's whole (residual-free)
3307/// distortion is.
3308fn ibc_sse(
3309 luma: &Plane,
3310 chroma: &[Plane; 2],
3311 (x, y): (usize, usize),
3312 (sx, sy): (usize, usize),
3313 side: usize,
3314) -> f64 {
3315 let mut sse = 0.0f64;
3316 for row in 0..side {
3317 let src = &luma.source[(y + row) * luma.width + x..][..side];
3318 let rec = &luma.reconstruction[(sy + row) * luma.width + sx..][..side];
3319 for (&s, &r) in src.iter().zip(rec) {
3320 let d = f64::from(i32::from(s) - i32::from(r));
3321 sse += d * d;
3322 }
3323 }
3324 let half = side / 2;
3325 for plane in chroma {
3326 for row in 0..half {
3327 let src = &plane.source[(y / 2 + row) * plane.width + x / 2..][..half];
3328 let rec = &plane.reconstruction[(sy / 2 + row) * plane.width + sx / 2..][..half];
3329 for (&s, &r) in src.iter().zip(rec) {
3330 let d = f64::from(i32::from(s) - i32::from(r));
3331 sse += d * d;
3332 }
3333 }
3334 }
3335 sse
3336}
3337
3338/// Copies the `side`-square block at `(sx, sy)` of each plane's
3339/// reconstruction onto `(x, y)` -- an intrabc block's whole reconstruction,
3340/// since it carries no residual (`skip`). Full-pel in both planes by
3341/// construction ([`intrabc_step`] keeps every DV even), which is what makes
3342/// this a plain copy where decode.rs runs the bilinear kernel over the same
3343/// samples.
3344fn ibc_commit(
3345 luma: &mut Plane,
3346 chroma: &mut [Plane; 2],
3347 (x, y): (usize, usize),
3348 (sx, sy): (usize, usize),
3349 side: usize,
3350) {
3351 for row in 0..side {
3352 let from = (sy + row) * luma.width + sx;
3353 let to = (y + row) * luma.width + x;
3354 let copied: Vec<u8> = luma.reconstruction[from..from + side].to_vec();
3355 luma.reconstruction[to..to + side].copy_from_slice(&copied);
3356 }
3357 let half = side / 2;
3358 for plane in chroma {
3359 for row in 0..half {
3360 let from = (sy / 2 + row) * plane.width + sx / 2;
3361 let to = (y / 2 + row) * plane.width + x / 2;
3362 let copied: Vec<u8> = plane.reconstruction[from..from + half].to_vec();
3363 plane.reconstruction[to..to + half].copy_from_slice(&copied);
3364 }
3365 plane.commit_ctx_zero(x / 2, y / 2, half);
3366 }
3367 luma.commit_ctx_zero(x, y, side);
3368}
3369
3370/// Searches this block's own DV: every hash-table position whose 16x16 luma
3371/// square equals the block's source square, plus the previous block's DV as a
3372/// local fallback, scored by [`ibc_sse`] against the DV's own price. Returns
3373/// the winning `(dv, cost)`, or `None` when nothing valid was found.
3374fn ibc_search(
3375 ibc: &mut Ibc,
3376 luma: &Plane,
3377 chroma: &[Plane; 2],
3378 (x, y): (usize, usize),
3379 side: usize,
3380 lambda: f64,
3381) -> Option<((i32, i32), f64, (usize, usize))> {
3382 let pred = ibc.last_dv.unwrap_or((0, -(64 + 256) * 8));
3383 let mut best: Option<((i32, i32), f64, (usize, usize))> = None;
3384 let consider = |ibc: &Ibc, sx: usize, sy: usize, best: &mut Option<((i32, i32), f64, (usize, usize))>| {
3385 let dv = (
3386 (sy as i32 - y as i32) * 8,
3387 (sx as i32 - x as i32) * 8,
3388 );
3389 if !ibc.dv_valid(x, y, side, side, dv) {
3390 return;
3391 }
3392 let cost = ibc_sse(luma, chroma, (x, y), (sx, sy), side) + lambda * dv_bits(dv, pred);
3393 if best.as_ref().is_none_or(|b| cost < b.1) {
3394 *best = Some((dv, cost, (sx, sy)));
3395 }
3396 };
3397 ibc.lookups += 1;
3398 let key = ibc_hash(luma.source, luma.width, x, y);
3399 // The table is filled in raster order, so the entries BEFORE this block's
3400 // own position are exactly the already-coded ones -- and the nearest of
3401 // them costs the fewest DV bits. Walking backwards from the block's own
3402 // slot is what makes the search look up-and-left; taking the newest
3403 // entries outright only ever finds candidates below and to the right,
3404 // every one of which `dv_valid` rejects.
3405 let hits: Vec<(u32, u32)> = ibc
3406 .table
3407 .get(&key)
3408 .map(|h| {
3409 let end = h.partition_point(|&(hx, hy)| (hy, hx) < (y as u32, x as u32));
3410 h[..end].iter().rev().take(32).copied().collect()
3411 })
3412 .unwrap_or_default();
3413 for (hx, hy) in hits {
3414 consider(&*ibc, hx as usize, hy as usize, &mut best);
3415 }
3416 if let Some(dv) = ibc.last_dv {
3417 let (sx, sy) = (x as i32 + dv.1 / 8, y as i32 + dv.0 / 8);
3418 if sx >= 0 && sy >= 0 {
3419 consider(&*ibc, sx as usize, sy as usize, &mut best);
3420 }
3421 }
3422 if best.is_some() {
3423 ibc.found += 1;
3424 }
3425 best
3426}
3427
3428fn code_square(
3429 luma: &mut Plane,
3430 chroma: &mut [Plane; 2],
3431 (x, y): (usize, usize),
3432 side: usize,
3433 search: &Search,
3434 mode_bits: &[f64; 13],
3435 // The frame header's `tx_mode == TxMode::Select`: the block then searches
3436 // its own transform depth ([`Plane::code_tx_depth`]) instead of coding one
3437 // transform over its whole side.
3438 tx_select: bool,
3439 // This tile's intra block-copy state ([`Ibc`]), `None` on a frame whose
3440 // header did not set `allow_intrabc`.
3441 ibc: Option<&mut Ibc>, fctx: &crate::decode::FrameCtx,
3442) -> (BlockCoeffs, f64) {
3443 let (luma_set, chroma_set) = if side == BLOCK {
3444 (TxbSet::Luma32, TxbSet::Chroma16)
3445 } else if side == 8 {
3446 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
3447 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
3448 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
3449 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
3450 // (this branch is still unreached), so leaving `Chroma8` here would
3451 // silently wire the wrong table the moment one does; `Chroma4` is
3452 // what a real caller needs.
3453 (TxbSet::Luma8, TxbSet::Chroma4)
3454 } else {
3455 (TxbSet::Luma16, TxbSet::Chroma8)
3456 };
3457 let at = At {
3458 x,
3459 y,
3460 side,
3461 reach: Reach::of(side, x, y, luma.true_width, luma.true_height, fctx),
3462 set: luma_set,
3463 };
3464 let (mut luma_coeffs, mode, mut cost) = luma.search_block(at, search, mode_bits, fctx);
3465 // The depth search runs on the mode the whole-block transform picked --
3466 // libaom's own ordering, and the reason it costs one extra pass per depth
3467 // rather than one per (mode, depth) pair.
3468 let mut tx_depth = 0u8;
3469 if tx_select && max_tx_depth(side) > 0 {
3470 let mut best = (
3471 cost + search.lambda * tx_depth_bits(side, 0),
3472 0usize,
3473 luma.snapshot(x, y, side),
3474 luma_coeffs,
3475 );
3476 for depth in 1..=max_tx_depth(side) {
3477 let (levels, sse, bits) = luma.code_tx_depth(at, mode, depth, search, fctx);
3478 let cost_d = sse
3479 + search.lambda
3480 * (bits + mode_bits[usize::from(mode)] + tx_depth_bits(side, depth));
3481 if cost_d < best.0 {
3482 best = (cost_d, depth, luma.snapshot(x, y, side), coeffs(&levels, side));
3483 }
3484 }
3485 luma.restore(x, y, side, &best.2);
3486 cost = best.0;
3487 tx_depth = best.1 as u8;
3488 luma_coeffs = best.3;
3489 TX_DEPTH_HITS[best.1].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3490 }
3491 // The palette candidate is priced against the mode the luma search (and
3492 // its transform-depth search) already settled on, so a block only takes
3493 // one when it beats the best ordinary intra coding of the same pixels.
3494 // A palette block is `DC_PRED` with `tx_depth` 0 by construction: its
3495 // prediction is the colour map, not the DC of its neighbours.
3496 let mut mode = mode;
3497 let mut palette = None;
3498 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
3499 let source: Vec<u8> = (y..y + side)
3500 .flat_map(|row| luma.source[row * luma.width + x..][..side].to_vec())
3501 .collect();
3502 let kept = luma.snapshot(x, y, side);
3503 for pal in palette_candidates(&source) {
3504 let n = usize::from(pal.size);
3505 let prediction: Vec<u8> = pal
3506 .map
3507 .iter()
3508 .map(|&i| pal.colors[usize::from(i).min(n - 1)] as u8)
3509 .collect();
3510 let trial = luma.code_from_prediction(
3511 x,
3512 y,
3513 side,
3514 &prediction,
3515 false,
3516 search.base_q_idx,
3517 search.deadzone,
3518 luma_set,
3519 );
3520 let cost_p = trial.sse
3521 + search.lambda
3522 * (trial.bits
3523 + mode_bits[DC_PRED as usize]
3524 + crate::tile::palette_bits(&pal, side)
3525 + if tx_select { tx_depth_bits(side, 0) } else { 0.0 });
3526 if cost_p < cost {
3527 cost = cost_p;
3528 mode = DC_PRED as u8;
3529 tx_depth = 0;
3530 luma_coeffs = coeffs(&trial.levels, side);
3531 luma.commit(x, y, side, &trial);
3532 palette = Some(pal);
3533 }
3534 }
3535 if palette.is_none() {
3536 luma.restore(x, y, side, &kept);
3537 }
3538 }
3539
3540 // Chroma searches its own mode over [`CHROMA_MODES`], one symbol for both
3541 // planes; what it costs still counts towards the partition decision.
3542 let ([u, v], uv_mode, chroma_cost, palette_uv) =
3543 search_chroma(chroma, (x, y), side, chroma_set, search, mode, fctx);
3544 cost += chroma_cost;
3545
3546 // The intrabc arm is priced against the WHOLE block -- luma and both
3547 // chroma planes, residual-free -- so it is compared after the chroma
3548 // search has added its own cost, not against the luma decision alone.
3549 if let Some(ibc) = ibc {
3550 if let Some((dv, cost_ibc, src)) =
3551 ibc_search(ibc, luma, chroma, (x, y), side, search.lambda)
3552 {
3553 if cost_ibc < cost {
3554 ibc_commit(luma, chroma, (x, y), src, side);
3555 ibc.last_dv = Some(dv);
3556 ibc.hits += 1;
3557 return (
3558 BlockCoeffs {
3559 skip: true,
3560 dv: Some(dv),
3561 ..BlockCoeffs::default()
3562 },
3563 cost_ibc,
3564 );
3565 }
3566 }
3567 }
3568 (
3569 BlockCoeffs {
3570 u,
3571 v,
3572 luma: luma_coeffs,
3573 mode,
3574 uv_mode,
3575 tx_depth,
3576 palette,
3577 palette_uv,
3578 ..BlockCoeffs::default()
3579 },
3580 cost,
3581 )
3582}
3583
3584/// The chroma modes the search offers, and the only ones it may offer: each
3585/// predicts from the row directly above and the column directly to the left
3586/// and nothing further, so none of them needs the above-right/below-left
3587/// `Reach` a chroma block is coded with `Reach::none()` for. The eight
3588/// directional modes do read past that, and `UV_CFL_PRED` needs the luma
3589/// reconstruction and its own alpha syntax; both are left out here.
3590const CHROMA_MODES: [u8; 7] = [
3591 DC_PRED,
3592 V_PRED,
3593 H_PRED,
3594 SMOOTH_PRED,
3595 SMOOTH_V_PRED,
3596 SMOOTH_H_PRED,
3597 PAETH_PRED,
3598];
3599
3600/// The thirteen intra mode names, for the chroma fire count's print.
3601#[cfg(test)]
3602const UV_MODE_NAMES: [&str; 13] = [
3603 "DC", "V", "H", "D45", "D135", "D113", "D157", "D203", "D67", "SMOOTH", "SMOOTH_V",
3604 "SMOOTH_H", "PAETH",
3605];
3606
3607/// How many blocks each chroma mode has won, indexed by the mode itself --
3608/// the fire count that says whether the search below reaches its candidates
3609/// at all (the `gate-blind-to-feature` class), printed once per gate run.
3610static UV_MODE_HITS: [std::sync::atomic::AtomicUsize; 13] =
3611 [const { std::sync::atomic::AtomicUsize::new(0) }; 13];
3612
3613/// Reads [`UV_MODE_HITS`] and zeroes it, so a gate can attribute the counts
3614/// to its own encode.
3615#[cfg(test)]
3616pub(crate) fn take_uv_mode_hits() -> [usize; 13] {
3617 std::array::from_fn(|m| UV_MODE_HITS[m].swap(0, std::sync::atomic::Ordering::Relaxed))
3618}
3619
3620/// Searches both chroma planes over [`CHROMA_MODES`] under one shared mode --
3621/// `uv_mode` is a single symbol covering U and V -- and commits the cheapest.
3622/// Returns each plane's levels, the mode, and what the pair cost (squared
3623/// error plus lambda times bits, the same currency the luma search speaks).
3624///
3625/// The chroma symbol itself was already priced at `DC_PRED` by [`mode_bits`],
3626/// which is what the luma mode decision was taken against, so what a
3627/// candidate owes here is only the *difference* from that -- plus, for `V`/`H`
3628/// (directional, spec `read_intra_angle_info`), the zero `angle_delta_uv` the
3629/// writer then has to code.
3630#[allow(clippy::too_many_arguments)]
3631/// How many of [`CHROMA_MODES`] the chroma search runs a full trial pair on,
3632/// ranked by the SAD of their predictions summed over both planes (`DC_PRED`
3633/// always kept, the same rule [`prune_by_sad`] applies to luma). `None`
3634/// trials all seven, as before this lever.
3635///
3636/// The census (`EC_AV1_CENSUS=1`) is what justifies the lever: chroma was
3637/// the search's largest trial population by far -- seven modes times two
3638/// planes for every intra block, against 3.7 luma trials -- and the RD
3639/// winner sat at SAD rank 0 for 67-77% of blocks and inside the top three
3640/// for 88%. `EC_AV1_CHROMA_K` sweeps it in any build.
3641fn chroma_top_k() -> Option<usize> {
3642 static K: std::sync::OnceLock<Option<usize>> = std::sync::OnceLock::new();
3643 *K.get_or_init(|| match std::env::var("EC_AV1_CHROMA_K").ok() {
3644 Some(v) => v.parse::<usize>().ok().filter(|&k| k > 0),
3645 None => CHROMA_TOP_K,
3646 })
3647}
3648
3649/// [`chroma_top_k`]'s default. `None`: no `K` cleared the keep rule on the BD
3650/// gate. Swept over 2/3/4/5 (vs libaom, base +121.1/+146.1/+79.3):
3651/// K=2 is +122.3/+147.5/+79.8 for -7.0/-8.3/-7.9% wall, K=3 +121.4/+146.8/
3652/// +80.6 for -5.4/-5.2/-4.6%, K=4 +120.5/+145.2/+79.3 (BD-neutral or better)
3653/// for only -3.4% wall and -2.8% instructions, K=5 +122.0/+145.1/+80.0. The
3654/// BD swings by about a point in either direction as near-tie chroma modes
3655/// flip, which is the measurement's own sensitivity, not a trend: nothing
3656/// here buys >=5% wall at <=+0.3 BD, so the default stays unpruned.
3657const CHROMA_TOP_K: Option<usize> = None;
3658
3659fn search_chroma(
3660 chroma: &mut [Plane; 2],
3661 (x, y): (usize, usize),
3662 side: usize,
3663 set: TxbSet,
3664 search: &Search,
3665 luma_mode: u8,
3666 fctx: &crate::decode::FrameCtx,
3667) -> ([Vec<Coeff>; 2], u8, f64, Option<crate::tile::PaletteUv>) {
3668 let at = At {
3669 x: x / 2,
3670 y: y / 2,
3671 side: side / 2,
3672 reach: Reach::none(),
3673 set,
3674 };
3675 // The census's cheap proxy for a chroma mode: the SAD of its prediction
3676 // summed over both planes, ranked by the same rule the luma histogram
3677 // uses. Only built under `EC_AV1_CENSUS`.
3678 // The SAD of each mode's prediction, summed over both planes -- the
3679 // census's ranking rule, and what [`chroma_top_k`] prunes by.
3680 let sad_scores = |chroma: &[Plane; 2]| -> Vec<(f64, u8)> {
3681 let u = chroma[0].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
3682 let v = chroma[1].intra_scores(at, &CHROMA_MODES, &[0.0; 13], 0.0, fctx);
3683 u.iter()
3684 .zip(v.iter())
3685 .map(|(&(us, mode), &(vs, _))| (us + vs, mode))
3686 .collect()
3687 };
3688 let modes: Vec<u8> = match chroma_top_k() {
3689 Some(k) if k < CHROMA_MODES.len() => prune_by_sad(&CHROMA_MODES, sad_scores(chroma), k),
3690 _ => CHROMA_MODES.to_vec(),
3691 };
3692 let uv_cdf = &cdf::UV_MODE_CFL[usize::from(luma_mode)];
3693 let dc_bits = symbol_bits(uv_cdf, usize::from(DC_PRED));
3694 let ranking: Vec<(f64, u8)> = if census_on() {
3695 sad_scores(chroma)
3696 } else {
3697 Vec::new()
3698 };
3699 census_add(2, 1);
3700 census_add(3, modes.len());
3701 let mut best: Option<(f64, u8, Trial, Trial)> = None;
3702 for mode in modes {
3703 let mut bits = symbol_bits(uv_cdf, usize::from(mode)) - dc_bits;
3704 if (V_PRED..=D67_PRED).contains(&mode) {
3705 bits += symbol_bits(&cdf::ANGLE_DELTA[usize::from(mode - V_PRED)], 3);
3706 }
3707 let tx_type = crate::decode::default_intra_tx_type(mode);
3708 let u = chroma[0].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx);
3709 let v = chroma[1].trial_typed(at, mode, search.base_q_idx, search.deadzone, tx_type, fctx);
3710 let cost = u.sse + v.sse + search.lambda * (bits + u.bits + v.bits);
3711 if best.as_ref().is_none_or(|(b, ..)| cost < *b) {
3712 best = Some((cost, mode, u, v));
3713 }
3714 }
3715 let (mut cost, mut mode, mut u, mut v) = best.expect("CHROMA_MODES is not empty");
3716 // The chroma palette arm (spec 5.11.46's plane-1 half): one k-means over
3717 // U -- the same 1-D Lloyd [`palette_candidates`] runs for luma, which is
3718 // what keeps `u_colors` ascending and distinct the way
3719 // `read_palette_colors_uv`'s merge/delta reader needs -- and V taken as
3720 // each cluster's own mean, since the colour-index map is SHARED by the
3721 // two planes. Priced against the best ordinary chroma mode above, so a
3722 // block only takes one when it beats it; a palette block's chroma mode is
3723 // `UV_DC_PRED` by construction.
3724 let mut palette_uv = None;
3725 if search.screen && crate::decode::palette_bsize_ctx(side).is_some() {
3726 debug_assert_eq!(crate::tile::palette_uv_side(side), at.side);
3727 let plane_source = |p: &Plane| -> Vec<u8> {
3728 (at.y..at.y + at.side)
3729 .flat_map(|row| p.source[row * p.width + at.x..][..at.side].to_vec())
3730 .collect()
3731 };
3732 let (u_source, v_source) = (plane_source(&chroma[0]), plane_source(&chroma[1]));
3733 for pal in palette_candidates(&u_source) {
3734 let n = usize::from(pal.size);
3735 // V's base colour per cluster: the mean of the samples the shared
3736 // map assigns to it (an empty cluster cannot happen -- every
3737 // colour `palette_candidates` returns is some pixel's nearest).
3738 let mut sums = [0u32; 8];
3739 let mut counts = [0u32; 8];
3740 for (&i, &sample) in pal.map.iter().zip(v_source.iter()) {
3741 let k = usize::from(i).min(n - 1);
3742 sums[k] += u32::from(sample);
3743 counts[k] += 1;
3744 }
3745 let mut v_colors = [0u16; 8];
3746 for k in 0..n {
3747 v_colors[k] = if counts[k] > 0 {
3748 ((sums[k] + counts[k] / 2) / counts[k]) as u16
3749 } else {
3750 0
3751 };
3752 }
3753 let candidate = crate::tile::PaletteUv {
3754 size: pal.size,
3755 u_colors: pal.colors,
3756 v_colors,
3757 map: pal.map,
3758 };
3759 let predict = |colors: &[u16; 8]| -> Vec<u8> {
3760 candidate
3761 .map
3762 .iter()
3763 .map(|&i| colors[usize::from(i).min(n - 1)] as u8)
3764 .collect()
3765 };
3766 let (pu, pv) = (predict(&candidate.u_colors), predict(&candidate.v_colors));
3767 let u_trial = chroma[0].code_from_prediction(
3768 at.x, at.y, at.side, &pu, false, search.base_q_idx, search.deadzone, set,
3769 );
3770 let v_trial = chroma[1].code_from_prediction(
3771 at.x, at.y, at.side, &pv, false, search.base_q_idx, search.deadzone, set,
3772 );
3773 let cost_p = u_trial.sse
3774 + v_trial.sse
3775 + search.lambda
3776 * (u_trial.bits
3777 + v_trial.bits
3778 + crate::tile::palette_uv_bits(&candidate, side));
3779 if cost_p < cost {
3780 cost = cost_p;
3781 mode = DC_PRED;
3782 u = u_trial;
3783 v = v_trial;
3784 palette_uv = Some(candidate);
3785 }
3786 }
3787 }
3788 if census_on() {
3789 CHROMA_RANK[sad_rank(&ranking, mode).min(6)]
3790 .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3791 }
3792 UV_MODE_HITS[usize::from(mode)].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3793 chroma[0].commit(at.x, at.y, at.side, &u);
3794 chroma[1].commit(at.x, at.y, at.side, &v);
3795 (
3796 [coeffs(&u.levels, at.side), coeffs(&v.levels, at.side)],
3797 mode,
3798 cost,
3799 palette_uv,
3800 )
3801}
3802
3803/// Codes one leaf of a straddling quadrant as whichever costs least of intra
3804/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
3805/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
3806/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
3807/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
3808/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
3809/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
3810/// attempted here: these leaves only ever fill the sliver of real content a
3811/// true edge lands in the middle of a larger block, not a leaf worth a full
3812/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
3813/// (see `write_inter_frame_leaf`'s doc comment).
3814#[allow(clippy::too_many_arguments)]
3815/// The compound MV stack of each `LAST` + extra-reference pair at one leaf,
3816/// as [`code_square_inter`] wants them: empty on a frame that codes no
3817/// `reference_select`, or when the leaf compound candidates are switched off.
3818/// One helper because THREE leaf call sites need it -- the split quadrants
3819/// and, since lane-av1comp4, both straddling-edge sites, which used to pass
3820/// `&[]` and so coded no compound block anywhere along the frame's true edge.
3821#[allow(clippy::too_many_arguments)]
3822fn leaf_compound_stacks<'a>(
3823 grid: &MiGrid,
3824 mi_row: usize,
3825 mi_col: usize,
3826 bw4: usize,
3827 bh4: usize,
3828 mi_cols: usize,
3829 mi_rows: usize,
3830 reference_select: bool,
3831 golden: Option<&'a Picture>,
3832 altref: Option<&'a Picture>,
3833) -> Vec<(i8, &'a Picture, crate::mvstack::CompoundMvStack)> {
3834 if !(reference_select && leaf_compound()) {
3835 return Vec::new();
3836 }
3837 [
3838 (crate::mvstack::GOLDEN_FRAME, golden),
3839 (crate::mvstack::ALTREF_FRAME, altref),
3840 ]
3841 .into_iter()
3842 .filter_map(|(r, pic)| {
3843 pic.map(|p| {
3844 (
3845 r,
3846 p,
3847 crate::mvstack::find_mv_stack_compound(
3848 grid, mi_row, mi_col, bw4, bh4,
3849 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
3850 grid.sign_bias_table(), &[(0, 0); 7], None,
3851 ),
3852 )
3853 })
3854 })
3855 .collect()
3856}
3857
3858/// The OBMC prediction of one square single-reference block: this block's own
3859/// translation prediction (`mc::predict`) with every bordering above/left
3860/// neighbour blended into the overlap strips by the DECODER's own plan and
3861/// blend ([`crate::decode::obmc_plan`] / [`crate::decode::obmc_run`]), so what
3862/// the search prices is what a decoder reconstructs -- never a second
3863/// implementation of the blend. `None` when the block has no overlappable
3864/// neighbour at all (the writer would then code no `motion_mode` symbol) or
3865/// when the plan cannot be built (a neighbour naming a reference this encode
3866/// does not hold).
3867#[allow(clippy::too_many_arguments)]
3868fn obmc_prediction(
3869 grid: &MiGrid,
3870 (mi_row, mi_col): (usize, usize),
3871 (mi_rows, mi_cols): (usize, usize),
3872 (x, y): (usize, usize),
3873 side: usize,
3874 mv: (i32, i32),
3875 refs: &[Option<&Picture>; 8],
3876 // This block's OWN reference planes, luma then both chroma, each as
3877 // (samples, stride, true width, true height).
3878 ref_planes: [(&[u16], usize, usize, usize); 3],
3879 frame_width: usize,
3880 fctx: &crate::decode::FrameCtx,
3881) -> Option<[Vec<u8>; 3]> {
3882 let n4 = side / 4;
3883 if !crate::decode::has_overlappable_neighbour(grid, mi_row, mi_col, n4, n4, mi_cols, mi_rows) {
3884 return None;
3885 }
3886 let refpix = crate::decode::RefPix::ready(*refs);
3887 let plan = crate::decode::obmc_plan(
3888 grid,
3889 &[],
3890 &[],
3891 mi_row,
3892 mi_col,
3893 n4,
3894 n4,
3895 mi_rows,
3896 mi_cols,
3897 side,
3898 side,
3899 side,
3900 side / 2,
3901 x,
3902 y,
3903 x / 2,
3904 y / 2,
3905 &refpix,
3906 Some(mc::InterpFilterKind::Regular),
3907 frame_width,
3908 )
3909 .ok()?;
3910 let mut pred = [
3911 vec![0u16; side * side],
3912 vec![0u16; side * side / 4],
3913 vec![0u16; side * side / 4],
3914 ];
3915 for (i, r) in ref_planes.into_iter().enumerate() {
3916 let luma_plane = i == 0;
3917 let (px, py) = if luma_plane { (x, y) } else { (x / 2, y / 2) };
3918 let s = if luma_plane { side } else { side / 2 };
3919 mc::predict(
3920 r.0,
3921 r.1,
3922 r.2,
3923 r.3,
3924 mv_to_q4(px, mv.1, luma_plane),
3925 mv_to_q4(py, mv.0, luma_plane),
3926 s,
3927 s,
3928 &mut pred[i],
3929 fctx,
3930 );
3931 }
3932 let [mut py_buf, mut pu_buf, mut pv_buf] = pred;
3933 crate::decode::obmc_run(&plan, &refpix, &mut py_buf, &mut pu_buf, &mut pv_buf, fctx);
3934 let u8s = |b: &[u16]| b.iter().map(|&v| v as u8).collect::<Vec<u8>>();
3935 Some([u8s(&py_buf), u8s(&pu_buf), u8s(&pv_buf)])
3936}
3937
3938fn code_square_inter(
3939 luma: &mut Plane,
3940 chroma: &mut [Plane; 2],
3941 (x, y): (usize, usize),
3942 side: usize,
3943 search: &Search,
3944 mode_bits: &[f64; 13],
3945 reference: &Picture,
3946 stack: &MvStack,
3947 // The COMPOUND stack of each `LAST` + extra-reference pair, built at THIS
3948 // leaf's own `bw4`/`bh4` (empty on a frame that does not code
3949 // `reference_select`, and at the straddling call sites).
3950 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
3951 // lane-av1obmc2: the mi grid this leaf's neighbours were published into
3952 // (`record_mi`, in the writer's own coding order) and this leaf's place in
3953 // it -- what the OBMC candidate's eligibility walk and neighbour plan
3954 // read, the same state the tile writer reads when it codes the leaf's
3955 // `motion_mode` symbol.
3956 grid: &MiGrid,
3957 (mi_row, mi_col): (usize, usize),
3958 (mi_rows, mi_cols): (usize, usize),
3959 // Every picture an OBMC neighbour can name: a leaf only searches LAST,
3960 // but the neighbours it blends may be GOLDEN/ALTREF blocks.
3961 refs: &[Option<&Picture>; 8],
3962 fctx: &crate::decode::FrameCtx,
3963) -> (BlockCoeffs, f64) {
3964 let (intra_block, intra_cost) =
3965 code_square(
3966 luma,
3967 chroma,
3968 (x, y),
3969 side,
3970 search,
3971 mode_bits,
3972 tx_select() && tx_select_inter(),
3973 None,
3974 fctx,
3975 );
3976 let luma_set = if side == 8 {
3977 TxbSet::Luma8Inter
3978 } else {
3979 TxbSet::Luma16Inter
3980 };
3981 let chroma_set = if side == 8 {
3982 TxbSet::Chroma4
3983 } else {
3984 TxbSet::Chroma8
3985 };
3986
3987 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
3988 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
3989 let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0)
3990 + symbol_bits(&cdf::SINGLE_REF[0][2], 0)
3991 + symbol_bits(&cdf::SINGLE_REF[0][3], 0);
3992 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
3993 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
3994 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
3995
3996 let mv = stack.nearest_mv;
3997 let ref_luma = (
3998 &reference.y,
3999 reference.width,
4000 luma.true_width,
4001 luma.true_height,
4002 );
4003 let ref_u = (
4004 &reference.u,
4005 reference.width / 2,
4006 chroma[0].true_width,
4007 chroma[0].true_height,
4008 );
4009 let ref_v = (
4010 &reference.v,
4011 reference.width / 2,
4012 chroma[1].true_width,
4013 chroma[1].true_height,
4014 );
4015 let luma_trial = mc_trial(
4016 luma,
4017 x,
4018 y,
4019 side,
4020 mv,
4021 true,
4022 ref_luma.0,
4023 ref_luma.1,
4024 ref_luma.2,
4025 ref_luma.3,
4026 false,
4027 search.base_q_idx,
4028 search.deadzone,
4029 luma_set, fctx,
4030 );
4031 let u = mc_trial(
4032 &chroma[0],
4033 x / 2,
4034 y / 2,
4035 side / 2,
4036 mv,
4037 false,
4038 ref_u.0,
4039 ref_u.1,
4040 ref_u.2,
4041 ref_u.3,
4042 false,
4043 search.base_q_idx,
4044 search.deadzone,
4045 chroma_set, fctx,
4046 );
4047 let v = mc_trial(
4048 &chroma[1],
4049 x / 2,
4050 y / 2,
4051 side / 2,
4052 mv,
4053 false,
4054 ref_v.0,
4055 ref_v.1,
4056 ref_v.2,
4057 ref_v.3,
4058 false,
4059 search.base_q_idx,
4060 search.deadzone,
4061 chroma_set, fctx,
4062 );
4063 let skip = luma_trial.levels.iter().all(|&l| l == 0)
4064 && u.levels.iter().all(|&l| l == 0)
4065 && v.levels.iter().all(|&l| l == 0);
4066 let inter_cost = luma_trial.sse
4067 + u.sse
4068 + v.sse
4069 + search.lambda
4070 * (skip_bits(skip)
4071 + intra_inter_bits(true)
4072 + single_ref_bits
4073 + mode_bits_inter
4074 + if skip {
4075 0.0
4076 } else {
4077 luma_trial.bits + u.bits + v.bits
4078 });
4079
4080 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
4081 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
4082 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
4083 // scan's own coverage already reached as far) but a real gap at 4-mi
4084 // leaf geometry. r3 ported the extended scan and, while proving it a
4085 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
4086 // `mvstack.rs`), found and fixed a second bug the extended scan's
4087 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
4088 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
4089 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
4090 // regardless of whether it also casts a ref-frame-matching vote) --
4091 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
4092 // branches), which is what made 8-mi geometry a true no-op instead of
4093 // one that only held when every neighbour happened to be inter.
4094 // A motion search of this leaf's own (lane-av1rd2): before it, a leaf
4095 // only ever took the stack's NEARESTMV candidate or went intra, so a
4096 // 32x32 block splitting because its four quarters MOVE differently could
4097 // not code the movement it split for. Same candidate `search_inter_block`
4098 // prices for a whole block -- `motion::search` from `pred_mv`, rounded to
4099 // a vector the residual syntax can name -- at this leaf's own side.
4100 let mut best: (f64, Option<(Trial, Trial, Trial, bool, InterInfo)>) = (inter_cost, None);
4101 // The `NEARESTMV` candidate `inter_cost` prices, named once so the OBMC
4102 // re-price below can hand it back as the winner's own mode info.
4103 let nearest_info = InterInfo {
4104 ref1: None,
4105 mv1: (0, 0),
4106 ref_frame: crate::mvstack::LAST_FRAME,
4107 mode: InterMode::NearestMv,
4108 mv,
4109 ref_mv_idx: 0,
4110 };
4111 // What the current SINGLE-REFERENCE winner pays in mode/reference/mv
4112 // syntax, apart from its residual: the OBMC candidate re-prices the same
4113 // syntax against a different prediction, so both sides of that comparison
4114 // carry it.
4115 let mut single_syntax = intra_inter_bits(true) + single_ref_bits + mode_bits_inter;
4116 // This leaf's own `NEWMV` vector, kept whether or not it won the
4117 // single-reference comparison: it seeds the compound half-new candidate
4118 // below, exactly as `search_inter_block` seeds its own from the searches
4119 // it already ran.
4120 let mut searched_new: Option<(i32, i32)> = None;
4121 // What that search cost, kept for the second reference's own early-out
4122 // below (`None` when this leaf ran no search at all).
4123 let mut searched_new_cost: Option<f64> = None;
4124 let source_block = luma.source_block(x, y, side);
4125 if leaf_new_mv() {
4126 let (seeds, seed_n) = mv_seeds(stack);
4127 let found = motion::search(
4128 ref_luma.0,
4129 ref_luma.1,
4130 ref_luma.2,
4131 ref_luma.3,
4132 &source_block,
4133 x,
4134 y,
4135 side,
4136 side,
4137 stack.pred_mv,
4138 &seeds[..seed_n],
4139 search.lambda, fctx,
4140 1,
4141 );
4142 let new_mv = round_to_valid_mv(found.mv, stack.pred_mv);
4143 searched_new_cost = Some(found.cost);
4144 if let Some(mv_bits) = mv_residual_bits(new_mv, stack.pred_mv) {
4145 searched_new = Some(new_mv);
4146 // Same reuse as `search_inter_block`: a NEWMV equal to the
4147 // stack's NEARESTMV is the same three trials, already run above.
4148 let (luma_new, u_new, v_new) = if new_mv == mv {
4149 (luma_trial.clone(), u.clone(), v.clone())
4150 } else {
4151 (
4152 mc_trial(
4153 luma, x, y, side, new_mv, true, ref_luma.0, ref_luma.1, ref_luma.2,
4154 ref_luma.3, false, search.base_q_idx, search.deadzone, luma_set, fctx,
4155 ),
4156 mc_trial(
4157 &chroma[0], x / 2, y / 2, side / 2, new_mv, false, ref_u.0, ref_u.1,
4158 ref_u.2, ref_u.3, false, search.base_q_idx, search.deadzone, chroma_set,
4159 fctx,
4160 ),
4161 mc_trial(
4162 &chroma[1], x / 2, y / 2, side / 2, new_mv, false, ref_v.0, ref_v.1,
4163 ref_v.2, ref_v.3, false, search.base_q_idx, search.deadzone, chroma_set,
4164 fctx,
4165 ),
4166 )
4167 };
4168 let skip_new = luma_new.levels.iter().all(|&l| l == 0)
4169 && u_new.levels.iter().all(|&l| l == 0)
4170 && v_new.levels.iter().all(|&l| l == 0);
4171 let drl_bits = if stack.entries.len() > 1 {
4172 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
4173 } else {
4174 0.0
4175 };
4176 let cost_new = luma_new.sse
4177 + u_new.sse
4178 + v_new.sse
4179 + search.lambda
4180 * (skip_bits(skip_new)
4181 + intra_inter_bits(true)
4182 + single_ref_bits
4183 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
4184 + drl_bits
4185 + mv_bits
4186 + if skip_new {
4187 0.0
4188 } else {
4189 luma_new.bits + u_new.bits + v_new.bits
4190 });
4191 if cost_new < best.0 {
4192 single_syntax = intra_inter_bits(true)
4193 + single_ref_bits
4194 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
4195 + drl_bits
4196 + mv_bits;
4197 best = (
4198 cost_new,
4199 Some((
4200 luma_new,
4201 u_new,
4202 v_new,
4203 skip_new,
4204 InterInfo {
4205 ref1: None,
4206 mv1: (0, 0),
4207 ref_frame: crate::mvstack::LAST_FRAME,
4208 mode: InterMode::NewMv,
4209 mv: new_mv,
4210 ref_mv_idx: 0,
4211 },
4212 )),
4213 );
4214 }
4215 }
4216 }
4217
4218 // The COMPOUND candidates at this leaf (lane-av1comp3), the same set
4219 // `search_inter_block` prices for a whole 32x32 block:
4220 // `NEAREST_NEARESTMV`, `GLOBAL_GLOBALMV`, `NEW_NEARESTMV` off the vector
4221 // this leaf already searched, and -- since lane-av1comp4 gave the leaf a
4222 // SECOND-reference search of its own -- `NEAREST_NEWMV` and `NEW_NEWMV`
4223 // too. Priced with the same static-CDF approximation, plus the
4224 // compound-only syntax the writer emits.
4225 for (ref1, g, cstack) in compound.iter().filter(|_| leaf_compound()) {
4226 let (ref1, g) = (*ref1, *g);
4227 let uni =
4228 (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME).contains(&ref1);
4229 let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
4230 + if uni {
4231 symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
4232 + symbol_bits(&cdf::COMP_REF[0][0], 0)
4233 + symbol_bits(&cdf::COMP_REF[0][1], 0)
4234 + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
4235 } else {
4236 symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
4237 + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
4238 + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
4239 + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
4240 };
4241 let mode_ctx =
4242 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
4243 let mode_bits_of =
4244 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
4245 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
4246 (
4247 cstack.nearest_mv,
4248 mode_bits_of(0),
4249 InterInfo {
4250 ref_frame: crate::mvstack::LAST_FRAME,
4251 mode: InterMode::NearestNearestMv,
4252 mv: cstack.nearest_mv.0,
4253 mv1: cstack.nearest_mv.1,
4254 ref1: Some(ref1),
4255 ref_mv_idx: 0,
4256 },
4257 ),
4258 (
4259 ((0, 0), (0, 0)),
4260 mode_bits_of(6),
4261 InterInfo {
4262 ref_frame: crate::mvstack::LAST_FRAME,
4263 mode: InterMode::GlobalGlobalMv,
4264 mv: (0, 0),
4265 mv1: (0, 0),
4266 ref1: Some(ref1),
4267 ref_mv_idx: 0,
4268 },
4269 ),
4270 ];
4271 // Every compound MV residual here is priced against compound stack
4272 // entry 0, which is what `assign_compound_mv` predicts from at
4273 // `ref_mv_idx = 0` -- so it is also what the second-reference search
4274 // below seeds from and rounds to, and no candidate it finds can then
4275 // fail `mv_residual_bits`.
4276 let cbase = cstack
4277 .entries
4278 .first()
4279 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
4280 // This leaf's SECOND-reference motion search (lane-av1comp4). Without
4281 // it a leaf could only name a stack vector for the second half, and
4282 // screen capture showed the consequence: every leaf compound block
4283 // there was `NEAREST_NEARESTMV`. Skipped, like `search_inter_block`'s
4284 // extra-reference `NEWMV`, when this reference's own
4285 // `NEAREST_NEARESTMV` vector already prices `margin` times better
4286 // than the `LAST` search of this same leaf did -- one candidate
4287 // evaluation standing in for a whole search.
4288 let margin = leaf_second_new_margin();
4289 let mut second_new: Option<(i32, i32)> = None;
4290 if leaf_second_new_mv() {
4291 let skip = margin > 0.0
4292 && searched_new_cost.is_some_and(|last| {
4293 motion::cost_at(
4294 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y,
4295 side, side, cstack.nearest_mv.1, cbase.1, search.lambda, fctx,
4296 ) * margin
4297 <= last
4298 });
4299 if !skip {
4300 let mut seeds = [(0, 0); 4];
4301 let mut seed_n = 1;
4302 for e in cstack.entries.iter().take(3) {
4303 seeds[seed_n] = e.mv1;
4304 seed_n += 1;
4305 }
4306 let found = motion::search(
4307 &g.y, g.width, luma.true_width, luma.true_height, &source_block, x, y, side,
4308 side, cbase.1, &seeds[..seed_n], search.lambda, fctx, ref_distance(ref1),
4309 );
4310 second_new = Some(round_to_valid_mv(found.mv, cbase.1));
4311 }
4312 }
4313 if let Some(new_mv) = searched_new {
4314 if let Some(b0) = mv_residual_bits(new_mv, cbase.0) {
4315 ccands.push((
4316 (new_mv, cstack.nearest_mv.1),
4317 mode_bits_of(3) + b0,
4318 InterInfo {
4319 ref_frame: crate::mvstack::LAST_FRAME,
4320 mode: InterMode::NewNearestMv,
4321 mv: new_mv,
4322 mv1: cstack.nearest_mv.1,
4323 ref1: Some(ref1),
4324 ref_mv_idx: 0,
4325 },
4326 ));
4327 }
4328 }
4329 // `NEAREST_NEWMV` and `NEW_NEWMV`: the NEW halves are the two
4330 // searches this leaf ran, each residual priced against `cbase`.
4331 if let Some(mv1) = second_new {
4332 if let Some(b1) = mv_residual_bits(mv1, cbase.1) {
4333 ccands.push((
4334 (cstack.nearest_mv.0, mv1),
4335 mode_bits_of(2) + b1,
4336 InterInfo {
4337 ref_frame: crate::mvstack::LAST_FRAME,
4338 mode: InterMode::NearestNewMv,
4339 mv: cstack.nearest_mv.0,
4340 mv1,
4341 ref1: Some(ref1),
4342 ref_mv_idx: 0,
4343 },
4344 ));
4345 if let Some((new_mv, b0)) =
4346 searched_new.and_then(|m| mv_residual_bits(m, cbase.0).map(|b| (m, b)))
4347 {
4348 ccands.push((
4349 (new_mv, mv1),
4350 mode_bits_of(7) + b0 + b1,
4351 InterInfo {
4352 ref_frame: crate::mvstack::LAST_FRAME,
4353 mode: InterMode::NewNewMv,
4354 mv: new_mv,
4355 mv1,
4356 ref1: Some(ref1),
4357 ref_mv_idx: 0,
4358 },
4359 ));
4360 }
4361 }
4362 }
4363 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
4364 ccands.dedup_by_key(|c| c.0);
4365 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
4366 let g_u = (
4367 g.u.as_slice(),
4368 g.width / 2,
4369 chroma[0].true_width,
4370 chroma[0].true_height,
4371 );
4372 let g_v = (
4373 g.v.as_slice(),
4374 g.width / 2,
4375 chroma[1].true_width,
4376 chroma[1].true_height,
4377 );
4378 for (mvs, bits, info) in ccands {
4379 let luma_c = mc_trial_compound(
4380 luma, x, y, side, mvs, true,
4381 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
4382 search.base_q_idx, search.deadzone, luma_set, fctx,
4383 );
4384 let u_c = mc_trial_compound(
4385 &chroma[0], x / 2, y / 2, side / 2, mvs, false,
4386 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
4387 search.base_q_idx, search.deadzone, chroma_set, fctx,
4388 );
4389 let v_c = mc_trial_compound(
4390 &chroma[1], x / 2, y / 2, side / 2, mvs, false,
4391 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
4392 search.base_q_idx, search.deadzone, chroma_set, fctx,
4393 );
4394 let skip_c = luma_c.levels.iter().all(|&l| l == 0)
4395 && u_c.levels.iter().all(|&l| l == 0)
4396 && v_c.levels.iter().all(|&l| l == 0);
4397 let cost_c = luma_c.sse
4398 + u_c.sse
4399 + v_c.sse
4400 + search.lambda
4401 * (skip_bits(skip_c)
4402 + intra_inter_bits(true)
4403 + bits
4404 + if skip_c { 0.0 } else { luma_c.bits + u_c.bits + v_c.bits });
4405 if cost_c < best.0 {
4406 best = (cost_c, Some((luma_c, u_c, v_c, skip_c, info)));
4407 }
4408 }
4409 }
4410
4411 // lane-av1obmc2: the OBMC candidate at a 16x16 / 8x8 LEAF (spec
4412 // `motion_mode == OBMC_CAUSAL`), offered to this leaf's single-reference
4413 // winner -- libaom's `motion_mode_allowed` refuses a compound block, and
4414 // the writer codes no symbol for one. The prediction is the decoder's own
4415 // plan and blend over the neighbours this leaf's `grid` already carries
4416 // (published by `record_mi` in the writer's coding order), so the
4417 // reconstruction priced here is the one a decoder rebuilds. lane-av1obmc
4418 // offered this only at 32x32, which is not where libaom cashes its OBMC
4419 // gain.
4420 let mut motion_won = 0u8;
4421 let single = match &best.1 {
4422 None => Some(nearest_info),
4423 Some((_, _, _, _, info)) if info.ref1.is_none() => Some(*info),
4424 Some(_) => None,
4425 };
4426 if let Some(info) = single.filter(|i| {
4427 (crate::envflags::env_flag!("EC_AV1_OBMC") || crate::envflags::env_flag!("EC_AV1_WARP"))
4428 && i.ref_frame == crate::mvstack::LAST_FRAME
4429 }) {
4430 let planes = [
4431 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
4432 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
4433 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
4434 ];
4435 // Which alphabet this block's writer will code the symbol against
4436 // (`tile::write_motion_mode`, libaom `motion_mode_allowed`): the
4437 // 3-symbol one only under `allow_warped_motion` and at least one warp
4438 // sample. Mirrored here so the candidates are priced against the
4439 // table the tile really narrows.
4440 let warp_alphabet = crate::envflags::env_flag!("EC_AV1_WARP")
4441 && crate::decode::num_proj_ref(
4442 grid,
4443 mi_row,
4444 mi_col,
4445 side / 4,
4446 side / 4,
4447 mi_cols,
4448 mi_rows,
4449 info.ref_frame,
4450 fctx,
4451 ) >= 1;
4452 let mm = |m: u8| motion_mode_bits(side, side, m, warp_alphabet);
4453 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
4454 if crate::envflags::env_flag!("EC_AV1_OBMC") && side >= obmc_min_side() {
4455 if let Some(pred) = obmc_prediction(
4456 grid,
4457 (mi_row, mi_col),
4458 (mi_rows, mi_cols),
4459 (x, y),
4460 side,
4461 info.mv,
4462 refs,
4463 planes,
4464 reference.width,
4465 fctx,
4466 ) {
4467 candidates.push((1, pred));
4468 }
4469 }
4470 if warp_alphabet {
4471 if let Some(pred) = warp_prediction(
4472 grid,
4473 (mi_row, mi_col),
4474 (mi_rows, mi_cols),
4475 (x, y),
4476 side,
4477 info.mv,
4478 info.ref_frame,
4479 planes,
4480 fctx,
4481 ) {
4482 candidates.push((2, pred));
4483 }
4484 }
4485 for (motion, pred) in candidates {
4486 let luma_o = luma.code_from_prediction(
4487 x, y, side, &pred[0], false, search.base_q_idx, search.deadzone, luma_set,
4488 );
4489 let u_o = chroma[0].code_from_prediction(
4490 x / 2, y / 2, side / 2, &pred[1], false, search.base_q_idx, search.deadzone,
4491 chroma_set,
4492 );
4493 let v_o = chroma[1].code_from_prediction(
4494 x / 2, y / 2, side / 2, &pred[2], false, search.base_q_idx, search.deadzone,
4495 chroma_set,
4496 );
4497 let skip_o = luma_o.levels.iter().all(|&l| l == 0)
4498 && u_o.levels.iter().all(|&l| l == 0)
4499 && v_o.levels.iter().all(|&l| l == 0);
4500 let cost_o = luma_o.sse
4501 + u_o.sse
4502 + v_o.sse
4503 + search.lambda
4504 * (skip_bits(skip_o)
4505 + single_syntax
4506 + mm(motion)
4507 + if skip_o { 0.0 } else { luma_o.bits + u_o.bits + v_o.bits });
4508 // The incumbent pays the motion_mode symbol IT would code, so
4509 // both sides of the comparison carry that syntax.
4510 if cost_o < best.0 + search.lambda * mm(motion_won) {
4511 motion_won = motion;
4512 best = (cost_o, Some((luma_o, u_o, v_o, skip_o, info)));
4513 }
4514 }
4515 }
4516
4517 if let (cost, Some((luma_new, u_new, v_new, skip_new, info))) = best {
4518 if cost < intra_cost {
4519 // A compound winner commits the flat trial it was priced from:
4520 // `commit_inter_luma`'s var-tx trial set is single-reference
4521 // (`mc_trial`), so a compound leaf codes `tx_depth = 0`.
4522 // lane-av1comp4 BUILT that upgrade (a `commit_inter_luma`
4523 // predicting each half-side trial from BOTH references, verified
4524 // byte-identical to this when its split is disabled) and MEASURED
4525 // it a loss: vs libaom +83.5/+99.7/+54.9 at no margin against the
4526 // +83.0/+99.9/+54.5 here, and +83.3/+100.2/+54.9, +83.8/+99.5/
4527 // +54.9, +83.3/+100.0/+54.9 at split margins 0.02/0.05/0.15. A
4528 // compound block's residual is small enough that the four extra
4529 // per-unit txb_skip/eob symbols cost more ladder bytes than this
4530 // encoder's static-CDF estimate prices them at, so the local RD
4531 // win does not convert. lane-av1txbits REBUILT it on top of a
4532 // search that prices against the tables the frame is really
4533 // written with (`tile::arm_pricing_cdfs`, the estimate error on
4534 // these very blocks measured down from +31% to +3%) and measured
4535 // it neutral-to-worse again: +78.8/+95.0/+54.5 and +36.5/+56.3/
4536 // +1.4 against the +78.8/+95.1/+54.5 and +36.1/+56.4/+1.4 of the
4537 // same build without it. The static-CDF estimate was NOT what
4538 // held the compound var-tx trial back. The flat trial stays.
4539 // An OBMC winner commits the flat trial too: `commit_inter_luma`
4540 // re-predicts each var-tx unit by plain translation, which is not
4541 // the prediction this candidate was priced from.
4542 let (levels, tx_depth, dcost) = if info.ref1.is_some() || motion_won != 0 {
4543 luma.commit(x, y, side, &luma_new);
4544 (luma_new.levels.clone(), 0, 0.0)
4545 } else {
4546 commit_inter_luma(
4547 luma, (x, y), side, info.mv,
4548 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
4549 search, &luma_new, skip_new, fctx,
4550 )
4551 };
4552 chroma[0].commit(x / 2, y / 2, side / 2, &u_new);
4553 chroma[1].commit(x / 2, y / 2, side / 2, &v_new);
4554 return (
4555 BlockCoeffs {
4556 luma: coeffs(&levels, side),
4557 u: coeffs(&u_new.levels, side / 2),
4558 v: coeffs(&v_new.levels, side / 2),
4559 mode: DC_PRED as u8,
4560 uv_mode: DC_PRED,
4561 skip: skip_new,
4562 eight: None,
4563 dv: None,
4564 palette: None,
4565 palette_uv: None,
4566 tx_depth,
4567 inter: Some(info),
4568 motion_mode: motion_won,
4569 },
4570 cost + dcost,
4571 );
4572 }
4573 }
4574
4575 census_add(8, 1);
4576 if skip {
4577 census_add(10, 1);
4578 }
4579 if inter_cost >= intra_cost {
4580 census_add(9, 1);
4581 }
4582 if inter_cost < intra_cost {
4583 let (levels, tx_depth, dcost) = commit_inter_luma(
4584 luma, (x, y), side, mv, (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), search, &luma_trial, skip, fctx,
4585 );
4586 chroma[0].commit(x / 2, y / 2, side / 2, &u);
4587 chroma[1].commit(x / 2, y / 2, side / 2, &v);
4588 (BlockCoeffs {
4589 luma: coeffs(&levels, side),
4590 u: coeffs(&u.levels, side / 2),
4591 v: coeffs(&v.levels, side / 2),
4592 mode: DC_PRED as u8,
4593 uv_mode: DC_PRED,
4594 skip,
4595 eight: None,
4596 dv: None,
4597 palette: None,
4598 palette_uv: None,
4599 tx_depth,
4600 motion_mode: 0,
4601 inter: Some(InterInfo {
4602 ref1: None,
4603 mv1: (0, 0),
4604 ref_frame: crate::mvstack::LAST_FRAME,
4605 mode: InterMode::NearestMv,
4606 mv,
4607 ref_mv_idx: 0,
4608 }),
4609 }, inter_cost + dcost)
4610 } else {
4611 (intra_block, intra_cost)
4612 }
4613}
4614
4615/// Publishes one coded inter-frame block into the `mi` grid the next block's
4616/// MV stack reads, over the `size` x `size` 4x4 units it covers. An intra
4617/// block casts no vote but is still a coded cell (see `code_square_inter`'s
4618/// note on `processed_rows`/`processed_cols`).
4619fn record_mi(grid: &mut MiGrid, mi_row: usize, mi_col: usize, size: u8, inter: Option<InterInfo>) {
4620 let info = match inter {
4621 Some(info) => MiInfo {
4622 is_inter: true,
4623 ref_frame: info.ref_frame,
4624 // A COMPOUND block votes with BOTH of its references and both of
4625 // its vectors, exactly as the tile writer publishes it: recording
4626 // a compound block as a single-reference one here left the
4627 // encoder's own grid disagreeing with the writer's from the first
4628 // compound block on, so every later stack it searched against was
4629 // not the stack the decoder derives.
4630 ref_frame1: info.ref1.unwrap_or(NO_REF1),
4631 mv1: mv16(info.mv1),
4632 mv: mv16(info.mv),
4633 // decode.rs' own `is_new_mv`: `NEWMV` on the single-reference
4634 // side, compound modes 2/3/7 on the other.
4635 is_new_mv: matches!(
4636 info.mode,
4637 InterMode::NewMv
4638 | InterMode::NewNewMv
4639 | InterMode::NearestNewMv
4640 | InterMode::NewNearestMv
4641 ),
4642 size,
4643 size_h: size,
4644 is_global_mv0: false,
4645 is_global_mv1: false,
4646 },
4647 None => MiInfo {
4648 is_inter: false,
4649 ref_frame: -1,
4650 ref_frame1: NO_REF1,
4651 mv1: (0, 0),
4652 mv: (0, 0),
4653 is_new_mv: false,
4654 size,
4655 size_h: size,
4656 is_global_mv0: false,
4657 is_global_mv1: false,
4658 },
4659 };
4660 for dr in 0..usize::from(size) {
4661 for dc in 0..usize::from(size) {
4662 grid.set(mi_row + dr, mi_col + dc, info);
4663 }
4664 }
4665}
4666
4667/// The reconstructed samples one 32x32 square covers in all three planes, so
4668/// that a partition trial can be undone.
4669/// One square of a plane, row-major, the inverse of [`Plane::restore`].
4670///
4671/// Same bytes as the `flat_map(|row| ..to_vec()).collect()` this replaces,
4672/// which allocated and freed a `Vec` per row of every block it copied --
4673/// `Plane::snapshot` runs once per partition trial.
4674fn rows_of(plane: &[u8], width: usize, x: usize, y: usize, side: usize) -> Vec<u8> {
4675 let mut out = vec![0u8; side * side];
4676 for row in 0..side {
4677 out[row * side..][..side].copy_from_slice(&plane[(y + row) * width + x..][..side]);
4678 }
4679 out
4680}
4681
4682fn snapshot(
4683 luma: &Plane,
4684 chroma: &[Plane; 2],
4685 (x, y): (usize, usize),
4686 side: usize,
4687) -> [(Vec<u8>, Vec<CoefCtx>); 3] {
4688 [
4689 luma.snapshot(x, y, side),
4690 chroma[0].snapshot(x / 2, y / 2, side / 2),
4691 chroma[1].snapshot(x / 2, y / 2, side / 2),
4692 ]
4693}
4694
4695/// Puts such a snapshot back.
4696fn restore(
4697 luma: &mut Plane,
4698 chroma: &mut [Plane; 2],
4699 (x, y): (usize, usize),
4700 side: usize,
4701 saved: &[(Vec<u8>, Vec<CoefCtx>); 3],
4702) {
4703 luma.restore(x, y, side, &saved[0]);
4704 chroma[0].restore(x / 2, y / 2, side / 2, &saved[1]);
4705 chroma[1].restore(x / 2, y / 2, side / 2, &saved[2]);
4706}
4707
4708/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
4709/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
4710/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
4711/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
4712/// rule shared with the key-frame path, not a second one that could diverge.
4713fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
4714 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
4715 let dc_entry = dc_pos.map(|i| scored.remove(i));
4716 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
4717 scored.truncate(if dc_entry.is_some() {
4718 top_k.saturating_sub(1)
4719 } else {
4720 top_k
4721 });
4722 if let Some(dc_entry) = dc_entry {
4723 scored.push(dc_entry);
4724 }
4725 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
4726 modes.iter().copied().filter(|m| keep.contains(m)).collect()
4727}
4728
4729fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
4730 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
4731 [INTRA_MODE_CTX[usize::from(left_mode)]];
4732 std::array::from_fn(|mode| {
4733 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
4734 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
4735 } else {
4736 0.0
4737 };
4738 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
4739 })
4740}
4741
4742/// What the luma mode search picks between, and under what terms.
4743struct Search<'a> {
4744 /// This frame's `allow_screen_content_tools` ([`screen_content`]): the
4745 /// luma search then offers a palette candidate beside the intra modes.
4746 screen: bool,
4747 base_q_idx: u8,
4748 deadzone: f64,
4749 lambda: f64,
4750 modes: &'a [u8],
4751 /// How many of `modes` the full RD trial (forward transform, quantize,
4752 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
4753 /// pre-pass on the prediction residual alone plus DC (always kept, since
4754 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
4755 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
4756 /// mode through full RD, unchanged from before this lever.
4757 top_k: Option<usize>,
4758}
4759
4760/// [`Search::top_k`]'s value: `None` keeps every mode's search unchanged
4761/// (the default, until a lever's quality gate justifies pruning by default);
4762/// `EC_AV1_PRUNE_K` sweeps it in a test build without touching callers.
4763fn prune_top_k() -> Option<usize> {
4764 #[cfg(test)]
4765 {
4766 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
4767 return k;
4768 }
4769 }
4770 let swept = std::env::var("EC_AV1_PRUNE_K")
4771 .ok()
4772 .and_then(|v| v.parse::<usize>().ok());
4773 match swept {
4774 Some(k) if cfg!(test) => Some(k),
4775 _ => PRUNE_TOP_K,
4776 }
4777}
4778
4779// A per-thread override [`prune_top_k`] checks first, so one test can sweep
4780// `top_k` in-process without mutating the environment (forbidden here --
4781// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
4782#[cfg(test)]
4783thread_local! {
4784 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
4785 const { std::cell::Cell::new(None) };
4786}
4787
4788#[cfg(test)]
4789fn set_test_top_k_override(value: Option<usize>) {
4790 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
4791}
4792
4793/// The default: unpruned, thirteen full trials per block, same as before this
4794/// lever. Set from the sweep in the lane report if the quality gate clears it.
4795const PRUNE_TOP_K: Option<usize> = None;
4796
4797/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
4798/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
4799/// quality gates were measured separately and may land on different
4800/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
4801/// [`EC_AV1_PRUNE_K`] or the key-frame path.
4802fn prune_top_k_inter() -> Option<usize> {
4803 #[cfg(test)]
4804 {
4805 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
4806 return k;
4807 }
4808 }
4809 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
4810 .ok()
4811 .and_then(|v| v.parse::<usize>().ok());
4812 match swept {
4813 Some(k) if cfg!(test) => Some(k),
4814 _ => INTER_PRUNE_TOP_K,
4815 }
4816}
4817
4818// A per-thread override [`prune_top_k_inter`] checks first, same reason as
4819// [`TEST_TOP_K_OVERRIDE`].
4820#[cfg(test)]
4821thread_local! {
4822 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
4823 const { std::cell::Cell::new(None) };
4824}
4825
4826#[cfg(test)]
4827fn set_test_top_k_override_inter(value: Option<usize>) {
4828 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
4829}
4830
4831/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
4832/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
4833/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
4834/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
4835/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
4836/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
4837/// pruning them costs less quality here.
4838const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
4839
4840// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
4841// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
4842// inter frame's cost can be attributed to a bucket without changing what
4843// the search actually does. Index: 0 = whole-call time inside
4844// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
4845// [`crate::mc::predict`] (every call, from the motion search's own
4846// candidates and from a committed inter block's final prediction alike),
4847// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
4848#[cfg(test)]
4849thread_local! {
4850 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
4851 std::cell::Cell::new(0),
4852 std::cell::Cell::new(0),
4853 std::cell::Cell::new(0),
4854 std::cell::Cell::new(0),
4855 ];
4856}
4857
4858#[cfg(test)]
4859pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
4860 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
4861}
4862
4863#[cfg(test)]
4864fn stage_reset() {
4865 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
4866}
4867
4868#[cfg(test)]
4869fn stage_read() -> [std::time::Duration; 4] {
4870 STAGE_NS.with(|c| {
4871 c.each_ref()
4872 .map(|cell| std::time::Duration::from_nanos(cell.get()))
4873 })
4874}
4875
4876/// One mode's coding of one block, before it is committed.
4877#[derive(Clone)]
4878struct Trial {
4879 levels: Vec<i32>,
4880 reconstruction: Vec<u8>,
4881 sse: f64,
4882 bits: f64,
4883}
4884
4885/// The non-zero levels of a block, as the tile writer takes them.
4886fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
4887 levels
4888 .iter()
4889 .enumerate()
4890 .filter(|&(_, &level)| level != 0)
4891 .map(|(i, &level)| Coeff {
4892 row: (i / side) as u8,
4893 col: (i % side) as u8,
4894 level,
4895 })
4896 .collect()
4897}
4898
4899thread_local! {
4900 /// The tile grid the next frame is coded with, as `(TileColsLog2,
4901 /// TileRowsLog2)` -- armed by [`crate::encoder::Av1Encoder`] from its
4902 /// [`crate::encoder::EncoderConfig`], the same way `crate::tile`'s
4903 /// `arm_cdef_idx`/`arm_lr`/`arm_sign_bias` arm the writers. `(0, 0)` is
4904 /// one tile per frame, what every caller that never arms anything gets
4905 /// and what every stream this crate wrote before tiles existed carries.
4906 static TILE_LOG2: std::cell::Cell<(u32, u32)> = const { std::cell::Cell::new((0, 0)) };
4907}
4908
4909/// Arms this thread's next frame encodes with a tile grid (log2 counts).
4910pub(crate) fn arm_tiles(cols_log2: u32, rows_log2: u32) {
4911 TILE_LOG2.with(|c| c.set((cols_log2, rows_log2)));
4912}
4913
4914fn armed_tiles() -> (u32, u32) {
4915 let armed = TILE_LOG2.with(std::cell::Cell::get);
4916 if armed != (0, 0) {
4917 return armed;
4918 }
4919 // `EC_AV1_TILES=<cols_log2>[:<rows_log2>]` in a TEST build, so the BD gate
4920 // (which codes through `encode_sequence`, not the facade) can measure what
4921 // a tile grid costs without a knob of its own -- same shape as
4922 // `EC_AV1_LR`/`EC_AV1_PYRAMID`.
4923 match std::env::var("EC_AV1_TILES").ok() {
4924 Some(v) if cfg!(test) => {
4925 let mut f = v.split(':');
4926 let cols = f.next().and_then(|c| c.parse().ok()).unwrap_or(0);
4927 let rows = f.next().and_then(|r| r.parse().ok()).unwrap_or(0);
4928 (cols, rows)
4929 }
4930 _ => armed,
4931 }
4932}
4933
4934/// Codes a frame's `tiles` tiles, each entirely on its own (see
4935/// [`crate::tile::TileRect`]), across [`crate::par::tile_threads`] workers of
4936/// the crate's own pool, and hands back their payloads in tile order plus
4937/// whatever `code` returned for tile `store` -- the CDF state
4938/// `context_update_tile_id` names. The result cannot depend on the thread
4939/// count: each job writes one tile from the frame's own starting tables into
4940/// its own slot.
4941fn write_tiles<F>(tiles: usize, store: usize, code: F) -> Result<(Vec<Vec<u8>>, Option<crate::cdf_state::Cdfs>)>
4942where
4943 F: Fn(usize) -> Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)> + Sync + Send,
4944{
4945 let _t = crate::par::timer(crate::par::S_TILE_WRITE);
4946 type Slot = Option<Result<(Vec<u8>, Option<crate::cdf_state::Cdfs>)>>;
4947 let threads = crate::par::tile_threads().min(tiles);
4948 let mut slots: Vec<Slot> = Vec::new();
4949 if threads <= 1 {
4950 for index in 0..tiles {
4951 slots.push(Some(code(index)));
4952 }
4953 } else {
4954 let done: std::sync::Mutex<Vec<Slot>> = std::sync::Mutex::new((0..tiles).map(|_| None).collect());
4955 {
4956 let batch = crate::par::Batch::new("ec-av1-tile");
4957 for (from, to) in crate::par::bands(tiles, threads) {
4958 let done = &done;
4959 let code = &code;
4960 batch.submit(move || {
4961 for index in from..to {
4962 let coded = code(index);
4963 done.lock().expect("tile slots")[index] = Some(coded);
4964 }
4965 });
4966 }
4967 }
4968 slots = done.into_inner().expect("tile slots");
4969 }
4970 let mut out = Vec::with_capacity(tiles);
4971 let mut stored = None;
4972 for (index, slot) in slots.into_iter().enumerate() {
4973 let (bytes, cdfs) = slot.expect("every tile was coded")?;
4974 if index == store {
4975 stored = cdfs;
4976 }
4977 out.push(bytes);
4978 }
4979 Ok((out, stored))
4980}
4981
4982/// Runs `job(tile_index, ctx)` once per tile, on `EC_AV1_TILE_THREADS`
4983/// workers, and returns the results in tile order. The counterpart of
4984/// [`write_tiles`] for the RD/motion SEARCH: a tile's job owns every piece of
4985/// state the search mutates (its own reconstruction planes, its own `MiGrid`,
4986/// its own neighbour-mode bands and its own [`crate::decode::FrameCtx`]), and
4987/// availability is already tile-relative (`clip_planes_to_tile`,
4988/// `MiGrid::set_tile_bounds`), so what a tile decides cannot depend on which
4989/// other tiles have run -- gated by
4990/// `encoder::tests::tile_bytes_do_not_depend_on_the_thread_count`, which now
4991/// covers the search as well as the write.
4992///
4993/// The `FrameCtx` copy is made on the calling thread (`&FrameCtx` is `!Sync`
4994/// by design) and moved into the worker, exactly as [`crate::par::run_bands`]
4995/// does it for the decoder's filter bands.
4996fn search_tiles<T, F>(tiles: usize, fctx: &crate::decode::FrameCtx, job: F) -> Result<Vec<T>>
4997where
4998 T: Send,
4999 F: Fn(usize, &crate::decode::FrameCtx) -> Result<T> + Sync,
5000{
5001 let _t = crate::par::timer(crate::par::S_TILE_SEARCH);
5002 let threads = crate::par::tile_threads().min(tiles);
5003 if threads <= 1 {
5004 return (0..tiles).map(|index| job(index, fctx)).collect();
5005 }
5006 type Slot<T> = Option<Result<T>>;
5007 let done: std::sync::Mutex<Vec<Slot<T>>> =
5008 std::sync::Mutex::new((0..tiles).map(|_| None).collect());
5009 {
5010 let batch = crate::par::Batch::new("ec-av1-tile-search");
5011 for (from, to) in crate::par::bands(tiles, threads) {
5012 let done = &done;
5013 let job = &job;
5014 let ctx = crate::decode::filter_ctx_copy(fctx);
5015 batch.submit(move || {
5016 for index in from..to {
5017 let searched = job(index, &ctx);
5018 done.lock().expect("tile slots")[index] = Some(searched);
5019 }
5020 });
5021 }
5022 }
5023 done.into_inner()
5024 .expect("tile slots")
5025 .into_iter()
5026 .map(|slot| slot.expect("every tile was searched"))
5027 .collect()
5028}
5029
5030/// One tile job's own copy of a plane: the frame's source, a blank
5031/// reconstruction of the frame's size, and the frame's own bounds -- narrowed
5032/// to the tile by `clip_planes_to_tile` right after. Blank rather than a copy
5033/// of the frame's reconstruction because a tile's prediction never reads a
5034/// sample outside its own rectangle, and every sample inside it is written
5035/// before it is read.
5036fn fresh_plane(source: &[u8], width: usize, height: usize, true_width: usize, true_height: usize) -> Plane<'_> {
5037 Plane {
5038 source,
5039 reconstruction: vec![128; source.len()],
5040 width,
5041 height,
5042 true_width,
5043 true_height,
5044 tile_x0: 0,
5045 tile_y0: 0,
5046 tile_x1: width,
5047 tile_y1: height,
5048 ctx: CoefCtxMap::default(),
5049 }
5050}
5051
5052/// Copies the rectangle `[x0, x1) x [y0, y1)` of a tile job's own plane into
5053/// the frame's plane, through the [`crate::par::Shared`] every job holds.
5054///
5055/// corner-cut: the disjointness that makes the aliasing sound is the caller's
5056/// -- `x0..x1`/`y0..y1` are the job's own `TileRect`, and a frame's tile
5057/// rectangles partition it -- checked end-to-end by
5058/// `tile_bytes_do_not_depend_on_the_thread_count` rather than by the borrow
5059/// checker, exactly the contract `Shared`'s own doc names. Upgrade path is
5060/// row-range `split_at_mut` plumbing through `Plane`, which would have to
5061/// thread an origin offset through every prediction and transform call site
5062/// for the same bytes.
5063#[allow(unsafe_code)]
5064fn copy_rect(
5065 dst: crate::par::Shared<'_, Vec<u8>>,
5066 src: &[u8],
5067 stride: usize,
5068 x0: usize,
5069 y0: usize,
5070 x1: usize,
5071 y1: usize,
5072) {
5073 // SAFETY: this job touches only its own tile rectangle (see above).
5074 let dst = unsafe { dst.get() };
5075 for y in y0..y1 {
5076 let (a, b) = (y * stride + x0, y * stride + x1);
5077 dst[a..b].copy_from_slice(&src[a..b]);
5078 }
5079}
5080
5081/// The frame header's `tile_info` (spec 5.9.15) for `layout`:
5082/// `context_update_tile_id` names the largest tile, whose end-of-tile CDF
5083/// tables the frame stores (spec 7.20), which is what
5084/// [`crate::tile::TileLayout::largest_tile`] picks and what the tile loops
5085/// below publish.
5086fn tile_info_of(layout: &crate::tile::TileLayout, tile_size_bytes: u32) -> ec_av1_syntax::TileInfo {
5087 ec_av1_syntax::TileInfo {
5088 uniform_spacing: true,
5089 cols: layout.cols(),
5090 rows: layout.rows(),
5091 cols_log2: layout.cols_log2,
5092 rows_log2: layout.rows_log2,
5093 mi_col_starts: layout.mi_col_starts(),
5094 mi_row_starts: layout.mi_row_starts(),
5095 context_update_tile_id: layout.largest_tile() as u32,
5096 tile_size_bytes,
5097 }
5098}
5099
5100/// Clips the three planes' intra edge reads to `rect`, the tile the
5101/// superblock about to be searched belongs to (the encoder side of the
5102/// decoder's `PlaneBuf::set_tile_origin`). The search itself stays in frame
5103/// raster order -- which is a linear extension of every tile's own coding
5104/// order, so a block still only ever predicts from samples already
5105/// reconstructed -- and only availability is tile-relative.
5106fn clip_planes_to_tile(
5107 luma: &mut Plane<'_>,
5108 chroma: &mut [Plane<'_>; 2],
5109 rect: crate::tile::TileRect,
5110) {
5111 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
5112 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
5113 luma.set_tile(x0, y0, x1, y1);
5114 for plane in chroma.iter_mut() {
5115 plane.set_tile(x0 / 2, y0 / 2, x1.div_ceil(2), y1.div_ceil(2));
5116 }
5117}
5118
5119/// Encodes one picture as a key frame.
5120///
5121/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
5122/// picks its coefficient CDFs from one of four q contexts by that index.
5123/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
5124/// smaller values trade fidelity for rate.
5125///
5126/// The picture may be any even width and height: the encoder pads it by edge
5127/// replication to a whole number of 32x32 blocks internally, and the frame it
5128/// writes crops back to the picture's own size (`render_width`/
5129/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
5130/// own size, never the padded one.
5131///
5132/// # Errors
5133/// Returns an error when the picture's width or height is zero or odd, or
5134/// when its planes are not 4:2:0 of that size.
5135/// Codes one picture as a whole key frame, at `base_q_idx`, and returns its
5136/// stream. The per-frame decode state this needs lives for exactly this call.
5137///
5138/// # Errors
5139/// Returns an error under the same conditions
5140/// [`encode_key_frame_with_modes`] does.
5141pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
5142 encode_key_frame_with_ctx(picture, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
5143}
5144
5145/// [`encode_key_frame`] with the per-block intra modes given rather than
5146/// searched.
5147///
5148/// # Errors
5149/// Returns an error when `picture`'s dimensions are odd or zero, when `modes`
5150/// is empty, or when a block's coefficients do not fit the coded frame.
5151pub fn encode_key_frame_with_modes(
5152 picture: &Picture,
5153 base_q_idx: u8,
5154 deadzone: f64,
5155 modes: &[u8],
5156) -> Result<Encoded> {
5157 encode_key_frame_with_modes_with_ctx(
5158 picture,
5159 base_q_idx,
5160 deadzone,
5161 modes,
5162 &crate::decode::FrameCtx::new(),
5163 )
5164}
5165
5166/// Codes `pictures` as one key frame followed by inter frames.
5167///
5168/// # Errors
5169/// Returns an error under the same conditions [`encode_key_frame`] and the
5170/// inter frame path do.
5171pub fn encode_sequence(
5172 pictures: &[Picture],
5173 base_q_idx: u8,
5174 deadzone: f64,
5175) -> Result<EncodedSequence> {
5176 encode_sequence_with_ctx(pictures, base_q_idx, deadzone, &crate::decode::FrameCtx::new())
5177}
5178
5179pub(crate) fn encode_key_frame_with_ctx(picture: &Picture, base_q_idx: u8, deadzone: f64, fctx: &crate::decode::FrameCtx) -> Result<Encoded> {
5180 encode_key_frame_with_modes_with_ctx(picture, base_q_idx, deadzone, &KEY_FRAME_MODES, fctx)
5181}
5182
5183/// Encodes one picture as a key frame, choosing each block's luma mode from
5184/// `modes` alone.
5185///
5186/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
5187/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
5188/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
5189/// uses.
5190///
5191/// # Errors
5192/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
5193/// names a mode [`crate::intra::predict`] does not predict.
5194pub(crate) fn encode_key_frame_with_modes_with_ctx(
5195 picture: &Picture,
5196 base_q_idx: u8,
5197 deadzone: f64,
5198 modes: &[u8], fctx: &crate::decode::FrameCtx,
5199) -> Result<Encoded> {
5200 picture.check_even()?;
5201 let padded = picture.padded_to(BLOCK);
5202 let encoded = encode_key_frame_inner(
5203 &padded,
5204 base_q_idx,
5205 deadzone,
5206 modes,
5207 split_blocks(),
5208 (picture.width, picture.height),
5209 unspecified_color_config(), fctx,
5210 )?;
5211 Ok(crop_encoded(&encoded, picture.width, picture.height))
5212}
5213
5214/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
5215/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
5216/// already padded to a whole number of 32x32 blocks; `render` is the real
5217/// (pre-pad) size the frame header tells a decoder to crop back to.
5218pub(crate) fn encode_key_frame_inner(
5219 picture: &Picture,
5220 base_q_idx: u8,
5221 deadzone: f64,
5222 modes: &[u8],
5223 split_blocks: bool,
5224 render: (usize, usize),
5225 color_config: ColorConfig, fctx: &crate::decode::FrameCtx,
5226) -> Result<Encoded> {
5227 picture.check()?;
5228 if modes.is_empty() {
5229 return Err(Error::unsupported(
5230 "AV1 encode",
5231 "a mode search needs at least one mode to choose from",
5232 ));
5233 }
5234 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
5235 return Err(Error::unsupported(
5236 "AV1 encode",
5237 format!("intra mode {bad} is not one the encoder predicts"),
5238 ));
5239 }
5240 // The header carries the frame's true (unpadded) size as `frame_width`/
5241 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
5242 // `mi_rows` derived from that same true size (spec `compute_image_size`).
5243 // `render_width`/`render_height` come out equal to it too, so
5244 // `render_and_frame_size_different` is false and no render_size bits are
5245 // written, mirroring libaom/rav1e: the padded `picture` below is only the
5246 // internal coding surface, never what the header names.
5247 // Screen-content detection runs on the SOURCE luma, before any header is
5248 // built: it decides this sequence's `seq_force_screen_content_tools` (and
5249 // so the layout of every frame header after it, [`SEQ_SCREEN`]) as well as
5250 // this frame's own `allow_screen_content_tools`.
5251 let screen = screen_content(
5252 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
5253 picture.width,
5254 (picture.width).min(render.0),
5255 (picture.height).min(render.1),
5256 );
5257 arm_seq_screen(screen);
5258 // A key frame's writer really does start from the defaults, and a search
5259 // worker may be carrying an inter frame's armed tables (lane-av1txbits):
5260 // disarm, or a key frame's bits would depend on which thread searched it.
5261 crate::tile::arm_pricing_cdfs(None, false);
5262 // spec 5.9.2 `allow_intrabc`, screen-detected key frames only: the bit
5263 // forces deblocking, CDEF and loop restoration OFF for this frame
5264 // (frame.rs:194/210/252/272), so it is only set when the source repeats
5265 // itself enough for the copied blocks to pay that back
5266 // ([`intrabc_worth_it`]).
5267 // Single-tile frames only: decode.rs keeps ONE frame-scoped intrabc mi
5268 // grid across every tile while this writer builds one per tile, so a
5269 // multi-tile allow_intrabc frame would predict its DVs off a different
5270 // grid than the decoder does. corner-cut, ceiling named: the upgrade
5271 // path is a frame-scoped grid shared by the tile writers.
5272 let (allow_intrabc, ibc_share) = if screen && intrabc_enabled() && armed_tiles() == (0, 0) {
5273 intrabc_worth_it(
5274 &picture.y.iter().map(|&v| v as u8).collect::<Vec<u8>>(),
5275 picture.width,
5276 picture.width.min(render.0),
5277 picture.height.min(render.1),
5278 )
5279 } else {
5280 (false, 0.0)
5281 };
5282 IBC_SHARE.with(|c| c.set(ibc_share));
5283 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
5284 header.allow_screen_content_tools = screen;
5285 header.allow_intrabc = allow_intrabc;
5286 header.render_width = render.0 as u32;
5287 header.render_height = render.1 as u32;
5288 // `TxMode::Select`: every block codes a `tx_depth` symbol and may split
5289 // its luma transform below its own side (`crate::tile::write_luma_select`).
5290 // Set here rather than in `key_frame_headers_colour` so the header
5291 // builders' other callers -- the hand-built tile writers, which code no
5292 // depth symbol -- keep the `TxMode::Largest` stream they are written for.
5293 let tx_select = tx_select();
5294 if tx_select {
5295 header.tx_mode = TxMode::Select;
5296 }
5297 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
5298
5299 // Prediction reads no further than this, in each plane's own units --
5300 // see `Plane::true_width`/`true_height`.
5301 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
5302 // lane-hbd r4: `Picture.y/u/v` widened to `Vec<u16>` for the decoder's
5303 // sake (DPB reference slots, 10-bit output); the encoder stays 8-bit by
5304 // design (see `intra_predict_u8`'s doc comment), so narrow the source
5305 // once here.
5306 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
5307 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
5308 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
5309 let mut luma = Plane {
5310 source: &picture_y8,
5311 reconstruction: vec![128; picture_y8.len()],
5312 width: picture.width,
5313 height: picture.height,
5314 true_width,
5315 true_height,
5316 tile_x0: 0,
5317 tile_y0: 0,
5318 tile_x1: picture.width,
5319 tile_y1: picture.height,
5320 ctx: CoefCtxMap::default(),
5321 };
5322 let mut chroma = [
5323 Plane {
5324 source: &picture_u8,
5325 reconstruction: vec![128; picture_u8.len()],
5326 width: picture.width / 2,
5327 height: picture.height / 2,
5328 true_width: true_width / 2,
5329 true_height: true_height / 2,
5330 tile_x0: 0,
5331 tile_y0: 0,
5332 tile_x1: picture.width / 2,
5333 tile_y1: picture.height / 2,
5334 ctx: CoefCtxMap::default(),
5335 },
5336 Plane {
5337 source: &picture_v8,
5338 reconstruction: vec![128; picture_v8.len()],
5339 width: picture.width / 2,
5340 height: picture.height / 2,
5341 true_width: true_width / 2,
5342 true_height: true_height / 2,
5343 tile_x0: 0,
5344 tile_y0: 0,
5345 tile_x1: picture.width / 2,
5346 tile_y1: picture.height / 2,
5347 ctx: CoefCtxMap::default(),
5348 },
5349 ];
5350
5351 // The search trades a bit for the squared error it saves, in the units the
5352 // reconstruction is measured in: one step of the quantizer, squared.
5353 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
5354 let search = Search {
5355 base_q_idx,
5356 deadzone,
5357 lambda: lambda_scale() * key_lambda_factor() * step * step,
5358 modes,
5359 top_k: prune_top_k(),
5360 screen,
5361 };
5362
5363 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
5364 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
5365 // which may be fewer columns/rows than the padded picture has room for
5366 // -- a block whose origin sits past the true bound is not coded at all,
5367 // matching what a decoder derives from `frame_width`/`frame_height` and
5368 // so never visits either.
5369 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
5370 let (cols, rows) = (cols as usize, rows as usize);
5371 // The luma mode of the block above and of the block to the left, which is
5372 // what picks the CDF the next block's mode is coded against -- the same
5373 // bookkeeping the tile writer keeps, so that the search is costing the
5374 // symbol the writer will actually write.
5375 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
5376 // because a 32x32 block may be split into four 16x16 ones.
5377 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
5378 // This frame's tile grid (one tile unless the facade armed more).
5379 let layout =
5380 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
5381 header.tile_info = tile_info_of(&layout, 1);
5382 // The filter search re-decodes this frame's tiles; the decoder derives
5383 // every tile's own rect from this same `tile_info` (its `mi_col_starts`/
5384 // `mi_row_starts`), which is what makes the writer's rects and the
5385 // reader's the same rects.
5386 let header_tile_info = header.tile_info.clone();
5387 // lane-av1tsearch: the search runs once per TILE (`search_tiles`), not
5388 // once over the whole frame. Each tile job builds its own reconstruction
5389 // planes and its own `above_mode`/`left_mode` bands, which is also what
5390 // the tile writer reads -- a tile resets its neighbour contexts (spec
5391 // 5.11.1), so a block at a tile's left edge must cost its mode against
5392 // the default context, not against whatever the tile to its west left in
5393 // that row. At one tile the bands are the frame's, exactly as before.
5394 let (frame_width, frame_height) = (picture.width, picture.height);
5395 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
5396 let [cb, cr] = &mut chroma;
5397 let chroma_out = [
5398 crate::par::Shared::new(&mut cb.reconstruction),
5399 crate::par::Shared::new(&mut cr.reconstruction),
5400 ];
5401 let search_tile = |index: usize,
5402 fctx: &crate::decode::FrameCtx|
5403 -> Result<Vec<(usize, Superblock, Vec<u8>)>> {
5404 crate::tile::arm_pricing_cdfs(None, false);
5405 let rect = layout.rect(index);
5406 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
5407 let mut chroma = [
5408 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
5409 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
5410 ];
5411 clip_planes_to_tile(&mut luma, &mut chroma, rect);
5412 let mut above_mode = vec![DC_PRED; cols * 2];
5413 let mut left_mode = vec![DC_PRED; rows * 2];
5414 let mut ibc = allow_intrabc.then(|| {
5415 Ibc::new(
5416 (
5417 rect.mi_col0 as usize * 4,
5418 rect.mi_row0 as usize * 4,
5419 (rect.mi_col1 as usize * 4).min(true_width),
5420 (rect.mi_row1 as usize * 4).min(true_height),
5421 ),
5422 &picture_y8,
5423 frame_width,
5424 )
5425 });
5426 let mut coded: Vec<(usize, Superblock, Vec<u8>)> = Vec::new();
5427 for sb_row in rect.sb_row0 as usize..rect.sb_row1 as usize {
5428 for sb_col in rect.sb_col0 as usize..rect.sb_col1 as usize {
5429 let mut modes = Vec::with_capacity(4);
5430 // The quadrants of a superblock are coded in the order the decoder
5431 // walks them, which for a 64x64 split into 32x32 blocks is raster
5432 // order among the quadrants that are inside the frame.
5433 let mut blocks = Vec::with_capacity(4);
5434 for quadrant in 0..4 {
5435 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
5436 if col >= cols || row >= rows {
5437 continue;
5438 }
5439 let (x, y) = (col * BLOCK, row * BLOCK);
5440 let (c0, r0) = (col * 2, row * 2);
5441 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
5442
5443 // spec `decode_partition`'s hasRows/hasCols recomputed at this
5444 // 32x32 block's own half (see `crate::tile::has_half`): the
5445 // true frame edge can fall inside a quadrant a superblock-level
5446 // check already let through. A quadrant that fails either may
5447 // not be left whole; a 16x16 sub-block that fails either (once
5448 // split) is a leaf this writer has no rectangular transform
5449 // for, so the search must not pick a split that would need one.
5450 let (has_cols32, has_rows32) = (
5451 crate::tile::has_half(
5452 col as u32 * crate::tile::BLOCK_MI,
5453 crate::tile::BLOCK_MI,
5454 header.mi_cols,
5455 ),
5456 crate::tile::has_half(
5457 row as u32 * crate::tile::BLOCK_MI,
5458 crate::tile::BLOCK_MI,
5459 header.mi_rows,
5460 ),
5461 );
5462 let whole_legal = has_cols32 && has_rows32;
5463 // A 16x16 sub-block's own hasCols/hasRows (spec
5464 // `decode_partition`, recomputed at this leaf's own half):
5465 // either axis false is a straddling leaf this writer codes as
5466 // the 8x8 leaves that are inside it
5467 // (`crate::tile::write_leaf8`, lane-av1-rect r7). Both axes
5468 // false is the same split with the partition symbol inferred
5469 // rather than coded -- no rectangular transform is needed
5470 // (lane-av1rect).
5471 let sub_half = |sr: usize, sc: usize| {
5472 (
5473 crate::tile::has_half(
5474 sc as u32 * crate::tile::SUB_MI,
5475 crate::tile::SUB_MI,
5476 header.mi_cols,
5477 ),
5478 crate::tile::has_half(
5479 sr as u32 * crate::tile::SUB_MI,
5480 crate::tile::SUB_MI,
5481 header.mi_rows,
5482 ),
5483 )
5484 };
5485 // What the whole 32x32 costs, including the partition symbol
5486 // that says it is not split.
5487 let (whole, mut cost_whole) = code_square(
5488 &mut luma,
5489 &mut chroma,
5490 (x, y),
5491 BLOCK,
5492 &search,
5493 &mode_bits(above_mode[c0], left_mode[r0]),
5494 tx_select,
5495 ibc.as_mut(), fctx,
5496 );
5497 cost_whole += search.lambda * partition_bits(BLOCK, false);
5498 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
5499
5500 // What four 16x16 blocks cost instead, each searched against
5501 // the reconstruction the ones before it left.
5502 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
5503 let mut split = Vec::with_capacity(4);
5504 let mut cost_split = search.lambda
5505 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
5506 let mut split_modes = Vec::with_capacity(4);
5507 for sub in 0..4 {
5508 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
5509 // Same filter as the writer's `sub_positions` (spec
5510 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
5511 // return): a sub-block whose own origin sits past the
5512 // true frame is never coded, so it must not be searched
5513 // or pushed onto `split` either, or the writer's block
5514 // count will not match what it is prepared to name.
5515 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
5516 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
5517 {
5518 continue;
5519 }
5520 let (has_cols16, has_rows16) = sub_half(sr, sc);
5521 if has_cols16 && has_rows16 {
5522 let (block, cost) = code_square(
5523 &mut luma,
5524 &mut chroma,
5525 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
5526 SUB,
5527 &search,
5528 &mode_bits(above_mode[sc], left_mode[sr]),
5529 tx_select,
5530 ibc.as_mut(), fctx,
5531 );
5532 cost_split += cost;
5533 split_modes.push(block.mode);
5534 above_mode[sc] = block.mode;
5535 left_mode[sr] = block.mode;
5536 split.push(block);
5537 } else {
5538 // A straddling 16x16: two (or, at a true corner, one)
5539 // 8x8 leaves, in the raster order `write_leaf8`'s
5540 // caller expects. Both leaves cost against the SAME
5541 // enclosing-slot mode context (see
5542 // `crate::tile::write_leaf8`'s doc), and neither
5543 // updates `above_mode`/`left_mode` at this SUB slot --
5544 // the writer never does either, so the search must
5545 // not diverge from what it will actually read next.
5546 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
5547 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
5548 let mut leaves = Vec::with_capacity(2);
5549 for i in 0..4 {
5550 let leaf_x = x_sub + (i % 2) * 8;
5551 let leaf_y = y_sub + (i / 2) * 8;
5552 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
5553 continue;
5554 }
5555 let (leaf, cost) = code_square(
5556 &mut luma,
5557 &mut chroma,
5558 (leaf_x, leaf_y),
5559 8,
5560 &search,
5561 &leaf_mode_bits,
5562 tx_select,
5563 None, fctx,
5564 );
5565 cost_split += cost;
5566 split_modes.push(leaf.mode);
5567 leaves.push(leaf);
5568 }
5569 split.push(BlockCoeffs {
5570 eight: Some(leaves),
5571 ..BlockCoeffs::default()
5572 });
5573 }
5574 }
5575
5576 // A split whose subs are all whole 16x16 is a real quality
5577 // alternative to `whole`, exactly as before. Through r14, a
5578 // split carrying an 8x8-leaf sub was only ever forced
5579 // (`!whole_legal`), never chosen on cost, because the leaf
5580 // path was not yet proven against a real decoder; r15 proved
5581 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
5582 // the read path (`decode_leaf8`), so leaf8 can now win on
5583 // cost anywhere, same as any other split.
5584 if !whole_legal || (split_blocks && cost_split < cost_whole) {
5585 modes.extend_from_slice(&split_modes);
5586 blocks.push(Quadrant::Split(split));
5587 } else {
5588 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
5589 for cell in 0..2 {
5590 above_mode[c0 + cell] = whole.mode;
5591 left_mode[r0 + cell] = whole.mode;
5592 }
5593 modes.push(whole.mode);
5594 blocks.push(Quadrant::Whole(whole));
5595 }
5596 }
5597 coded.push((sb_row * sb_cols + sb_col, Superblock::Split(blocks), modes));
5598 }
5599 }
5600 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
5601 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
5602 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
5603 for (&out, tile) in chroma_out.iter().zip(&chroma) {
5604 copy_rect(
5605 out,
5606 &tile.reconstruction,
5607 frame_width / 2,
5608 x0 / 2,
5609 y0 / 2,
5610 x1.div_ceil(2),
5611 y1.div_ceil(2),
5612 );
5613 }
5614 Ok(coded)
5615 };
5616 let searched = search_tiles(layout.count(), fctx, search_tile)?;
5617 // Back into frame raster order: the tile writer indexes `superblocks` by
5618 // the frame's own superblock index, and `modes` is the coding order the
5619 // ablation drivers read.
5620 let mut in_order: Vec<Option<(Superblock, Vec<u8>)>> = (0..sb_cols * sb_rows).map(|_| None).collect();
5621 for (at, superblock, block_modes) in searched.into_iter().flatten() {
5622 in_order[at] = Some((superblock, block_modes));
5623 }
5624 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
5625 let mut modes = Vec::with_capacity(cols * rows);
5626 for slot in in_order {
5627 let (superblock, block_modes) = slot.expect("every superblock belongs to a tile");
5628 superblocks.push(superblock);
5629 modes.extend_from_slice(&block_modes);
5630 }
5631
5632 #[cfg(test)]
5633 record_predicted_bits(crate::tile::predicted_coeff_bits_sb(&superblocks, base_q_idx));
5634 // A key frame always starts from the defaults (`primary_ref_frame` is
5635 // `PRIMARY_REF_NONE`), and its header keeps `disable_frame_end_update_cdf`
5636 // set, so what it stores into the slots it refreshes is exactly those
5637 // defaults again (spec 7.20's `started_from` arm) -- the first inter
5638 // frame after it therefore starts from the defaults too.
5639 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
5640 let cdfs = crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx));
5641 let start_cdfs = CdfSnapshot(cdfs);
5642 // The luma restoration-unit grid this frame's `lr_params` implies
5643 // (`av1_lr_count_units` rounds to nearest, so a short last unit is
5644 // swallowed by the one before it), for the tile writer's own per-unit
5645 // walk.
5646 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
5647 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
5648 // Every tile is coded from this frame's OWN starting tables and leaves
5649 // its own end state behind (spec 5.11.1: each tile resets the CDFs, the
5650 // loop-restoration reference and its neighbour contexts), so the tiles
5651 // are independent of each other and of the order they are written in.
5652 let code_tiles = |bits: u8,
5653 sb_cols: usize,
5654 grid: &[u8],
5655 units: &[Option<crate::restoration::WienerInfo>]|
5656 -> Result<Vec<Vec<u8>>> {
5657 let (out, _) = write_tiles(layout.count(), usize::MAX, |index| {
5658 crate::tile::arm_cdef_idx(bits, sb_cols, grid.to_vec());
5659 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
5660 let mut cdfs = start_cdfs.0.clone();
5661 crate::tile::arm_screen(screen);
5662 crate::tile::arm_intrabc(allow_intrabc);
5663 crate::tile::arm_pricing_cdfs(None, false);
5664 let bytes = crate::tile::sb_coeff_key_frame_tile_cdfs(
5665 mi_cols,
5666 mi_rows,
5667 base_q_idx,
5668 &superblocks,
5669 tx_select,
5670 &mut cdfs,
5671 layout.rect(index),
5672 )?;
5673 Ok((bytes, None))
5674 })?;
5675 Ok(out)
5676 };
5677 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
5678 // spec 7.14 deblocking: pick this frame's `loop_filter_level` by handing
5679 // the tile just coded back to the decoder under each candidate (see
5680 // `crate::filter_search`), and keep the filtered picture that wins as
5681 // the reconstruction -- what a decoder outputs, and what the next
5682 // frame predicts from.
5683 pick_and_apply_filters(
5684 &mut header,
5685 &mut luma,
5686 &mut chroma,
5687 [&picture_y8, &picture_u8, &picture_v8],
5688 // spec 5.9.11/5.9.19/5.9.20: `allow_intrabc` forces deblocking, CDEF
5689 // and loop restoration off and codes none of their parameters
5690 // (frame.rs:194/210/252/272) -- there is no filter to search for, and
5691 // the encoder's reconstruction is already what a decoder produces.
5692 !allow_intrabc,
5693 &mut tiles,
5694 search.lambda,
5695 fctx,
5696 // Every re-code starts from this frame's OWN starting tables, never
5697 // from where the first write left them: the second tile is the same
5698 // symbol sequence plus new ones, so it must adapt from the same
5699 // point the decoder will.
5700 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
5701 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
5702 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
5703 crate::decode::decode_key_frame_tiles_lr(
5704 &payloads,
5705 &header_tile_info,
5706 h.mi_cols,
5707 h.mi_rows,
5708 base_q_idx,
5709 h.frame_width,
5710 h.frame_height,
5711 seq.enable_filter_intra,
5712 cdef,
5713 lf,
5714 tx_select,
5715 h.reduced_tx_set,
5716 h.allow_screen_content_tools,
5717 h.allow_intrabc,
5718 lr,
5719 fctx,
5720 )
5721 },
5722 )?;
5723 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
5724 header.tile_info.tile_size_bytes = tile_size_bytes;
5725 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
5726 let mut stream = temporal_delimiter();
5727 stream.extend_from_slice(&sequence_header_obu(&seq)?);
5728 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
5729
5730 let [u, v] = chroma;
5731 Ok(Encoded {
5732 stream,
5733 modes,
5734 inter_block_share: 0.0,
5735 reconstruction: Picture {
5736 width: luma.width,
5737 height: luma.height,
5738 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
5739 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
5740 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
5741 },
5742 tile,
5743 mi_cols: header.mi_cols,
5744 mi_rows: header.mi_rows,
5745 base_q_idx,
5746 tx_select,
5747 // A key frame codes no inter block, so no motion_mode symbol.
5748 switchable_motion_mode: false,
5749 screen,
5750 next_cdfs: start_cdfs.clone(),
5751 start_cdfs,
5752 loop_filter: header.loop_filter,
5753 cdef: header.cdef,
5754 loop_restoration: header.loop_restoration,
5755 allow_intrabc,
5756 })
5757}
5758
5759/// Chooses this frame's deblocking levels and CDEF strengths, writes them
5760/// into `header` and
5761/// replaces the frame's own region of the encoder's reconstruction with the
5762/// filtered picture the decoder produced under them
5763/// ([`crate::filter_search::pick_deblock`]).
5764///
5765/// `search == false` leaves the header at level 0 (deblocking off) and the
5766/// reconstruction untouched: the caller's stream is one this crate's own
5767/// decoder cannot read back, so there is nothing to search against.
5768///
5769/// # Errors
5770/// The decoder's own error, when it refuses the tile the encoder just wrote
5771/// -- that is an encoder defect, not a filter one, so it is propagated
5772/// rather than swallowed into "no deblocking".
5773fn pick_and_apply_filters(
5774 header: &mut FrameHeader,
5775 luma: &mut Plane<'_>,
5776 chroma: &mut [Plane<'_>; 2],
5777 source: [&[u8]; 3],
5778 search: bool,
5779 // The coded tiles, one payload per tile of the frame's grid, replaced in
5780 // place when the search chooses a per-64x64 `cdef_idx` list
5781 // (`cdef_bits > 0`): those literals live in the tile payloads, so every
5782 // tile is written a second time under `recode` and the winner
5783 // re-decoded from them.
5784 tiles: &mut Vec<Vec<u8>>,
5785 lambda: f64,
5786 fctx: &crate::decode::FrameCtx,
5787 recode: impl Fn(
5788 u8,
5789 usize,
5790 &[u8],
5791 &[Option<crate::restoration::WienerInfo>],
5792 ) -> Result<Vec<Vec<u8>>>,
5793 decode: impl Fn(
5794 &LoopFilterParams,
5795 &CdefParams,
5796 &FrameHeader,
5797 &[Vec<u8>],
5798 &LoopRestorationParams,
5799 ) -> Result<Picture>,
5800) -> Result<()> {
5801 if !search {
5802 return Ok(());
5803 }
5804 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
5805 let hdr = header.clone();
5806 // libaom `av1_pick_filter_level`'s sibling `av1_cdef_search`:
5807 // `cdef_damping = 3 + (base_qindex >> 6)`, never searched.
5808 let damping = 3 + (header.quantization.base_q_idx >> 6);
5809 let (cols32, rows32) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
5810 let (sb_cols, sb_rows) = (cols32.div_ceil(2) as usize, rows32.div_ceil(2) as usize);
5811 let none_lr = LoopRestorationParams::default();
5812 // Every candidate scores the same coded tile: decode it once and re-run
5813 // the filters alone for the rest (`crate::decode::FilterReplay`, 24% of
5814 // the encoder's profile before this). The per-64x64 error the CDEF
5815 // preset search reads comes off the REPLAYED picture, which is the same
5816 // picture a decode produces -- that is what the replay is pinned on.
5817 crate::decode::clear_filter_replay();
5818 // lane-av1fpar: the per-tile search is over, so every core is idle from
5819 // here to the end of the frame -- band each candidate's deblock/CDEF
5820 // replay, the capture decode's own filter chain and the loop-restoration
5821 // passes across the same workers the search used.
5822 let _bands = crate::par::override_filter_threads(crate::par::tile_threads());
5823 let ft = crate::par::timer(crate::par::S_FILTER);
5824 let search_result = crate::filter_search::pick_filters(
5825 |lf, cdef| {
5826 if let Some(picture) = crate::decode::replay_filters(lf, cdef, fctx) {
5827 return Ok(picture);
5828 }
5829 crate::decode::arm_filter_replay();
5830 let _t = crate::par::timer(crate::par::S_FIRST);
5831 decode(lf, cdef, &hdr, tiles, &none_lr)
5832 },
5833 source,
5834 luma.width,
5835 (fw, fh),
5836 damping,
5837 (sb_cols, sb_rows),
5838 lambda,
5839 );
5840 drop(ft);
5841 crate::decode::clear_filter_replay();
5842 let (lf, cdef, idx_grid, picture) = search_result?;
5843 header.loop_filter = lf;
5844 header.cdef = cdef;
5845 // spec 7.17: loop restoration. Its per-unit filters live in the TILE, not
5846 // in the frame header, so a re-decode under candidate parameters cannot
5847 // search them the way deblocking and CDEF are searched above. What the
5848 // decoder hands back instead is its own filter chain's intermediates
5849 // (`crate::decode::FrameCtx::capture_stages`), and the search runs on
5850 // those, through the decoder's own Wiener kernel.
5851 //
5852 // The capture rides the decode this stage was already going to do: the
5853 // re-decode of the `cdef_idx` tile when there is one, and otherwise one
5854 // decode of the tile as it stands. That decode's header still says
5855 // `RESTORE_NONE`, so the decoder takes no pre-CDEF snapshot and the
5856 // post-CDEF picture stands in for it at LR's 3-row stripe borders --
5857 // an approximation inside the SEARCH only; the reconstruction this
5858 // function ends up splicing is always a real decode of the real tile.
5859 let lr_on = restoration_enabled();
5860 fctx.capture_stages.set(lr_on);
5861 let mut filtered = if idx_grid.is_empty() {
5862 if lr_on {
5863 let _t = crate::par::timer(crate::par::S_CAPTURE);
5864 decode(&lf, &cdef, &hdr, tiles, &none_lr)?
5865 } else {
5866 picture
5867 }
5868 } else {
5869 let coded = recode(cdef.bits, sb_cols, &idx_grid, &[])?;
5870 let _t = crate::par::timer(crate::par::S_CAPTURE);
5871 let picture = decode(&lf, &cdef, &hdr, &coded, &none_lr)?;
5872 *tiles = coded;
5873 picture
5874 };
5875 fctx.capture_stages.set(false);
5876 let mut lr = LoopRestorationParams::default();
5877 if lr_on {
5878 let mut want = LoopRestorationParams {
5879 loop_restoration_size: [64, 64, 64],
5880 uses_lr: true,
5881 ..LoopRestorationParams::default()
5882 };
5883 want.frame_restoration_type[0] = ec_av1_syntax::RestorationType::Wiener;
5884 let lrt = crate::par::timer(crate::par::S_LR);
5885 let units = match crate::decode::take_filter_stages(fctx) {
5886 Some(stages) => crate::filter_search::pick_restoration(
5887 &stages,
5888 source[0],
5889 luma.width,
5890 (fw, fh),
5891 &want,
5892 lambda,
5893 fctx,
5894 ),
5895 None => Vec::new(),
5896 };
5897 // A frame no unit restores keeps `RESTORE_NONE` on every plane
5898 // rather than paying ~1 bit per 64x64 for a tile full of
5899 // `restore_wiener = 0` symbols (the BD gate saw exactly that on the
5900 // clip whose units never take a filter).
5901 drop(lrt);
5902 if units.iter().any(Option::is_some) {
5903 let coded = recode(cdef.bits, sb_cols, &idx_grid, &units)?;
5904 let _t = crate::par::timer(crate::par::S_CAPTURE);
5905 filtered = decode(&lf, &cdef, &hdr, &coded, &want)?;
5906 *tiles = coded;
5907 lr = want;
5908 }
5909 }
5910 header.loop_restoration = lr;
5911 let dec_cw = filtered.width.div_ceil(2);
5912 let (cw, ch) = (fw.div_ceil(2), fh.div_ceil(2));
5913 crate::filter_search::splice(&mut luma.reconstruction, luma.width, &filtered.y, filtered.width, fw, fh);
5914 crate::filter_search::splice(&mut chroma[0].reconstruction, chroma[0].width, &filtered.u, dec_cw, cw, ch);
5915 crate::filter_search::splice(&mut chroma[1].reconstruction, chroma[1].width, &filtered.v, dec_cw, cw, ch);
5916 Ok(())
5917}
5918
5919/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
5920/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
5921/// since every block this crate's inter tile writer codes is 32x32.
5922const SIZE_GROUP_32: usize = 3;
5923
5924/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
5925/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
5926/// stack this encoder builds is ever asked to predict against.
5927const LAST_FRAME: i8 = 1;
5928
5929/// What an inter frame's intra branch spends to name each of the thirteen
5930/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
5931/// context, since an inter frame's intra blocks do not read their
5932/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
5933/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
5934/// state, so it is built once per frame.
5935fn inter_mode_bits() -> [f64; 13] {
5936 std::array::from_fn(|mode| {
5937 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
5938 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
5939 } else {
5940 0.0
5941 };
5942 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
5943 + angle
5944 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
5945 })
5946}
5947
5948/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
5949/// [`mc::predict`] takes, in the units of the plane it predicts into.
5950///
5951/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
5952/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
5953/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
5954/// domain. `luma` picks which.
5955fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
5956 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
5957}
5958
5959/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
5960/// that module): the magnitude an `MV_CLASS_n` component's own bits start
5961/// counting from.
5962fn mv_class_base(class: usize) -> i32 {
5963 if class == 0 { 0 } else { 2i32 << (class + 2) }
5964}
5965
5966/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
5967/// `tile::mv_class_of`.
5968fn mv_class_of(z: i32) -> usize {
5969 let mut class = 0;
5970 while class < 10 && mv_class_base(class + 1) <= z {
5971 class += 1;
5972 }
5973 class
5974}
5975
5976/// What [`crate::tile::write_mv_component`] (private to that module) would
5977/// spend coding one non-zero motion vector component, against the same
5978/// static default CDFs the writer starts a frame from — the same
5979/// static-table approximation [`mode_bits`] costs the luma mode symbol
5980/// through, not the tile writer's own adapting state, which this encoder has
5981/// no way to read without duplicating it block for block.
5982///
5983/// Returns `None` when `diff` needs the eighth-pel precision this crate's
5984/// frames never carry (`allow_high_precision_mv` is always off), which is
5985/// what [`round_to_valid_mv`] exists to avoid ever happening.
5986fn mv_component_bits(diff: i32) -> Option<f64> {
5987 let mag = diff.unsigned_abs() as i32;
5988 let z = mag - 1;
5989 if z & 1 == 0 {
5990 return None;
5991 }
5992 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
5993 let class = mv_class_of(z);
5994 bits += symbol_bits(&cdf::MV_CLASS, class);
5995 let local = z - mv_class_base(class);
5996 if class == 0 {
5997 let bit = (local >> 3) & 1;
5998 let fr = (local >> 1) & 3;
5999 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
6000 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
6001 } else {
6002 let d = local >> 3;
6003 let fr = (local >> 1) & 3;
6004 for i in 0..class {
6005 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
6006 }
6007 bits += symbol_bits(&cdf::MV_FR, fr as usize);
6008 }
6009 Some(bits)
6010}
6011
6012/// Whether an extra reference (GOLDEN/ALTREF) is offered a `NEWMV` of its
6013/// own -- a second motion search per block against that reference's picture,
6014/// priced off that reference's own stack. `EC_AV1_MV_EXTRA_NEW=0` turns it
6015/// off in a test build (what the lane measured both arms with).
6016fn extra_ref_new_mv() -> bool {
6017 match std::env::var("EC_AV1_MV_EXTRA_NEW").ok() {
6018 Some(v) if cfg!(test) => v != "0",
6019 _ => EXTRA_REF_NEW_MV,
6020 }
6021}
6022
6023/// The seven `ref_frame_idx` order hints of a frame coded on this crate's own
6024/// flat slot plan (`inter_frame_headers_slots`): every reference but
6025/// `GOLDEN_FRAME` and `ALTREF_FRAME` reads the frame just coded,
6026/// `GOLDEN_FRAME` reads the GOP's key frame, and `ALTREF_FRAME` reads the
6027/// frame two back when there is one (otherwise it, too, names the key frame's
6028/// slot). Hints are 7-bit, the only `order_hint_bits` this encoder writes.
6029pub(crate) fn flat_order_hints(order_hint: u32, key_hint: u32, has_altref: bool) -> [u32; 7] {
6030 let last = order_hint.wrapping_sub(1) & 0x7f;
6031 let alt = if has_altref {
6032 order_hint.wrapping_sub(2) & 0x7f
6033 } else {
6034 key_hint
6035 };
6036 [last, last, last, key_hint, last, last, alt]
6037}
6038
6039/// Whether an inter frame carries `reference_select` (spec 5.9.22): the
6040/// header bit that lets each block choose between a single and a compound
6041/// reference. Off by default until compound prediction is measured to pay;
6042/// `EC_AV1_COMPOUND=1` arms it in a test build (which is what the BD gate
6043/// runs as), and every block still codes SINGLE, so the only cost is one
6044/// `comp_mode` symbol per inter block.
6045const REFERENCE_SELECT: bool = true;
6046
6047/// [`REFERENCE_SELECT`], with the test-build environment override.
6048pub(crate) fn reference_select() -> bool {
6049 match std::env::var("EC_AV1_COMPOUND").ok() {
6050 Some(v) if cfg!(test) => v != "0",
6051 _ => REFERENCE_SELECT,
6052 }
6053}
6054
6055/// [`tile::write_drl_idx`]'s cost against one stack: one `drl_mode` symbol
6056/// per entry past `start`, `1` to advance and `0` to stop, at most two.
6057fn drl_bits_for(stack: &MvStack, start: usize, target: usize) -> f64 {
6058 let mut bits = 0.0;
6059 let mut idx = start;
6060 while idx < start + 2 && stack.entries.len() > idx + 1 {
6061 let advance = idx < target;
6062 bits += symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[idx]], usize::from(advance));
6063 if !advance {
6064 break;
6065 }
6066 idx += 1;
6067 }
6068 bits
6069}
6070
6071/// The cheapest `(bits, drl index)` the `NEWMV` syntax can name `mv` with off
6072/// `stack`: each DRL entry is a different `PredMv` (spec 7.10.2.10
6073/// `assign_mv`), so the same vector costs a different residual from each.
6074fn best_new_mv_syntax(stack: &MvStack, mv: (i32, i32)) -> Option<(f64, u8)> {
6075 let mut best: Option<(f64, u8)> = None;
6076 for idx in 0..3usize {
6077 if idx > 0 && stack.entries.len() <= idx {
6078 break;
6079 }
6080 let base = stack.entries.get(idx).map_or(stack.pred_mv, |e| e.mv);
6081 if let Some(b) = mv_residual_bits(mv, base) {
6082 let total = b + drl_bits_for(stack, 0, idx);
6083 if best.is_none_or(|(t, _)| total < t) {
6084 best = Some((total, idx as u8));
6085 }
6086 }
6087 }
6088 best
6089}
6090
6091/// The starting points [`motion::search`] gets besides `stack.pred_mv`: the
6092/// zero vector and the stack's own candidates. A neighbour block's vector is
6093/// where this block's motion most often already is, which is what pays for
6094/// the extra starting points (measured on the BD gate: -0.9/-0.8/-0.0 points
6095/// vs libaom for 0.2 s off a 6 s ladder).
6096fn mv_seeds(stack: &MvStack) -> ([(i32, i32); 4], usize) {
6097 let mut seeds = [(0, 0); 4];
6098 let mut n = 1;
6099 for e in stack.entries.iter().take(3) {
6100 seeds[n] = e.mv;
6101 n += 1;
6102 }
6103 (seeds, n)
6104}
6105
6106/// What [`crate::tile::write_mv`] (private to that module) would spend
6107/// coding `mv` as a residual against `pred`: the joint symbol naming which
6108/// components differ, then each differing component. `None` under the same
6109/// condition [`mv_component_bits`] returns `None`.
6110/// How many frames back `ref_frame` sits from the frame being coded, off the
6111/// order hints [`crate::tile::arm_order_hints`] armed for it. `LAST_FRAME` is
6112/// 1 in this encoder's GOP; `GOLDEN`/`ALTREF` can be much further, which is
6113/// what [`crate::motion::search`] scales its starting step by.
6114fn ref_distance(ref_frame: i8) -> u32 {
6115 let (bits, order_hint, hints) = crate::tile::order_hints();
6116 let i = (ref_frame - crate::mvstack::LAST_FRAME).clamp(0, 6) as usize;
6117 let d = crate::motion_field::get_relative_dist(bits, order_hint, hints[i])
6118 .unsigned_abs()
6119 .max(1);
6120 if crate::envflags::env_flag!("EC_TRACE_DIST") {
6121 eprintln!("EC_DIST ref={ref_frame} bits={bits} oh={order_hint} hint={} d={d}", hints[i]);
6122 }
6123 d
6124}
6125
6126fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
6127 let diff = (mv.0 - pred.0, mv.1 - pred.1);
6128 let joint = match (diff.0 != 0, diff.1 != 0) {
6129 (false, false) => 0,
6130 (false, true) => 1,
6131 (true, false) => 2,
6132 (true, true) => 3,
6133 };
6134 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
6135 for d in [diff.0, diff.1] {
6136 if d != 0 {
6137 bits += mv_component_bits(d)?;
6138 }
6139 }
6140 Some(bits)
6141}
6142
6143/// Rounds `mv` so that its residual against `pred` is one
6144/// [`crate::tile::write_mv_component`] can actually code: each component's
6145/// difference is either zero or has an even magnitude (the eighth-pel bit
6146/// `allow_high_precision_mv` off always infers as one forces the coded
6147/// magnitude odd one step further in, which comes out even here since this
6148/// crate's motion search works in whole units of that same step). Rounding
6149/// down keeps every coded MV — and so every `nearest_mv` a later block's
6150/// stack votes with — built from an even displacement from `(0, 0)`, so the
6151/// invariant holds without this function seeing the whole stack.
6152fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
6153 let round = |m: i32, p: i32| {
6154 let diff = m - p;
6155 let mag = diff.unsigned_abs() as i32;
6156 let even = mag - mag % 2;
6157 if even == 0 {
6158 p
6159 } else {
6160 p + even * diff.signum()
6161 }
6162 };
6163 (round(mv.0, pred.0), round(mv.1, pred.1))
6164}
6165
6166/// Predicts one `side`-square block by motion compensation from `reference`
6167/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
6168#[allow(clippy::too_many_arguments)]
6169fn mc_trial(
6170 plane: &Plane,
6171 x: usize,
6172 y: usize,
6173 side: usize,
6174 mv: (i32, i32),
6175 luma: bool,
6176 reference: &[u16],
6177 stride: usize,
6178 ref_width: usize,
6179 ref_height: usize,
6180 skip: bool,
6181 base_q_idx: u8,
6182 deadzone: f64,
6183 set: TxbSet, fctx: &crate::decode::FrameCtx,
6184) -> Trial {
6185 let x_q4 = mv_to_q4(x, mv.1, luma);
6186 let y_q4 = mv_to_q4(y, mv.0, luma);
6187 // lane-hbd r4: `reference` (a DPB `Picture`'s plane) is `u16` now that
6188 // `Picture` is widened; `prediction`/the encoder stay `u8` (encoder is
6189 // 8-bit only this round, see `intra_predict_u8`'s doc comment).
6190 // lane-av1speed: both buffers are per-candidate scratch on the hottest
6191 // path in the encoder, so they live on the stack -- `side` is at most
6192 // `BLOCK` (32) for luma and half that for chroma. Two heap allocations
6193 // per motion-compensated trial otherwise.
6194 let mut prediction16 = [0u16; BLOCK * BLOCK];
6195 let prediction16 = &mut prediction16[..side * side];
6196 mc::predict(
6197 reference,
6198 stride,
6199 ref_width,
6200 ref_height,
6201 x_q4,
6202 y_q4,
6203 side,
6204 side,
6205 prediction16, fctx,
6206 );
6207 let mut prediction = [0u8; BLOCK * BLOCK];
6208 let prediction = &mut prediction[..side * side];
6209 for (dst, &src) in prediction.iter_mut().zip(prediction16.iter()) {
6210 *dst = src as u8;
6211 }
6212 plane.code_from_prediction(x, y, side, prediction, skip, base_q_idx, deadzone, set)
6213}
6214
6215/// [`mc_trial`]'s compound counterpart (spec 7.11.3.1's compound path): both
6216/// references predict into the `CONV_BUF` intermediate domain
6217/// ([`mc::predict_compound_intermediate`]) and are blended by
6218/// [`mc::combine_compound`] at the simple-average split `(8, 8)` -- exactly
6219/// what a decoder computes for a `comp_group_idx == 0`, `compound_idx == 1`
6220/// block, so the encoder's reconstruction is the decoder's.
6221#[allow(clippy::too_many_arguments)]
6222fn mc_trial_compound(
6223 plane: &Plane,
6224 x: usize,
6225 y: usize,
6226 side: usize,
6227 (mv0, mv1): ((i32, i32), (i32, i32)),
6228 luma: bool,
6229 ref0: (&[u16], usize, usize, usize),
6230 ref1: (&[u16], usize, usize, usize),
6231 base_q_idx: u8,
6232 deadzone: f64,
6233 set: TxbSet, fctx: &crate::decode::FrameCtx,
6234) -> Trial {
6235 let mut inter0 = [0i32; BLOCK * BLOCK];
6236 let mut inter1 = [0i32; BLOCK * BLOCK];
6237 let (inter0, inter1) = (&mut inter0[..side * side], &mut inter1[..side * side]);
6238 for (mv, r, dst) in [(mv0, ref0, &mut *inter0), (mv1, ref1, &mut *inter1)] {
6239 mc::predict_compound_intermediate(
6240 r.0,
6241 r.1,
6242 r.2,
6243 r.3,
6244 mv_to_q4(x, mv.1, luma),
6245 mv_to_q4(y, mv.0, luma),
6246 mc::REF_NO_SCALE,
6247 side,
6248 side,
6249 mc::InterpFilterKind::Regular,
6250 mc::InterpFilterKind::Regular,
6251 dst,
6252 );
6253 }
6254 let mut blended16 = [0u16; BLOCK * BLOCK];
6255 let blended16 = &mut blended16[..side * side];
6256 mc::combine_compound(inter0, inter1, 8, 8, blended16, fctx);
6257 let mut prediction = [0u8; BLOCK * BLOCK];
6258 let prediction = &mut prediction[..side * side];
6259 for (dst, &src) in prediction.iter_mut().zip(blended16.iter()) {
6260 *dst = src as u8;
6261 }
6262 plane.code_from_prediction(x, y, side, prediction, false, base_q_idx, deadzone, set)
6263}
6264
6265/// Codes one 32x32 block of an inter frame as whichever costs least of: each
6266/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
6267/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
6268/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
6269/// coding a real residual (`skip: false`) whenever one prices out cheaper
6270/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
6271/// missing inter `tx_type` symbol (the desync this function's candidates
6272/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
6273/// fixed.
6274///
6275/// The symbol costs this ranks candidates by use fixed contexts (0) for
6276/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
6277/// contexts for those come from its own neighbour bookkeeping
6278/// (`tile::Neighbours`), which is private to that module and not worth
6279/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
6280/// `drl_mode` contexts come straight from `stack`, which is exact, because
6281/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
6282/// the tile writer derives from the same grid state.
6283#[allow(clippy::too_many_arguments)]
6284fn search_inter_block(
6285 luma: &mut Plane,
6286 chroma: &mut [Plane; 2],
6287 (x, y): (usize, usize),
6288 search: &Search,
6289 mode_bits: &[f64; 13],
6290 reference: &Picture,
6291 stack: &MvStack,
6292 // `GOLDEN_FRAME`: the key frame's own reconstruction, held in DPB slot 1
6293 // for the whole GOP, with the stack this block derives against it. Only
6294 // its two search-free modes are priced (`NEARESTMV`, `GLOBALMV`) -- a
6295 // second motion search would double the wall of the stage that already
6296 // owns most of it.
6297 extra: &[(i8, &Picture, &MvStack)],
6298 // The COMPOUND stack of each `LAST_FRAME` + extra-reference pair, built by
6299 // the caller off the same MI grid the tile writer will (empty unless the
6300 // frame carries `reference_select`).
6301 compound: &[(i8, &Picture, crate::mvstack::CompoundMvStack)],
6302 // lane-av1obmc: the mi grid this search's neighbours were published into
6303 // (`record_mi`) and this block's own place in it -- what the OBMC
6304 // candidate's eligibility walk and neighbour plan read, the same state
6305 // the tile writer will read when it codes the `motion_mode` symbol.
6306 grid: &MiGrid,
6307 (mi_row, mi_col): (usize, usize),
6308 (mi_rows, mi_cols): (usize, usize),
6309 fctx: &crate::decode::FrameCtx,
6310) -> (BlockCoeffs, f64) {
6311 // `luma_set` is the INTRA candidates' table; the two inter candidates
6312 // below price their coefficients through `TxbSet::Luma32Inter`, which is
6313 // what `sb_coeff_inter_frame_tile` codes an inter block with (it carries
6314 // the inter `tx_type` symbol `Luma32` has no table for -- lane-av1rd1).
6315 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
6316 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height, fctx);
6317
6318 // skip / intra_inter symbol costs at a fixed context -- see this
6319 // function's doc comment.
6320 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
6321 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
6322 // `write_single_ref`'s own tree, at the fixed context this pricer uses
6323 // for every neighbour-derived symbol: LAST is p1=0,p3=0,p4=0 and GOLDEN
6324 // p1=0,p3=1,p5=1.
6325 let single_ref_bits = |ref_frame: i8| {
6326 symbol_bits(&cdf::SINGLE_REF[0][0], 0)
6327 + if ref_frame == crate::mvstack::GOLDEN_FRAME {
6328 symbol_bits(&cdf::SINGLE_REF[0][2], 1) + symbol_bits(&cdf::SINGLE_REF[0][4], 1)
6329 } else {
6330 symbol_bits(&cdf::SINGLE_REF[0][2], 0) + symbol_bits(&cdf::SINGLE_REF[0][3], 0)
6331 }
6332 };
6333
6334 struct Candidate {
6335 cost: f64,
6336 luma: Trial,
6337 u: Trial,
6338 v: Trial,
6339 mode: u8,
6340 skip: bool,
6341 inter: Option<InterInfo>,
6342 /// The mode/mv syntax this candidate pays for, apart from its
6343 /// residual -- what the OBMC candidate below has to re-pay when it
6344 /// re-prices the winner's prediction.
6345 mode_bits: f64,
6346 }
6347 let mut best: Option<Candidate> = None;
6348 let mut consider = |candidate: Candidate| {
6349 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
6350 best = Some(candidate);
6351 }
6352 };
6353
6354 // The chroma trial an intra candidate prices does not depend on `mode`
6355 // at all -- both planes always code `DC_PRED` here (a coding choice this
6356 // search inherited, not this loop's to second-guess) at the same `reach:
6357 // Reach::none()` -- so it is the same call with the same inputs on every
6358 // one of the thirteen iterations below; run it once and reuse the result
6359 // rather than repeat an already-priced transform/quantize/entropy call
6360 // twelve times for nothing (bit-identical: the value each iteration
6361 // reads back is exactly what it used to recompute).
6362 let u_trial = chroma[0].trial(
6363 At {
6364 x: x / 2,
6365 y: y / 2,
6366 side: BLOCK / 2,
6367 reach: Reach::none(),
6368 set: chroma_set,
6369 },
6370 DC_PRED,
6371 search.base_q_idx,
6372 search.deadzone, fctx,
6373 );
6374 let v_trial = chroma[1].trial(
6375 At {
6376 x: x / 2,
6377 y: y / 2,
6378 side: BLOCK / 2,
6379 reach: Reach::none(),
6380 set: chroma_set,
6381 },
6382 DC_PRED,
6383 search.base_q_idx,
6384 search.deadzone, fctx,
6385 );
6386
6387 let intra_modes: Vec<u8> = match search.top_k {
6388 Some(k) if k < search.modes.len() => {
6389 let scored = luma.intra_scores(
6390 At {
6391 x,
6392 y,
6393 side: BLOCK,
6394 reach,
6395 set: luma_set,
6396 },
6397 search.modes,
6398 mode_bits,
6399 search.lambda, fctx,
6400 );
6401 prune_by_sad(search.modes, scored, k)
6402 }
6403 _ => search.modes.to_vec(),
6404 };
6405 census_add(5, 1);
6406 census_add(6, intra_modes.len());
6407 for &mode in &intra_modes {
6408 let luma_trial = luma.trial(
6409 At {
6410 x,
6411 y,
6412 side: BLOCK,
6413 reach,
6414 set: luma_set,
6415 },
6416 mode,
6417 search.base_q_idx,
6418 search.deadzone, fctx,
6419 );
6420 let u = u_trial.clone();
6421 let v = v_trial.clone();
6422 let cost = luma_trial.sse
6423 + u.sse
6424 + v.sse
6425 + search.lambda
6426 * (luma_trial.bits
6427 + u.bits
6428 + v.bits
6429 + mode_bits[usize::from(mode)]
6430 + skip_bits(false)
6431 + intra_inter_bits(false));
6432 consider(Candidate {
6433 cost,
6434 luma: luma_trial,
6435 u,
6436 v,
6437 mode,
6438 skip: false,
6439 inter: None,
6440 mode_bits: mode_bits[usize::from(mode)],
6441 });
6442 }
6443
6444 // The reference frame buffer a spec decoder holds is exactly the true
6445 // (unpadded) coded extent -- a superblock whose partition stops early at
6446 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
6447 // beyond it, so those samples are never part of the decoded picture.
6448 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
6449 // reference sample position clamp), not to this crate's own
6450 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
6451 // here would let a fractional-pel read past the true edge pick up this
6452 // encoder's own uncoded padding instead of the true edge's replicated
6453 // value a decoder computes.
6454 let ref_luma = (
6455 &reference.y,
6456 reference.width,
6457 luma.true_width,
6458 luma.true_height,
6459 );
6460 let ref_u = (
6461 &reference.u,
6462 reference.width / 2,
6463 chroma[0].true_width,
6464 chroma[0].true_height,
6465 );
6466 let ref_v = (
6467 &reference.v,
6468 reference.width / 2,
6469 chroma[1].true_width,
6470 chroma[1].true_height,
6471 );
6472 // Every single-reference mode the writer can code (spec 5.11.24's symbol
6473 // chain, mirrored by `tile::write_inter_mode`), priced with the static
6474 // CDFs at this block's own stack contexts. A candidate is a motion
6475 // vector plus the cheapest syntax that reaches it, so two modes landing
6476 // on the same vector share one set of trials: the added modes cost
6477 // mode-bit arithmetic, not another motion compensation.
6478 let not_new = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1);
6479 let not_zero = symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1);
6480 // `tile::write_drl_idx`'s cost: one `drl_mode` symbol per stack entry
6481 // past `start`, `1` to advance and `0` to stop, at most two. A `target`
6482 // the loop cannot reach is never offered below -- every candidate's
6483 // index is one this same loop walks to.
6484 let drl_bits = |start: usize, target: usize| drl_bits_for(stack, start, target);
6485 let last_ref_bits = single_ref_bits(crate::mvstack::LAST_FRAME);
6486 let mut cands: Vec<((i32, i32), f64, InterInfo)> = vec![
6487 (
6488 stack.nearest_mv,
6489 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0),
6490 InterInfo {
6491 ref1: None,
6492 mv1: (0, 0),
6493 ref_frame: crate::mvstack::LAST_FRAME,
6494 mode: InterMode::NearestMv,
6495 mv: stack.nearest_mv,
6496 ref_mv_idx: 0,
6497 },
6498 ),
6499 // GLOBALMV is the identity model's zero vector -- this encoder writes
6500 // no `gm_params` -- and the cheapest syntax of the four on the static
6501 // content where that vector is also the right one.
6502 (
6503 (0, 0),
6504 last_ref_bits + not_new + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 0),
6505 InterInfo {
6506 ref1: None,
6507 mv1: (0, 0),
6508 ref_frame: crate::mvstack::LAST_FRAME,
6509 mode: InterMode::GlobalMv,
6510 mv: (0, 0),
6511 ref_mv_idx: 0,
6512 },
6513 ),
6514 ];
6515 let near_bits =
6516 last_ref_bits + not_new + not_zero + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 1);
6517 for idx in 1..=2usize {
6518 if let Some(e) = stack.entries.get(idx) {
6519 cands.push((
6520 e.mv,
6521 near_bits + drl_bits(1, idx),
6522 InterInfo {
6523 ref1: None,
6524 mv1: (0, 0),
6525 ref_frame: crate::mvstack::LAST_FRAME,
6526 mode: InterMode::NearMv,
6527 mv: e.mv,
6528 ref_mv_idx: idx as u8,
6529 },
6530 ));
6531 }
6532 }
6533
6534 let source_block = luma.source_block(x, y, BLOCK);
6535 let (seeds, seed_n) = mv_seeds(stack);
6536 #[cfg(test)]
6537 let t = std::time::Instant::now();
6538 let found = motion::search(
6539 ref_luma.0,
6540 ref_luma.1,
6541 ref_luma.2,
6542 ref_luma.3,
6543 &source_block,
6544 x,
6545 y,
6546 BLOCK,
6547 BLOCK,
6548 stack.pred_mv,
6549 &seeds[..seed_n],
6550 search.lambda, fctx,
6551 1,
6552 );
6553 #[cfg(test)]
6554 stage_add(0, t.elapsed());
6555 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
6556 // Each DRL entry is a different `PredMv` (spec 7.10.2.10 `assign_mv`), so
6557 // the same vector costs a different residual from each: take the index
6558 // whose residual plus DRL bits is cheapest, not entry 0 by default.
6559 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(stack, mv) {
6560 cands.push((
6561 mv,
6562 last_ref_bits + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0) + bits,
6563 InterInfo {
6564 ref1: None,
6565 mv1: (0, 0),
6566 ref_frame: crate::mvstack::LAST_FRAME,
6567 mode: InterMode::NewMv,
6568 mv,
6569 ref_mv_idx,
6570 },
6571 ));
6572 }
6573
6574 // Each extra reference's own `NEWMV` vector, for the compound
6575 // `NEW_NEWMV` candidate below to pair with `LAST`'s.
6576 let mut extra_new_mvs: Vec<(i8, (i32, i32))> = Vec::new();
6577 for &(ref_frame, g, gstack) in extra {
6578 let g_ref_bits = single_ref_bits(ref_frame);
6579 let g_not_new = symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 1);
6580 cands.push((
6581 gstack.nearest_mv,
6582 g_ref_bits
6583 + g_not_new
6584 + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 1)
6585 + symbol_bits(&cdf::REF_MV[gstack.ref_mv_ctx], 0),
6586 InterInfo {
6587 ref1: None,
6588 mv1: (0, 0),
6589 ref_frame,
6590 mode: InterMode::NearestMv,
6591 mv: gstack.nearest_mv,
6592 ref_mv_idx: 0,
6593 },
6594 ));
6595 cands.push((
6596 (0, 0),
6597 g_ref_bits + g_not_new + symbol_bits(&cdf::ZERO_MV[gstack.zero_mv_ctx], 0),
6598 InterInfo {
6599 ref1: None,
6600 mv1: (0, 0),
6601 ref_frame,
6602 mode: InterMode::GlobalMv,
6603 mv: (0, 0),
6604 ref_mv_idx: 0,
6605 },
6606 ));
6607 // A motion search of this reference's own: without it, GOLDEN/ALTREF
6608 // can only be coded at a vector some neighbour already found, which
6609 // is why they carried a third of the inter blocks at their two
6610 // search-free modes alone.
6611 // The search is skipped when this reference's own NEARESTMV already
6612 // prices out `margin` times better than LAST's best vector does --
6613 // one candidate evaluation (`motion::cost_at`) standing in for a
6614 // whole search of ~50.
6615 let margin = extra_new_skip_margin();
6616 let skip_search = extra_ref_new_mv()
6617 && margin > 0.0
6618 && motion::cost_at(
6619 &g.y,
6620 g.width,
6621 luma.true_width,
6622 luma.true_height,
6623 &source_block,
6624 x,
6625 y,
6626 BLOCK,
6627 BLOCK,
6628 gstack.nearest_mv,
6629 gstack.pred_mv,
6630 search.lambda,
6631 fctx,
6632 ) * margin
6633 <= found.cost;
6634 if extra_ref_new_mv() && !skip_search {
6635 let (gseeds, gn) = mv_seeds(gstack);
6636 #[cfg(test)]
6637 let t = std::time::Instant::now();
6638 let gfound = motion::search(
6639 &g.y,
6640 g.width,
6641 luma.true_width,
6642 luma.true_height,
6643 &source_block,
6644 x,
6645 y,
6646 BLOCK,
6647 BLOCK,
6648 gstack.pred_mv,
6649 &gseeds[..gn],
6650 search.lambda, fctx,
6651 ref_distance(ref_frame),
6652 );
6653 #[cfg(test)]
6654 stage_add(0, t.elapsed());
6655 let gmv = round_to_valid_mv(gfound.mv, gstack.pred_mv);
6656 extra_new_mvs.push((ref_frame, gmv));
6657 if let Some((bits, ref_mv_idx)) = best_new_mv_syntax(gstack, gmv) {
6658 cands.push((
6659 gmv,
6660 g_ref_bits + symbol_bits(&cdf::NEW_MV[gstack.new_mv_ctx], 0) + bits,
6661 InterInfo {
6662 ref1: None,
6663 mv1: (0, 0),
6664 ref_frame,
6665 mode: InterMode::NewMv,
6666 mv: gmv,
6667 ref_mv_idx,
6668 },
6669 ));
6670 }
6671 }
6672 }
6673
6674 // The compound candidates (spec 5.11.24's `INTER_COMPOUND_MODES`), one
6675 // trial set each: both references predict the block and the two
6676 // predictions are averaged, which is what pays on content where neither
6677 // reference alone is right. Priced with the same static-CDF approximation
6678 // the single-reference candidates use, plus the compound-only symbols
6679 // (`comp_mode`, the reference-pair tree, `comp_group_idx`/`compound_idx`).
6680 // The two compound-mode arms, each measured alone on the BD gate before
6681 // it could default on. `NEAREST_NEWMV`/`NEW_NEARESTMV` keep (-1.0/-0.8
6682 // vs libaom, screen byte-identical) and ship on; `NEAR_NEARMV` does not
6683 // (+0.5/-0.2/flat) and stays behind `EC_AV1_COMP_NEARNEAR`.
6684 let near_near = crate::envflags::env_flag!("EC_AV1_COMP_NEARNEAR");
6685 let half_new = true;
6686 for (ref1, g, cstack) in compound {
6687 let (ref1, g) = (*ref1, *g);
6688 let uni = (crate::mvstack::BWDREF_FRAME..=crate::mvstack::ALTREF_FRAME)
6689 .contains(&ref1);
6690 let pair_bits = symbol_bits(&cdf::COMP_MODE[0], 1)
6691 + if uni {
6692 // LAST + a backward reference: `comp_ref_type` = bidirectional,
6693 // `comp_ref` LAST, `comp_bwdref` ALTREF.
6694 symbol_bits(&cdf::COMP_REF_TYPE[0], 1)
6695 + symbol_bits(&cdf::COMP_REF[0][0], 0)
6696 + symbol_bits(&cdf::COMP_REF[0][1], 0)
6697 + symbol_bits(&cdf::COMP_BWDREF[0][0], 1)
6698 } else {
6699 // LAST + GOLDEN: unidirectional, `uni_comp_ref` p0/p1/p2.
6700 symbol_bits(&cdf::COMP_REF_TYPE[0], 0)
6701 + symbol_bits(&cdf::UNI_COMP_REF[0][0], 0)
6702 + symbol_bits(&cdf::UNI_COMP_REF[0][1], 1)
6703 + symbol_bits(&cdf::UNI_COMP_REF[0][2], 1)
6704 };
6705 let mode_ctx =
6706 cdf::COMPOUND_MODE_CTX_MAP[cstack.ref_mv_ctx >> 1][cstack.new_mv_ctx.min(4)];
6707 let mode_bits_of =
6708 |mode: usize| pair_bits + symbol_bits(&cdf::INTER_COMPOUND_MODE[mode_ctx], mode);
6709 let mut ccands: Vec<(((i32, i32), (i32, i32)), f64, InterInfo)> = vec![
6710 (
6711 cstack.nearest_mv,
6712 mode_bits_of(0),
6713 InterInfo {
6714 ref_frame: crate::mvstack::LAST_FRAME,
6715 mode: InterMode::NearestNearestMv,
6716 mv: cstack.nearest_mv.0,
6717 mv1: cstack.nearest_mv.1,
6718 ref1: Some(ref1),
6719 ref_mv_idx: 0,
6720 },
6721 ),
6722 (
6723 ((0, 0), (0, 0)),
6724 mode_bits_of(6),
6725 InterInfo {
6726 ref_frame: crate::mvstack::LAST_FRAME,
6727 mode: InterMode::GlobalGlobalMv,
6728 mv: (0, 0),
6729 mv1: (0, 0),
6730 ref1: Some(ref1),
6731 ref_mv_idx: 0,
6732 },
6733 ),
6734 ];
6735 // `NEAR_NEARMV`: both halves off compound stack entry 1 (the
6736 // decoder's `ref_mv_idx = 0`), which costs one DRL symbol whenever
6737 // the stack is deep enough for that walk to read one.
6738 if let Some(e) = cstack.entries.get(1).filter(|_| near_near) {
6739 let drl = if cstack.entries.len() > 2 {
6740 symbol_bits(&cdf::DRL_MODE[cstack.drl_ctx[1]], 0)
6741 } else {
6742 0.0
6743 };
6744 ccands.push((
6745 (e.mv0, e.mv1),
6746 mode_bits_of(1) + drl,
6747 InterInfo {
6748 ref_frame: crate::mvstack::LAST_FRAME,
6749 mode: InterMode::NearNearMv,
6750 mv: e.mv0,
6751 mv1: e.mv1,
6752 ref1: Some(ref1),
6753 ref_mv_idx: 0,
6754 },
6755 ));
6756 }
6757 // The half-new modes and `NEW_NEWMV`, all seeded from the two
6758 // single-reference searches this block already ran -- no joint search
6759 // of its own. Every residual is priced against stack entry 0, which
6760 // is what `assign_compound_mv` predicts from at `ref_mv_idx = 0`.
6761 let cbase = cstack
6762 .entries
6763 .first()
6764 .map_or(cstack.nearest_mv, |e| (e.mv0, e.mv1));
6765 if let Some(b0) = mv_residual_bits(mv, cbase.0).filter(|_| half_new) {
6766 ccands.push((
6767 (mv, cstack.nearest_mv.1),
6768 mode_bits_of(3) + b0,
6769 InterInfo {
6770 ref_frame: crate::mvstack::LAST_FRAME,
6771 mode: InterMode::NewNearestMv,
6772 mv,
6773 mv1: cstack.nearest_mv.1,
6774 ref1: Some(ref1),
6775 ref_mv_idx: 0,
6776 },
6777 ));
6778 }
6779 if let Some(&(_, mv1)) = extra_new_mvs.iter().find(|(r, _)| *r == ref1) {
6780 if let Some(b1) = mv_residual_bits(mv1, cbase.1).filter(|_| half_new) {
6781 ccands.push((
6782 (cstack.nearest_mv.0, mv1),
6783 mode_bits_of(2) + b1,
6784 InterInfo {
6785 ref_frame: crate::mvstack::LAST_FRAME,
6786 mode: InterMode::NearestNewMv,
6787 mv: cstack.nearest_mv.0,
6788 mv1,
6789 ref1: Some(ref1),
6790 ref_mv_idx: 0,
6791 },
6792 ));
6793 }
6794 let base = cbase;
6795 if let (Some(b0), Some(b1)) = (
6796 mv_residual_bits(mv, base.0),
6797 mv_residual_bits(mv1, base.1),
6798 ) {
6799 ccands.push((
6800 (mv, mv1),
6801 mode_bits_of(7) + b0 + b1,
6802 InterInfo {
6803 ref_frame: crate::mvstack::LAST_FRAME,
6804 mode: InterMode::NewNewMv,
6805 mv,
6806 mv1,
6807 ref1: Some(ref1),
6808 ref_mv_idx: 0,
6809 },
6810 ));
6811 }
6812 }
6813 ccands.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
6814 ccands.dedup_by_key(|c| c.0);
6815 let g_luma = (g.y.as_slice(), g.width, luma.true_width, luma.true_height);
6816 let g_u = (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height);
6817 let g_v = (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height);
6818 for (mvs, bits, info) in ccands {
6819 let luma_trial = mc_trial_compound(
6820 luma, x, y, BLOCK, mvs, true,
6821 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3), g_luma,
6822 search.base_q_idx, search.deadzone, TxbSet::Luma32Inter, fctx,
6823 );
6824 let u = mc_trial_compound(
6825 &chroma[0], x / 2, y / 2, BLOCK / 2, mvs, false,
6826 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3), g_u,
6827 search.base_q_idx, search.deadzone, chroma_set, fctx,
6828 );
6829 let v = mc_trial_compound(
6830 &chroma[1], x / 2, y / 2, BLOCK / 2, mvs, false,
6831 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3), g_v,
6832 search.base_q_idx, search.deadzone, chroma_set, fctx,
6833 );
6834 let skip = luma_trial.levels.iter().all(|&l| l == 0)
6835 && u.levels.iter().all(|&l| l == 0)
6836 && v.levels.iter().all(|&l| l == 0);
6837 let cost = luma_trial.sse
6838 + u.sse
6839 + v.sse
6840 + search.lambda
6841 * (skip_bits(skip)
6842 + intra_inter_bits(true)
6843 + bits
6844 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
6845 consider(Candidate {
6846 cost,
6847 luma: luma_trial,
6848 u,
6849 v,
6850 mode: DC_PRED,
6851 skip,
6852 mode_bits: bits,
6853 inter: Some(info),
6854 });
6855 }
6856 }
6857
6858 // One trial set per distinct (reference, vector) pair: sort, cheapest
6859 // syntax first, and drop the rest of each pair's run.
6860 cands.sort_by(|a, b| {
6861 (a.2.ref_frame, a.0)
6862 .cmp(&(b.2.ref_frame, b.0))
6863 .then(a.1.total_cmp(&b.1))
6864 });
6865 cands.dedup_by_key(|c| (c.2.ref_frame, c.0));
6866 census_add(7, cands.len());
6867 {
6868 for (mv, mode_bits_inter, info) in cands {
6869 let (ref_luma, ref_u, ref_v) = match extra
6870 .iter()
6871 .find(|(r, _, _)| *r == info.ref_frame)
6872 {
6873 Some(&(_, g, _)) => (
6874 (&g.y, g.width, luma.true_width, luma.true_height),
6875 (&g.u, g.width / 2, chroma[0].true_width, chroma[0].true_height),
6876 (&g.v, g.width / 2, chroma[1].true_width, chroma[1].true_height),
6877 ),
6878 None => (ref_luma, ref_u, ref_v),
6879 };
6880 let luma_trial = mc_trial(
6881 luma,
6882 x,
6883 y,
6884 BLOCK,
6885 mv,
6886 true,
6887 ref_luma.0,
6888 ref_luma.1,
6889 ref_luma.2,
6890 ref_luma.3,
6891 false,
6892 search.base_q_idx,
6893 search.deadzone,
6894 TxbSet::Luma32Inter, fctx,
6895 );
6896 let u = mc_trial(
6897 &chroma[0],
6898 x / 2,
6899 y / 2,
6900 BLOCK / 2,
6901 mv,
6902 false,
6903 ref_u.0,
6904 ref_u.1,
6905 ref_u.2,
6906 ref_u.3,
6907 false,
6908 search.base_q_idx,
6909 search.deadzone,
6910 chroma_set, fctx,
6911 );
6912 let v = mc_trial(
6913 &chroma[1],
6914 x / 2,
6915 y / 2,
6916 BLOCK / 2,
6917 mv,
6918 false,
6919 ref_v.0,
6920 ref_v.1,
6921 ref_v.2,
6922 ref_v.3,
6923 false,
6924 search.base_q_idx,
6925 search.deadzone,
6926 chroma_set, fctx,
6927 );
6928 let skip = luma_trial.levels.iter().all(|&l| l == 0)
6929 && u.levels.iter().all(|&l| l == 0)
6930 && v.levels.iter().all(|&l| l == 0);
6931 let cost = luma_trial.sse
6932 + u.sse
6933 + v.sse
6934 + search.lambda
6935 * (skip_bits(skip)
6936 + intra_inter_bits(true)
6937 + mode_bits_inter
6938 + if skip {
6939 0.0
6940 } else {
6941 luma_trial.bits + u.bits + v.bits
6942 });
6943 consider(Candidate {
6944 cost,
6945 luma: luma_trial,
6946 u,
6947 v,
6948 mode: DC_PRED,
6949 skip,
6950 mode_bits: mode_bits_inter,
6951 inter: Some(info),
6952 });
6953 }
6954 }
6955
6956 let best = best.expect("the search offers at least the intra modes");
6957 // lane-av1obmc: the OBMC candidate (spec `motion_mode == OBMC_CAUSAL`),
6958 // offered to the SINGLE-REFERENCE winner only -- libaom's
6959 // `motion_mode_allowed` fails `is_motion_variation_allowed_compound` on a
6960 // compound block, so the writer codes no symbol for one. The prediction
6961 // is built by the DECODER's own plan and blend
6962 // ([`crate::decode::obmc_plan`]/[`crate::decode::obmc_run`],
6963 // `av1_build_obmc_inter_prediction`) off the committed neighbours' mvs
6964 // this search's `grid` already carries, so what is priced here is what a
6965 // decoder reconstructs -- never a second implementation of the blend.
6966 //
6967 // MEASURED 2026-09-06 and NOT KEPT ON BY DEFAULT (`EC_AV1_OBMC=1` turns it
6968 // on). Native crop BD, the standing recipe, with it on against the same
6969 // build with it off: film 1080p +18.2/+0.9 against +18.0/+0.7, film 2160p
6970 // +47.3/+19.2 against +47.3/+19.2, screen +59.1/-10.0 against
6971 // +59.4/-10.0. That is one row down (screen -0.3 vs libaom), one flat and
6972 // one UP -- the keep rule wants two down and one flat, so it stays off.
6973 // The 640x384 gate reads the same shape louder: +79.7/+95.5/+54.2 and
6974 // +37.2/+56.8/+0.8 against +78.8/+95.1/+54.5 and +36.1/+56.4/+1.1. Two
6975 // things bound it and are the upgrade path: only the 32x32 winner is
6976 // offered OBMC (the 16x16/8x8 leaves in `code_square_inter` are not, and
6977 // that is where libaom cashes most of its OBMC gain), and the symbol/
6978 // residual price here is the static-CDF estimate.
6979 let mut best = best;
6980 let mut motion_won = 0u8;
6981 if let Some(info) = best.inter.filter(|i| {
6982 i.ref1.is_none()
6983 && (crate::envflags::env_flag!("EC_AV1_OBMC")
6984 || crate::envflags::env_flag!("EC_AV1_WARP"))
6985 }) {
6986 let mut refs: [Option<&Picture>; 8] = [None; 8];
6987 refs[LAST_FRAME as usize] = Some(reference);
6988 for &(r, p, _) in extra {
6989 refs[r as usize] = Some(p);
6990 }
6991 // This block's OWN reference planes: the single-reference winner may
6992 // be one of the extra references, not LAST.
6993 let planes: [(&[u16], usize, usize, usize); 3] =
6994 match extra.iter().find(|(r, _, _)| *r == info.ref_frame) {
6995 Some(&(_, g, _)) => [
6996 (g.y.as_slice(), g.width, luma.true_width, luma.true_height),
6997 (g.u.as_slice(), g.width / 2, chroma[0].true_width, chroma[0].true_height),
6998 (g.v.as_slice(), g.width / 2, chroma[1].true_width, chroma[1].true_height),
6999 ],
7000 None => [
7001 (ref_luma.0.as_slice(), ref_luma.1, ref_luma.2, ref_luma.3),
7002 (ref_u.0.as_slice(), ref_u.1, ref_u.2, ref_u.3),
7003 (ref_v.0.as_slice(), ref_v.1, ref_v.2, ref_v.3),
7004 ],
7005 };
7006 // The alphabet `tile::write_motion_mode` will code this block's
7007 // symbol against, mirrored term for term (libaom
7008 // `motion_mode_allowed`).
7009 let warp_alphabet = crate::envflags::env_flag!("EC_AV1_WARP")
7010 && crate::decode::num_proj_ref(
7011 grid,
7012 mi_row,
7013 mi_col,
7014 8,
7015 8,
7016 mi_cols,
7017 mi_rows,
7018 info.ref_frame,
7019 fctx,
7020 ) >= 1;
7021 let mm = |m: u8| motion_mode_bits(BLOCK, BLOCK, m, warp_alphabet);
7022 let mut candidates: Vec<(u8, [Vec<u8>; 3])> = Vec::new();
7023 if crate::envflags::env_flag!("EC_AV1_OBMC") {
7024 if let Some(pred) = obmc_prediction(
7025 grid,
7026 (mi_row, mi_col),
7027 (mi_rows, mi_cols),
7028 (x, y),
7029 BLOCK,
7030 info.mv,
7031 &refs,
7032 planes,
7033 reference.width,
7034 fctx,
7035 ) {
7036 candidates.push((1, pred));
7037 }
7038 }
7039 if warp_alphabet {
7040 if let Some(pred) = warp_prediction(
7041 grid,
7042 (mi_row, mi_col),
7043 (mi_rows, mi_cols),
7044 (x, y),
7045 BLOCK,
7046 info.mv,
7047 info.ref_frame,
7048 planes,
7049 fctx,
7050 ) {
7051 candidates.push((2, pred));
7052 }
7053 }
7054 for (motion, pred) in candidates {
7055 let luma_trial = luma.code_from_prediction(
7056 x, y, BLOCK, &pred[0], false, search.base_q_idx, search.deadzone,
7057 TxbSet::Luma32Inter,
7058 );
7059 let u = chroma[0].code_from_prediction(
7060 x / 2, y / 2, BLOCK / 2, &pred[1], false, search.base_q_idx, search.deadzone,
7061 chroma_set,
7062 );
7063 let v = chroma[1].code_from_prediction(
7064 x / 2, y / 2, BLOCK / 2, &pred[2], false, search.base_q_idx, search.deadzone,
7065 chroma_set,
7066 );
7067 let skip = luma_trial.levels.iter().all(|&l| l == 0)
7068 && u.levels.iter().all(|&l| l == 0)
7069 && v.levels.iter().all(|&l| l == 0);
7070 let cost = luma_trial.sse
7071 + u.sse
7072 + v.sse
7073 + search.lambda
7074 * (skip_bits(skip)
7075 + intra_inter_bits(true)
7076 + best.mode_bits
7077 + mm(motion)
7078 + if skip { 0.0 } else { luma_trial.bits + u.bits + v.bits });
7079 if cost < best.cost + search.lambda * mm(motion_won) {
7080 motion_won = motion;
7081 best = Candidate {
7082 cost,
7083 luma: luma_trial,
7084 u,
7085 v,
7086 mode: DC_PRED,
7087 skip,
7088 mode_bits: best.mode_bits,
7089 inter: best.inter,
7090 };
7091 }
7092 }
7093 }
7094 // lane-av1txbits BUILT the transform-depth search this path lacks -- a
7095 // 32x32 single-reference winner offered `commit_inter_luma`'s four 16x16
7096 // units against its flat trial, exactly as a 16x16 winner is -- and
7097 // MEASURED it flat to slightly worse: +78.7/+95.1/+54.6 vs libaom and
7098 // +36.1/+56.2/+1.8 vs rav1e, against the +78.8/+95.1/+54.5 and
7099 // +36.1/+56.4/+1.4 this code scores, while the split fired on 40.2% of
7100 // the film's inter blocks and 17.6% of the screen's. The same shape as
7101 // the compound trial set below: a local RD win that does not convert into
7102 // ladder bytes. The flat 32x32 transform stays.
7103 luma.commit(x, y, BLOCK, &best.luma);
7104 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
7105 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
7106 (
7107 BlockCoeffs {
7108 luma: coeffs(&best.luma.levels, BLOCK),
7109 u: coeffs(&best.u.levels, BLOCK / 2),
7110 v: coeffs(&best.v.levels, BLOCK / 2),
7111 mode: best.mode,
7112 uv_mode: DC_PRED,
7113 skip: best.skip,
7114 inter: best.inter,
7115 motion_mode: motion_won,
7116 eight: None,
7117 dv: None,
7118 palette: None,
7119 palette_uv: None,
7120 tx_depth: 0,
7121 },
7122 best.cost,
7123 )
7124}
7125
7126/// Where one inter frame sits in a coding-order pyramid: which DPB slots its
7127/// references name, which slot it refreshes, whether it is shown when it is
7128/// coded, and the `ref_frame_sign_bias` that follows from all of it. `None`
7129/// keeps `encode_inter_frame`'s pre-pyramid flat behaviour verbatim (slot
7130/// 0/2 alternation, every frame shown, every reference in the past).
7131///
7132/// The sign bias is carried rather than derived here because only the caller
7133/// knows what order hint each slot holds; it is armed onto the tile writer
7134/// ([`crate::tile::arm_sign_bias`]) and set on the encoder's own MV grid, so
7135/// the writer scans the same stacks the decoder will.
7136#[derive(Debug, Clone, Copy)]
7137pub(crate) struct PyramidFrame {
7138 /// The slot `LAST_FRAME` (and every reference this encoder does not name
7139 /// apart) reads.
7140 pub last_slot: u8,
7141 /// The single slot `refresh_frame_flags` sets.
7142 pub self_slot: u8,
7143 /// The slot `ALTREF_FRAME` reads -- a FUTURE frame for a leaf of a
7144 /// pyramid, which is what makes `sign_bias`'s last entry true.
7145 pub altref_slot: u8,
7146 /// `show_frame`: false for a hidden frame, output later by a
7147 /// `show_existing_frame` header.
7148 pub show_frame: bool,
7149 /// This frame's `ref_frame_sign_bias` (spec 5.9.2).
7150 pub sign_bias: crate::mvstack::SignBiasTable,
7151}
7152
7153/// Encodes one picture as an inter frame predicting from `reference`'s
7154/// reconstruction, which the caller decoded (or, for the frame right after
7155/// the key frame, is the key frame's own reconstruction).
7156pub(crate) fn encode_inter_frame(
7157 picture: &Picture,
7158 reference: &Picture,
7159 base_q_idx: u8,
7160 deadzone: f64,
7161 order_hint: u32,
7162 // The order hint each of the seven `ref_frame_idx` entries names, which a
7163 // decoder reads out of its own reference state -- only spec 5.9.22's
7164 // `skipModeAllowed` (in `frame::write_frame_header`) reads it, and only
7165 // on a `reference_select` frame. [`flat_order_hints`] builds it for the
7166 // callers that follow this crate's own flat slot plan.
7167 order_hints: [u32; 7],
7168 render: (usize, usize),
7169 // The tables this frame's writer starts from: what the previous frame
7170 // stored into the slot this one's `primary_ref_frame` names. `None`
7171 // starts from the defaults, which is right only for the frame straight
7172 // after a key frame.
7173 start_cdfs: Option<&crate::cdf_state::Cdfs>,
7174 // The key frame's own (padded) reconstruction, which every frame of the
7175 // GOP still holds in DPB slot 1 -- `GOLDEN_FRAME`. `None` codes the frame
7176 // with `LAST_FRAME` alone, exactly as before.
7177 golden: Option<&Picture>,
7178 // The frame two back, held in the slot this frame is about to refresh
7179 // (the encoder alternates 0/2): `ALTREF_FRAME`. `None` for the first two
7180 // inter frames of a GOP, where the frame two back IS the key frame.
7181 altref: Option<&Picture>, fctx: &crate::decode::FrameCtx,
7182 // Where this frame sits in the coding-order pyramid; `None` is the flat
7183 // one-shown-frame-per-picture stream this encoder wrote before.
7184 pyramid: Option<PyramidFrame>,
7185) -> Result<Encoded> {
7186 picture.check()?;
7187 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
7188 return Err(Error::unsupported(
7189 "AV1 encode",
7190 "an inter frame is coded only for a picture that is a whole number \
7191 of 64x64 superblocks -- the inter tile writer never splits a \
7192 superblock's partition below that",
7193 ));
7194 }
7195 if reference.width != picture.width || reference.height != picture.height {
7196 return Err(Error::unsupported(
7197 "AV1 encode",
7198 "the reference picture must be the same size as the one being coded",
7199 ));
7200 }
7201
7202 // The single slot this crate's inter frames ever predict from or
7203 // refresh (`inter_frame_headers`'s contract): every frame both reads and
7204 // overwrites slot 0, so the frame just coded is always what the next one
7205 // predicts against.
7206 const LAST_SLOT: u8 = 0;
7207 // Slot 0 and slot 2 alternate so the frame two back survives one more
7208 // frame: frame n writes A(n) = 0 for odd n, 2 for even, so A(n) = A(n-2)
7209 // and the picture this frame names as `ALTREF_FRAME` is the one sitting
7210 // in the very slot it will overwrite.
7211 let self_slot = pyramid.map_or(if order_hint % 2 == 1 { 0 } else { 2 }, |p| p.self_slot);
7212 let last_slot = pyramid.map_or(
7213 if order_hint <= 1 {
7214 LAST_SLOT
7215 } else if (order_hint - 1) % 2 == 1 {
7216 0
7217 } else {
7218 2
7219 },
7220 |p| p.last_slot,
7221 );
7222 // `render`, not `picture.width`/`picture.height`: `picture` here is
7223 // already padded to a whole number of superblocks (`encode_sequence`'s
7224 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
7225 // every true-edge clamp downstream) must come from the frame's real,
7226 // unpadded size, same as `key_frame_headers_colour` takes `render` and
7227 // not the padded picture in `encode_key_frame_inner`.
7228 let (seq, mut header) = inter_frame_headers_slots(
7229 render.0,
7230 render.1,
7231 base_q_idx,
7232 order_hint,
7233 last_slot,
7234 self_slot,
7235 match pyramid {
7236 Some(p) => p.altref_slot,
7237 None if altref.is_some() => self_slot,
7238 None => GOLDEN_SLOT,
7239 },
7240 )?;
7241 header.render_width = render.0 as u32;
7242 header.render_height = render.1 as u32;
7243 let sign_bias = pyramid.map_or(crate::mvstack::NO_SIGN_BIAS, |p| p.sign_bias);
7244 // The order hint behind each `ref_frame_idx` entry. The flat path's own
7245 // slot plan (`inter_frame_headers_slots`) is: every reference but
7246 // `GOLDEN_FRAME` reads `last_slot` (the frame just coded) except
7247 // `ALTREF_FRAME`, which reads the frame two back when there is one;
7248 // `GOLDEN_FRAME` is the key frame, order hint 0. Only
7249 // `frame::write_frame_header`'s `skipModeAllowed` reads this.
7250 header.order_hints = order_hints;
7251 header.reference_select = reference_select();
7252 // Armed HERE, not only beside the tile write below: `ref_distance`'s own
7253 // per-reference order-hint distance is read by the block SEARCH, which
7254 // runs long before the writer arms these (the distance-scaled search step
7255 // read `(0, 0, [0; 7])` and came out 1 for every reference -- the knob
7256 // never reached the tool).
7257 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
7258 if let Some(p) = pyramid {
7259 header.show_frame = p.show_frame;
7260 header.showable_frame = !p.show_frame;
7261 header.ref_frame_sign_bias = p.sign_bias;
7262 }
7263 // `TxMode::Select` here too: an inter block then codes one `txfm_split`
7264 // flag (kept at zero -- its var-tx tree is not searched yet) and an INTRA
7265 // block inside this frame codes and searches its own `tx_depth`, the same
7266 // as in a key frame (`crate::tile::write_tx_syntax_inter`).
7267 let tx_select = tx_select() && tx_select_inter();
7268 if tx_select {
7269 header.tx_mode = TxMode::Select;
7270 }
7271
7272 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
7273 // lane-hbd r4: encoder stays 8-bit by design; narrow the source once
7274 // here (see `encode_key_frame_inner`).
7275 let picture_y8: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
7276 let picture_u8: Vec<u8> = picture.u.iter().map(|&v| v as u8).collect();
7277 let picture_v8: Vec<u8> = picture.v.iter().map(|&v| v as u8).collect();
7278 // This frame's own `allow_screen_content_tools`. It can only be set when
7279 // the SEQUENCE offers the bit at all, which is the key frame's decision
7280 // ([`SEQ_SCREEN`]): a frame header that contradicts
7281 // `seq_force_screen_content_tools` is a corrupt stream, not a tighter
7282 // encode.
7283 let screen = seq_screen()
7284 && screen_content(&picture_y8, picture.width, true_width, true_height);
7285 header.allow_screen_content_tools = screen;
7286 // The search prices coefficients against the tables this frame's writer
7287 // starts from, not against the defaults (lane-av1txbits) -- but only on a
7288 // frame the screen detector said no to (lane-av1price2): armed HERE, after
7289 // `screen` exists, and again on every search/tile worker below.
7290 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
7291 let mut luma = Plane {
7292 source: &picture_y8,
7293 reconstruction: vec![128; picture_y8.len()],
7294 width: picture.width,
7295 height: picture.height,
7296 true_width,
7297 true_height,
7298 tile_x0: 0,
7299 tile_y0: 0,
7300 tile_x1: picture.width,
7301 tile_y1: picture.height,
7302 ctx: CoefCtxMap::default(),
7303 };
7304 let mut chroma = [
7305 Plane {
7306 source: &picture_u8,
7307 reconstruction: vec![128; picture_u8.len()],
7308 width: picture.width / 2,
7309 height: picture.height / 2,
7310 true_width: true_width / 2,
7311 true_height: true_height / 2,
7312 tile_x0: 0,
7313 tile_y0: 0,
7314 tile_x1: picture.width / 2,
7315 tile_y1: picture.height / 2,
7316 ctx: CoefCtxMap::default(),
7317 },
7318 Plane {
7319 source: &picture_v8,
7320 reconstruction: vec![128; picture_v8.len()],
7321 width: picture.width / 2,
7322 height: picture.height / 2,
7323 true_width: true_width / 2,
7324 true_height: true_height / 2,
7325 tile_x0: 0,
7326 tile_y0: 0,
7327 tile_x1: picture.width / 2,
7328 tile_y1: picture.height / 2,
7329 ctx: CoefCtxMap::default(),
7330 },
7331 ];
7332
7333 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
7334 let search = Search {
7335 base_q_idx,
7336 deadzone,
7337 lambda: lambda_scale() * step * step,
7338 modes: &KEY_FRAME_MODES,
7339 top_k: prune_top_k_inter(),
7340 screen,
7341 };
7342 let mode_bits_table = inter_mode_bits();
7343
7344 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
7345 // coding surface's: `blocks` carries one entry per 32x32 block the tile
7346 // writer will actually visit, same count it checks `blocks.len()`
7347 // against, which is fewer than the padded surface's own block count
7348 // whenever the true size is not a 64x64 multiple.
7349 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
7350 let (cols, rows) = (cols as usize, rows as usize);
7351 let (sb_cols, _sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
7352 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
7353 // This frame's tile grid, as in `encode_key_frame_inner`.
7354 let (tile_cols_log2, tile_rows_log2) = armed_tiles();
7355 let layout =
7356 crate::tile::TileLayout::new(header.mi_cols, header.mi_rows, tile_cols_log2, tile_rows_log2);
7357 header.tile_info = tile_info_of(&layout, 1);
7358 let header_tile_info = header.tile_info.clone();
7359 // lane-hbd r4: `motion::search` is 8-bit only (its SAD/cost math is
7360 // integer-`u8`-scale), so the DPB reference plane is narrowed for it --
7361 // once per frame (lane-av1rd2), not once per block, which is a whole
7362 // plane's map per 32x32 block and now per leaf too.
7363 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
7364 // lane-av1tsearch: one search job per TILE (`search_tiles`). Neighbour
7365 // availability -- intra edges and the MV stack's scans alike -- already
7366 // stopped at the superblock's own tile (`PlaneBuf::set_tile_origin`,
7367 // `MiGrid::set_tile_bounds`), so a tile reads nothing another tile wrote;
7368 // giving each job its own planes and its own `MiGrid` therefore leaves
7369 // every decision, and so every coded bit, exactly where the whole-frame
7370 // loop left it, at any tile count and any thread count.
7371 let (frame_width, frame_height) = (picture.width, picture.height);
7372 let luma_out = crate::par::Shared::new(&mut luma.reconstruction);
7373 let [cb, cr] = &mut chroma;
7374 let chroma_out = [
7375 crate::par::Shared::new(&mut cb.reconstruction),
7376 crate::par::Shared::new(&mut cr.reconstruction),
7377 ];
7378 let search_tile = |index: usize,
7379 fctx: &crate::decode::FrameCtx|
7380 -> Result<Vec<(usize, Quadrant)>> {
7381 // Thread-local, and this job may be running on a `search_tiles`
7382 // worker: `ref_distance`'s order-hint distance (the scaled motion
7383 // search step) is read by the SEARCH, so every worker arms it or the
7384 // tile's bits depend on the thread count.
7385 crate::tile::arm_order_hints(seq.order_hint_bits, order_hint, order_hints);
7386 crate::tile::arm_pricing_cdfs(start_cdfs, screen);
7387 let rect = layout.rect(index);
7388 let mut luma = fresh_plane(&picture_y8, frame_width, frame_height, true_width, true_height);
7389 let mut chroma = [
7390 fresh_plane(&picture_u8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
7391 fresh_plane(&picture_v8, frame_width / 2, frame_height / 2, true_width / 2, true_height / 2),
7392 ];
7393 clip_planes_to_tile(&mut luma, &mut chroma, rect);
7394 let mut grid = MiGrid::new(mi_cols, mi_rows);
7395 grid.set_sign_bias(sign_bias);
7396 // lane-av1obmc2: every picture an OBMC neighbour of a LEAF can name,
7397 // built once per tile job (`obmc_prediction`).
7398 let mut obmc_refs: [Option<&Picture>; 8] = [None; 8];
7399 obmc_refs[crate::mvstack::LAST_FRAME as usize] = Some(reference);
7400 obmc_refs[crate::mvstack::GOLDEN_FRAME as usize] = golden;
7401 obmc_refs[crate::mvstack::ALTREF_FRAME as usize] = altref;
7402 grid.set_tile_bounds(
7403 rect.mi_row0 as usize,
7404 rect.mi_col0 as usize,
7405 rect.mi_row1 as usize,
7406 rect.mi_col1 as usize,
7407 );
7408 let mut blocks: Vec<(usize, Quadrant)> = Vec::new();
7409 for sb_r in rect.sb_row0 as usize..rect.sb_row1 as usize {
7410 for sb_c in rect.sb_col0 as usize..rect.sb_col1 as usize {
7411 for quadrant in 0..4 {
7412 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
7413 // Same filter as the tile writer's: a quadrant whose own mi
7414 // origin is not inside the true frame is never coded.
7415 if r32 >= rows || c32 >= cols {
7416 continue;
7417 }
7418 // spec `decode_partition`'s hasRows/hasCols recomputed at this
7419 // 32x32 block's own half (`crate::tile::has_half`), same as
7420 // the key frame search: the true frame edge can fall inside a
7421 // quadrant a superblock-level check already let through, and
7422 // such a quadrant cannot be left whole -- it must split into
7423 // the 16x16 leaves that are actually inside the true frame
7424 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
7425 // arm).
7426 let (has_cols32, has_rows32) = (
7427 crate::tile::has_half(
7428 c32 as u32 * crate::tile::BLOCK_MI,
7429 crate::tile::BLOCK_MI,
7430 header.mi_cols,
7431 ),
7432 crate::tile::has_half(
7433 r32 as u32 * crate::tile::BLOCK_MI,
7434 crate::tile::BLOCK_MI,
7435 header.mi_rows,
7436 ),
7437 );
7438 if has_cols32 && has_rows32 {
7439 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
7440 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
7441 let stack =
7442 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
7443 let extra_stacks: Vec<(i8, &Picture, MvStack)> = [
7444 (crate::mvstack::GOLDEN_FRAME, golden),
7445 (crate::mvstack::ALTREF_FRAME, altref),
7446 ]
7447 .into_iter()
7448 .filter_map(|(r, pic)| {
7449 pic.map(|p| {
7450 (
7451 r,
7452 p,
7453 find_mv_stack(&grid, mi_row, mi_col, 8, 8, r, mi_cols, mi_rows),
7454 )
7455 })
7456 })
7457 .collect();
7458 let extra: Vec<(i8, &Picture, &MvStack)> = extra_stacks
7459 .iter()
7460 .map(|(r, p, st)| (*r, *p, st))
7461 .collect();
7462 // The COMPOUND stack of each `LAST` + extra pair, off the
7463 // same grid (and the same armed sign bias) the tile writer
7464 // rebuilds it from. Empty unless this frame codes
7465 // `reference_select`, which is what gates the syntax.
7466 let compound: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
7467 if header.reference_select {
7468 extra_stacks
7469 .iter()
7470 .map(|&(r, p, _)| {
7471 (
7472 r,
7473 p,
7474 crate::mvstack::find_mv_stack_compound(
7475 &grid,
7476 mi_row,
7477 mi_col,
7478 8,
7479 8,
7480 (crate::mvstack::LAST_FRAME, r),
7481 mi_cols,
7482 mi_rows,
7483 grid.sign_bias_table(),
7484 &[(0, 0); 7],
7485 None,
7486 ),
7487 )
7488 })
7489 .collect()
7490 } else {
7491 Vec::new()
7492 };
7493
7494 let base = snapshot(&luma, &chroma, (x, y), BLOCK);
7495 let (block, mut cost_whole) = search_inter_block(
7496 &mut luma,
7497 &mut chroma,
7498 (x, y),
7499 &search,
7500 &mode_bits_table,
7501 reference,
7502 &stack,
7503 &extra,
7504 &compound,
7505 &grid,
7506 (mi_row, mi_col),
7507 (mi_rows, mi_cols),
7508 fctx,
7509 );
7510 cost_whole += search.lambda * partition_bits(BLOCK, false);
7511 let after_whole = snapshot(&luma, &chroma, (x, y), BLOCK);
7512
7513 // What four 16x16 leaves cost instead (spec
7514 // PARTITION_SPLIT at BLOCK_32X32, which
7515 // `sb_coeff_inter_frame_tile`'s `Quadrant::Split` arm
7516 // already writes for a straddling quadrant). Each leaf is
7517 // searched against the reconstruction -- and the `mi`
7518 // grid -- the ones before it left, exactly as the writer
7519 // and the decoder will read them.
7520 //
7521 // A block the whole-32 search left skipped (no residual
7522 // at all) is not offered the split: libaom prunes the
7523 // same way at cpu-used 6, and it is where the wall would
7524 // otherwise go on static content.
7525 let leaf_positions: Vec<(usize, usize)> = (0..4)
7526 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
7527 .collect();
7528 let leaves_legal = leaf_positions.iter().all(|&(sr, sc)| {
7529 crate::tile::has_half(
7530 sc as u32 * crate::tile::SUB_MI,
7531 crate::tile::SUB_MI,
7532 header.mi_cols,
7533 ) && crate::tile::has_half(
7534 sr as u32 * crate::tile::SUB_MI,
7535 crate::tile::SUB_MI,
7536 header.mi_rows,
7537 )
7538 });
7539 // The breakout above: a 32x32 block that codes almost
7540 // nothing is not offered the split at all.
7541 let breakout = split_breakout_coeffs();
7542 let split = (!block.skip
7543 && !split_rd_breakout(cost_whole, BLOCK, search.lambda)
7544 && (breakout == 0 || block.luma.len() > 4 * breakout)
7545 && leaves_legal
7546 && split_inter_blocks())
7547 .then(|| {
7548 restore(&mut luma, &mut chroma, (x, y), BLOCK, &base);
7549 let mut cost = search.lambda * partition_bits(BLOCK, true);
7550 let mut leaves = Vec::with_capacity(4);
7551 for &(sr, sc) in &leaf_positions {
7552 let (mi_row, mi_col) = (sr * 4, sc * 4);
7553 let (lx, ly) = (sc * SUB, sr * SUB);
7554 let leaf_base = snapshot(&luma, &chroma, (lx, ly), SUB);
7555 let stack = find_mv_stack(
7556 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
7557 );
7558 let cstacks = leaf_compound_stacks(
7559 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
7560 header.reference_select, golden, altref,
7561 );
7562 let (leaf, leaf_cost) = code_square_inter(
7563 &mut luma,
7564 &mut chroma,
7565 (lx, ly),
7566 SUB,
7567 &search,
7568 &mode_bits_table,
7569 reference,
7570 &stack,
7571 &cstacks,
7572 &grid,
7573 (mi_row, mi_col),
7574 (mi_rows, mi_cols),
7575 &obmc_refs,
7576 fctx,
7577 );
7578 let leaf_cost = leaf_cost
7579 + search.lambda * partition_bits(SUB, false);
7580 let after_leaf = snapshot(&luma, &chroma, (lx, ly), SUB);
7581
7582 // And what four 8x8 leaves cost instead --
7583 // the same tree one step further down, which
7584 // the writer codes as a real PARTITION_SPLIT
7585 // at BLOCK_16X16 (lane-av1rd2). Same
7586 // skipped-block prune as the level above.
7587 let eight = (!leaf.skip
7588 && !split_rd_breakout(leaf_cost, SUB, search.lambda)
7589 && (breakout == 0 || leaf.luma.len() > breakout)
7590 && split_inter_8())
7591 .then(|| {
7592 restore(
7593 &mut luma, &mut chroma, (lx, ly), SUB, &leaf_base,
7594 );
7595 let mut cost8 = search.lambda
7596 * (partition_bits(SUB, true)
7597 + 4.0 * partition_bits(8, false));
7598 let mut eight = Vec::with_capacity(4);
7599 for i in 0..4 {
7600 let (mr, mc) =
7601 (mi_row + (i / 2) * 2, mi_col + (i % 2) * 2);
7602 let stack8 = find_mv_stack(
7603 &grid, mr, mc, 2, 2, LAST_FRAME, mi_cols, mi_rows,
7604 );
7605 let cstacks8: Vec<(i8, &Picture, crate::mvstack::CompoundMvStack)> =
7606 if header.reference_select && leaf_compound() {
7607 [
7608 (crate::mvstack::GOLDEN_FRAME, golden),
7609 (crate::mvstack::ALTREF_FRAME, altref),
7610 ]
7611 .into_iter()
7612 .filter_map(|(r, pic)| {
7613 pic.map(|p| {
7614 (
7615 r,
7616 p,
7617 crate::mvstack::find_mv_stack_compound(
7618 &grid, mr, mc, 2, 2,
7619 (crate::mvstack::LAST_FRAME, r), mi_cols, mi_rows,
7620 grid.sign_bias_table(), &[(0, 0); 7], None,
7621 ),
7622 )
7623 })
7624 })
7625 .collect()
7626 } else {
7627 Vec::new()
7628 };
7629 let (leaf8, cost) = code_square_inter(
7630 &mut luma,
7631 &mut chroma,
7632 (lx + (i % 2) * 8, ly + (i / 2) * 8),
7633 8,
7634 &search,
7635 &mode_bits_table,
7636 reference,
7637 &stack8,
7638 &cstacks8,
7639 &grid,
7640 (mr, mc),
7641 (mi_rows, mi_cols),
7642 &obmc_refs,
7643 fctx,
7644 );
7645 cost8 += cost;
7646 record_mi(&mut grid, mr, mc, 2, leaf8.inter);
7647 eight.push(leaf8);
7648 }
7649 (eight, cost8)
7650 });
7651 match eight {
7652 Some((eight, cost8)) if cost8 < leaf_cost => {
7653 partition_hit(3);
7654 cost += cost8;
7655 leaves.push(BlockCoeffs {
7656 eight: Some(eight),
7657 ..BlockCoeffs::default()
7658 });
7659 continue;
7660 }
7661 Some(_) => restore(
7662 &mut luma, &mut chroma, (lx, ly), SUB, &after_leaf,
7663 ),
7664 None => {}
7665 }
7666 partition_hit(2);
7667 cost += leaf_cost;
7668 record_mi(&mut grid, mi_row, mi_col, 4, leaf.inter);
7669 leaves.push(leaf);
7670 }
7671 (leaves, cost)
7672 });
7673 if let Some((leaves, cost)) = split {
7674 if cost < cost_whole {
7675 // The leaves' own `mi` cells are already in the
7676 // grid, and their reconstruction is what the
7677 // planes hold.
7678 partition_hit(1);
7679 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
7680 continue;
7681 }
7682 restore(&mut luma, &mut chroma, (x, y), BLOCK, &after_whole);
7683 }
7684 partition_hit(0);
7685 record_mi(&mut grid, mi_row, mi_col, 8, block.inter);
7686 blocks.push((r32 * cols + c32, Quadrant::Whole(block)));
7687 } else {
7688 // The sub-positions actually inside the true frame, same
7689 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
7690 let sub_positions: Vec<(usize, usize)> = (0..4)
7691 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
7692 .filter(|&(sr, sc)| {
7693 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
7694 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
7695 })
7696 .collect();
7697 // Each leaf searches intra against its own `NEARESTMV`
7698 // candidate (`code_square_inter`), same real-inter choice
7699 // `search_inter_block` makes for a whole 32x32 block, at
7700 // this leaf's own 4x4-mi mv-stack window -- unless the
7701 // leaf's own half itself straddles the true edge, which
7702 // it codes as two (or one, at a true corner) 8x8 leaves
7703 // (`crate::tile::write_leaf8`'s inter counterpart),
7704 // mirroring the key frame search's straddling-16x16
7705 // handling above (lane-av1inter8).
7706 let mut leaves = Vec::with_capacity(sub_positions.len());
7707 for (sr, sc) in sub_positions {
7708 let (has_cols16, has_rows16) = (
7709 crate::tile::has_half(
7710 sc as u32 * crate::tile::SUB_MI,
7711 crate::tile::SUB_MI,
7712 header.mi_cols,
7713 ),
7714 crate::tile::has_half(
7715 sr as u32 * crate::tile::SUB_MI,
7716 crate::tile::SUB_MI,
7717 header.mi_rows,
7718 ),
7719 );
7720 if has_cols16 && has_rows16 {
7721 let (x, y) = (sc * SUB, sr * SUB);
7722 let (mi_row, mi_col) = (sr * 4, sc * 4);
7723 let stack = find_mv_stack(
7724 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
7725 );
7726 let cstacks = leaf_compound_stacks(
7727 &grid, mi_row, mi_col, 4, 4, mi_cols, mi_rows,
7728 header.reference_select, golden, altref,
7729 );
7730 let (block, _) = code_square_inter(
7731 &mut luma,
7732 &mut chroma,
7733 (x, y),
7734 SUB,
7735 &search,
7736 &mode_bits_table,
7737 reference,
7738 &stack,
7739 &cstacks,
7740 &grid,
7741 (mi_row, mi_col),
7742 (mi_rows, mi_cols),
7743 &obmc_refs,
7744 fctx,
7745 );
7746 // One publication point for every coded leaf
7747 // (`record_mi`): this site used to spell the vote
7748 // out with `ref_frame` pinned to LAST and `mv1`
7749 // to (0,0), which is the encoder-grid-drift class
7750 // -- correct only for as long as a leaf can never
7751 // be compound.
7752 record_mi(&mut grid, mi_row, mi_col, 4, block.inter);
7753 leaves.push(block);
7754 } else {
7755 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
7756 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
7757 let mut eight = Vec::with_capacity(2);
7758 for i in 0..4 {
7759 let leaf_x = x_sub + (i % 2) * 8;
7760 let leaf_y = y_sub + (i / 2) * 8;
7761 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
7762 continue;
7763 }
7764 let (mi_row, mi_col) =
7765 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
7766 let stack = find_mv_stack(
7767 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
7768 );
7769 let cstacks = leaf_compound_stacks(
7770 &grid, mi_row, mi_col, 2, 2, mi_cols, mi_rows,
7771 header.reference_select, golden, altref,
7772 );
7773 let (leaf, _) = code_square_inter(
7774 &mut luma,
7775 &mut chroma,
7776 (leaf_x, leaf_y),
7777 8,
7778 &search,
7779 &mode_bits_table,
7780 reference,
7781 &stack,
7782 &cstacks,
7783 &grid,
7784 (mi_row, mi_col),
7785 (mi_rows, mi_cols),
7786 &obmc_refs,
7787 fctx,
7788 );
7789 // Same publication point as the 16x16
7790 // straddling leaf above (`record_mi`).
7791 record_mi(&mut grid, mi_row, mi_col, 2, leaf.inter);
7792 eight.push(leaf);
7793 }
7794 leaves.push(BlockCoeffs {
7795 eight: Some(eight),
7796 ..BlockCoeffs::default()
7797 });
7798 }
7799 }
7800 blocks.push((r32 * cols + c32, Quadrant::Split(leaves)));
7801 }
7802 }
7803 }
7804 }
7805 let (x0, y0) = (rect.mi_col0 as usize * 4, rect.mi_row0 as usize * 4);
7806 let (x1, y1) = (rect.mi_col1 as usize * 4, rect.mi_row1 as usize * 4);
7807 copy_rect(luma_out, &luma.reconstruction, frame_width, x0, y0, x1, y1);
7808 for (&out, tile) in chroma_out.iter().zip(&chroma) {
7809 copy_rect(
7810 out,
7811 &tile.reconstruction,
7812 frame_width / 2,
7813 x0 / 2,
7814 y0 / 2,
7815 x1.div_ceil(2),
7816 y1.div_ceil(2),
7817 );
7818 }
7819 Ok(blocks)
7820 };
7821 for (at, quadrant) in search_tiles(layout.count(), fctx, search_tile)?
7822 .into_iter()
7823 .flatten()
7824 {
7825 blocks[at] = quadrant;
7826 }
7827
7828 let modes = blocks
7829 .iter()
7830 .flat_map(Quadrant::blocks)
7831 .map(|b| b.mode)
7832 .collect::<Vec<_>>();
7833 let inter_block_share = blocks
7834 .iter()
7835 .flat_map(Quadrant::blocks)
7836 .filter(|b| b.inter.is_some())
7837 .count() as f64
7838 / modes.len() as f64;
7839 for block in blocks.iter().flat_map(Quadrant::blocks) {
7840 if let Some(info) = block.inter {
7841 let r = (info.ref_frame as usize).min(7);
7842 REF_FRAME_HITS[r].fetch_add(1, std::sync::atomic::Ordering::Relaxed);
7843 }
7844 }
7845 #[cfg(test)]
7846 record_predicted_bits(crate::tile::predicted_coeff_bits(&blocks, base_q_idx));
7847 // This frame's header leaves `disable_frame_end_update_cdf` off, so it
7848 // stores its end-of-tile tables with the counts reset (spec 7.20) and the
7849 // next frame's writer starts from them -- exactly what
7850 // `crate::stream::stored_cdfs_for` hands the decoder.
7851 let (mi_cols, mi_rows) = (header.mi_cols, header.mi_rows);
7852 let cdfs = start_cdfs
7853 .cloned()
7854 .unwrap_or_else(|| crate::cdf_state::Cdfs::new(crate::tile::q_ctx_of(base_q_idx)));
7855 let start_cdfs = CdfSnapshot(cdfs);
7856 let reference_select_bit = header.reference_select;
7857 let switchable_motion_mode = header.is_motion_mode_switchable;
7858 let warped_motion = header.allow_warped_motion;
7859 let order_hint_bits = seq.order_hint_bits;
7860 let lr_horz = crate::restoration::count_units(header.frame_width, 64) as u32;
7861 let lr_vert = crate::restoration::count_units(header.frame_height, 64) as u32;
7862 // What this frame stores is the LARGEST tile's end-of-tile tables --
7863 // its own header's `context_update_tile_id` (spec 7.20), which
7864 // `tile_info_of` set to exactly that tile.
7865 let store_tile = layout.largest_tile();
7866 let end_cdfs = std::cell::RefCell::new(None);
7867 // As in `encode_key_frame_inner`: every tile starts from this frame's
7868 // own tables, so no tile depends on any other.
7869 let code_tiles = |bits: u8,
7870 sb_cols: usize,
7871 cdef_grid: &[u8],
7872 units: &[Option<crate::restoration::WienerInfo>]|
7873 -> Result<Vec<Vec<u8>>> {
7874 let (out, stored) = write_tiles(layout.count(), store_tile, |index| {
7875 crate::tile::arm_cdef_idx(bits, sb_cols, cdef_grid.to_vec());
7876 crate::tile::arm_lr(64, lr_horz, lr_vert, units.to_vec());
7877 crate::tile::arm_sign_bias(sign_bias);
7878 // Thread-locals: every tile job arms its own worker.
7879 crate::tile::arm_reference_select(reference_select_bit);
7880 crate::tile::arm_motion_mode(switchable_motion_mode);
7881 crate::tile::arm_warped_motion(warped_motion);
7882 crate::tile::arm_order_hints(order_hint_bits, order_hint, order_hints);
7883 crate::tile::arm_screen(screen);
7884 let mut cdfs = start_cdfs.0.clone();
7885 crate::tile::arm_pricing_cdfs(Some(&cdfs), screen);
7886 // Each tile's own MV grid: a candidate scan never reaches past
7887 // the tile's bounds, so a grid holding only this tile's own
7888 // blocks reads exactly as the decoder's frame-wide one does
7889 // under `MiGrid::set_tile_bounds`.
7890 let mut mv_grid = MiGrid::new(mi_cols as usize, mi_rows as usize);
7891 mv_grid.set_sign_bias(sign_bias);
7892 let bytes = crate::tile::sb_coeff_inter_frame_tile_cdfs(
7893 mi_cols,
7894 mi_rows,
7895 base_q_idx,
7896 &blocks,
7897 tx_select,
7898 &mut cdfs,
7899 layout.rect(index),
7900 &mut mv_grid,
7901 )?;
7902 Ok((bytes, Some(cdfs)))
7903 })?;
7904 if let Some(cdfs) = stored {
7905 *end_cdfs.borrow_mut() = Some(cdfs);
7906 }
7907 Ok(out)
7908 };
7909 let mut tiles = code_tiles(0, sb_cols, &[], &[])?;
7910 // Deblocking, as in `encode_key_frame_inner`: the decoder reconstructs
7911 // this tile against the same single-slot reference this encoder predicted
7912 // from, under each candidate level.
7913 // The reference a DECODER holds is this frame's cropped size, not the
7914 // encoder's padded coding surface -- `decode_inter_frame_tile` refuses a
7915 // reference whose height is not the header's own `frame_height` (spec
7916 // 7.9's compatible-size rule), and the chained-decode round trips prove
7917 // the two predict identically.
7918 let (fw, fh) = (header.frame_width as usize, header.frame_height as usize);
7919 let trial_ref = if (reference.width, reference.height) == (fw, fh) {
7920 reference.clone()
7921 } else {
7922 Picture {
7923 width: fw,
7924 height: fh,
7925 y: crop_plane(&reference.y, reference.width, fw, fh),
7926 u: crop_plane(&reference.u, reference.width / 2, fw / 2, fh / 2),
7927 v: crop_plane(&reference.v, reference.width / 2, fw / 2, fh / 2),
7928 }
7929 };
7930 // `RefPix` is indexed by the reference NAME (`LAST_FRAME` = 1,
7931 // `GOLDEN_FRAME` = 4), not by DPB slot: the trial decode of a frame whose
7932 // blocks may name GOLDEN needs that plane too, cropped the same way.
7933 let trial_golden = golden.map(|g| {
7934 if (g.width, g.height) == (fw, fh) {
7935 g.clone()
7936 } else {
7937 Picture {
7938 width: fw,
7939 height: fh,
7940 y: crop_plane(&g.y, g.width, fw, fh),
7941 u: crop_plane(&g.u, g.width / 2, fw / 2, fh / 2),
7942 v: crop_plane(&g.v, g.width / 2, fw / 2, fh / 2),
7943 }
7944 }
7945 });
7946 let trial_altref = altref.map(|a| {
7947 if (a.width, a.height) == (fw, fh) {
7948 a.clone()
7949 } else {
7950 Picture {
7951 width: fw,
7952 height: fh,
7953 y: crop_plane(&a.y, a.width, fw, fh),
7954 u: crop_plane(&a.u, a.width / 2, fw / 2, fh / 2),
7955 v: crop_plane(&a.v, a.width / 2, fw / 2, fh / 2),
7956 }
7957 }
7958 });
7959 let mut refs: [Option<&Picture>; 8] = [None; 8];
7960 refs[1] = Some(&trial_ref);
7961 refs[4] = trial_golden.as_ref();
7962 refs[7] = trial_altref.as_ref();
7963 let refpix = crate::decode::RefPix::ready(refs);
7964 pick_and_apply_filters(
7965 &mut header,
7966 &mut luma,
7967 &mut chroma,
7968 [&picture_y8, &picture_u8, &picture_v8],
7969 // Merge of lane-av1filt with lane-av1tx2: the trial decoder takes
7970 // this frame's own `tx_select`, so the search runs under inter
7971 // `TxMode::Select` too (it used to skip and leave every inter frame
7972 // unfiltered once Select became the default).
7973 true,
7974 &mut tiles,
7975 search.lambda,
7976 fctx,
7977 // As in `encode_key_frame_inner`, but this frame's end-of-tile tables
7978 // are what the NEXT frame writes from, so the winning re-code
7979 // publishes its own into `end_cdfs` -- the first write's are stale
7980 // the moment a second tile is coded.
7981 |bits, sb_cols, grid, units| code_tiles(bits, sb_cols, grid, units),
7982 |lf, cdef, h, tiles: &[Vec<u8>], lr| {
7983 let payloads: Vec<&[u8]> = tiles.iter().map(Vec::as_slice).collect();
7984 crate::decode::decode_inter_frame_tiles_lr(
7985 &payloads,
7986 &header_tile_info,
7987 h.mi_cols,
7988 h.mi_rows,
7989 base_q_idx,
7990 h.frame_width,
7991 h.frame_height,
7992 &refpix,
7993 cdef,
7994 lf,
7995 h.allow_high_precision_mv,
7996 h.force_integer_mv,
7997 Some(mc::InterpFilterKind::Regular),
7998 seq.enable_dual_filter,
7999 h.reference_select,
8000 tx_select,
8001 lr,
8002 // The trial decode re-reads the tile the writer just wrote,
8003 // so it starts from the same tables the writer did (this
8004 // frame's `start_cdfs`), not from the defaults.
8005 Some(start_cdfs.0.clone()),
8006 sign_bias,
8007 h.allow_screen_content_tools,
8008 switchable_motion_mode,
8009 h.allow_warped_motion,
8010 fctx,
8011 )
8012 },
8013 )?;
8014 let mut cdfs = end_cdfs
8015 .into_inner()
8016 .unwrap_or_else(|| start_cdfs.0.clone());
8017 cdfs.reset_counts();
8018 let next_cdfs = CdfSnapshot(cdfs);
8019 let tile_size_bytes = crate::frame::tile_size_bytes_for(&tiles);
8020 header.tile_info.tile_size_bytes = tile_size_bytes;
8021 let tile = crate::frame::tile_group_payload(&tiles, tile_size_bytes);
8022 let mut stream = temporal_delimiter();
8023 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
8024
8025 let [u, v] = chroma;
8026 Ok(Encoded {
8027 stream,
8028 modes,
8029 inter_block_share,
8030 reconstruction: Picture {
8031 width: luma.width,
8032 height: luma.height,
8033 y: luma.reconstruction.iter().map(|&v| u16::from(v)).collect(),
8034 u: u.reconstruction.iter().map(|&v| u16::from(v)).collect(),
8035 v: v.reconstruction.iter().map(|&v| u16::from(v)).collect(),
8036 },
8037 tile,
8038 mi_cols: header.mi_cols,
8039 mi_rows: header.mi_rows,
8040 base_q_idx,
8041 tx_select,
8042 switchable_motion_mode,
8043 screen,
8044 start_cdfs,
8045 next_cdfs,
8046 loop_filter: header.loop_filter,
8047 cdef: header.cdef,
8048 loop_restoration: header.loop_restoration,
8049 // An inter frame never allows intrabc (spec 5.9.2 codes the bit on
8050 // intra frames only).
8051 allow_intrabc: false,
8052 })
8053}
8054
8055/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
8056/// frame's temporal unit followed by one inter frame's temporal unit per
8057/// remaining picture, all sharing the key frame's sequence header -- and
8058/// each frame's own [`Encoded`], in coding order.
8059#[derive(Clone, Debug)]
8060pub struct EncodedSequence {
8061 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
8062 /// sequence header and the key frame) followed by each later frame's
8063 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
8064 /// the sequence header the key frame carried).
8065 pub stream: Vec<u8>,
8066 /// One entry per picture, in coding order.
8067 pub frames: Vec<Encoded>,
8068}
8069
8070/// Encodes a sequence of pictures as a key frame followed by one inter frame
8071/// per remaining picture, each predicting from the previous frame's own
8072/// decoded reconstruction — never from the source, which is what a decoder
8073/// cannot see. Every picture must be the same even size (any even width and
8074/// height — each is padded to a whole number of 64x64 superblocks
8075/// internally, which is what lets an inter frame's reference always match
8076/// the frame being coded against it), and `pictures` must be non-empty.
8077///
8078/// # Errors
8079/// Returns an error when `pictures` is empty, when any picture besides the
8080/// first is not the same size as the first, or under the same conditions
8081/// [`encode_key_frame`] and the inter frame path do.
8082pub(crate) fn encode_sequence_with_ctx(
8083 pictures: &[Picture],
8084 base_q_idx: u8,
8085 deadzone: f64, fctx: &crate::decode::FrameCtx,
8086) -> Result<EncodedSequence> {
8087 let Some((first, rest)) = pictures.split_first() else {
8088 return Err(Error::unsupported(
8089 "AV1 encode",
8090 "a sequence needs at least one picture",
8091 ));
8092 };
8093 first.check_even()?;
8094 let render = (first.width, first.height);
8095 // The key frame and every inter frame after it are coded at the same
8096 // padded size, so the reference each inter frame predicts from -- the
8097 // previous frame's own uncropped reconstruction, at the size a decoder's
8098 // reference buffer actually holds -- always matches the frame being
8099 // coded against it.
8100 let key = encode_key_frame_inner(
8101 &first.padded_to(SUPERBLOCK),
8102 base_q_idx,
8103 deadzone,
8104 &KEY_FRAME_MODES,
8105 split_blocks(),
8106 render,
8107 unspecified_color_config(), fctx,
8108 )?;
8109 let mut stream = key.stream.clone();
8110 // Slot 1 keeps the key frame's own reconstruction for the whole GOP (the
8111 // key frame refreshes every slot, each inter frame only slot 0), which is
8112 // what `GOLDEN_FRAME` names.
8113 let golden = key.reconstruction.clone();
8114 // The frame two back, once there is one that is not the key frame
8115 // itself (which `GOLDEN_FRAME` already names).
8116 let mut prev2: Option<Picture> = None;
8117 let mut carried = key.next_cdfs.clone();
8118 let mut reference = key.reconstruction.clone();
8119 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
8120 for (i, picture) in rest.iter().enumerate() {
8121 picture.check_even()?;
8122 if (picture.width, picture.height) != render {
8123 return Err(Error::unsupported(
8124 "AV1 encode",
8125 "every picture in a sequence must be the same size as the first",
8126 ));
8127 }
8128 let order_hint = (i + 1) as u32;
8129 let inter = encode_inter_frame(
8130 &picture.padded_to(SUPERBLOCK),
8131 &reference,
8132 base_q_idx,
8133 deadzone,
8134 order_hint,
8135 flat_order_hints(order_hint, 0, prev2.is_some()),
8136 render,
8137 Some(&carried.0),
8138 Some(&golden),
8139 prev2.as_ref(), fctx,
8140 None,
8141 )?;
8142 stream.extend_from_slice(&inter.stream);
8143 carried = inter.next_cdfs.clone();
8144 prev2 = Some(std::mem::replace(
8145 &mut reference,
8146 inter.reconstruction.clone(),
8147 ));
8148 frames.push(crop_encoded(&inter, render.0, render.1));
8149 }
8150 Ok(EncodedSequence { stream, frames })
8151}
8152
8153#[cfg(test)]
8154mod tests {
8155
8156 /// lane-rectx r5: libaom lays `has_tr_*`/`has_bl_*` out row-major for a
8157 /// 128x128 superblock -- `MAX_MIB_SIZE_LOG2 = 5` mi columns per row, so a
8158 /// row holds `32 >> bw_in_mi_log2` bits and the table holds
8159 /// `32 >> bh_in_mi_log2` such rows. Walking every block position of that
8160 /// superblock must therefore hit every bit of the table EXACTLY ONCE.
8161 /// r4's `4 - bw_log2` index halved the row stride: the walk then covered
8162 /// only a quarter of the 16x8 table and read the wrong byte for every
8163 /// block row but the first (silently wrong above-right/below-left
8164 /// availability -- wrong pixels, no error).
8165 #[test]
8166 fn rect_reach_tables_are_indexed_with_a_32_mi_row_stride() {
8167 for (bw, bh) in [(16usize, 8usize), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
8168 let (bw_log2, bh_log2) =
8169 ((bw / 4).trailing_zeros() as usize, (bh / 4).trailing_zeros() as usize);
8170 let (rows, cols) = (32 >> bh_log2, 32 >> bw_log2);
8171 for (name, table) in
8172 [("has_tr", rect_reach_tables(bw, bh).0), ("has_bl", rect_reach_tables(bw, bh).1)]
8173 {
8174 assert_eq!(
8175 table.len() * 8,
8176 rows * cols,
8177 "{name}_{bw}x{bh}: libaom's table is {rows} rows of {cols} bits"
8178 );
8179 let mut seen = vec![0u32; table.len() * 8];
8180 for blk_row in 0..rows {
8181 for blk_col in 0..cols {
8182 let idx = Reach::rect_table_index(bw_log2, blk_row, blk_col);
8183 assert!(
8184 idx < seen.len(),
8185 "{name}_{bw}x{bh}: index {idx} past the table at ({blk_row},{blk_col})"
8186 );
8187 seen[idx] += 1;
8188 }
8189 }
8190 assert!(
8191 seen.iter().all(|&n| n == 1),
8192 "{name}_{bw}x{bh}: the block walk is not a bijection onto the table's bits \
8193 (row stride is not {cols})"
8194 );
8195 }
8196 }
8197 }
8198 use super::*;
8199 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
8200 use std::io::Write;
8201 use std::process::{Command, Stdio};
8202
8203 /// Every rectangular shape this decoder codes, at every position a block
8204 /// of that shape can sit inside a 64x64 superblock: [`Reach::of_rect`]
8205 /// must answer exactly what libaom's `has_top_right`/`has_bottom_left`
8206 /// (`reconintra.c`) answer, whose bodies are ported below.
8207 ///
8208 /// lane-tx4x8 r3 ([[enumerate-table-domain]], [[tool-disabled-in-every-gate]]):
8209 /// `rect_reach_tables` used to route every shape but 4x8/8x4/16x32 to the
8210 /// 32x16 row, so live 16x8 strips read the wrong bit at 10 (above-right)
8211 /// and 7 (below-left) of the 21 reachable positions with no gate seeing
8212 /// it. The per-shape `(len, byte sum)` fingerprints below come from the
8213 /// oracle's own arrays, so a re-routed or truncated table fails here even
8214 /// where the two rows happen to agree.
8215 ///
8216 /// Not covered (no parameter for either on `of_rect`): chroma `ss_x`/
8217 /// `ss_y`, and sub-block transforms (`row_off`/`col_off` > 0), which the
8218 /// callers handle by predicting each transform unit as its own block.
8219 /// `PARTITION_VERT_A`/`VERT_B` need no arm either: libaom's
8220 /// `has_tr_vert_tables`/`has_bl_vert_tables` entry for every RECT bsize is
8221 /// either the plain table itself (4x8, 8x16, 16x32, 32x64) or NULL
8222 /// (the horizontal shapes, which those partitions never produce).
8223 #[test]
8224 fn every_rect_shape_reaches_what_libaom_says_over_the_whole_superblock() {
8225 let fctx = &crate::decode::FrameCtx::new();
8226 // (bw, bh, has_tr len, has_tr byte sum, has_bl len, has_bl byte sum).
8227 const SHAPES: [(usize, usize, usize, u32, usize, u32); 14] = [
8228 (4, 8, 64, 9280, 64, 550),
8229 (8, 4, 64, 3712, 64, 9630),
8230 (8, 16, 16, 2352, 16, 134),
8231 (16, 8, 16, 960, 16, 2400),
8232 (16, 32, 4, 620, 4, 32),
8233 (32, 16, 4, 32, 4, 184),
8234 (32, 64, 1, 127, 1, 0),
8235 (64, 32, 1, 19, 1, 34),
8236 (4, 16, 32, 5472, 32, 14),
8237 (16, 4, 32, 960, 32, 6464),
8238 (8, 32, 8, 1400, 8, 2),
8239 (32, 8, 8, 32, 8, 1136),
8240 (16, 64, 2, 382, 2, 0),
8241 (64, 16, 2, 4, 2, 84),
8242 ];
8243 /// libaom `reconintra.c` `has_top_right`/`has_bottom_left`, ported for
8244 /// a block whose transform covers it whole (`row_off == col_off == 0`,
8245 /// `tx_size == bsize`) and luma (`ss_x == ss_y == 0`) on a 64-pixel
8246 /// superblock (`sb_mi_size == 16`).
8247 fn libaom_reach(
8248 bw: usize,
8249 bh: usize,
8250 x: usize,
8251 y: usize,
8252 width: usize,
8253 height: usize, _fctx: &crate::decode::FrameCtx,
8254 ) -> (bool, bool) {
8255 let (bw_log2, bh_log2) = ((bw / 4).ilog2() as usize, (bh / 4).ilog2() as usize);
8256 let (_bw_unit, bh_unit) = (bw / 4, bh / 4);
8257 let sb_mi_size = 16usize;
8258 let blk_row_in_sb = ((y / 4) & (sb_mi_size - 1)) >> bh_log2;
8259 let blk_col_in_sb = ((x / 4) & (sb_mi_size - 1)) >> bw_log2;
8260 let this_blk_index = (blk_row_in_sb << (5 - bw_log2)) + blk_col_in_sb;
8261 let (tr_table, bl_table) = rect_reach_tables(bw, bh);
8262 let bit = |t: &[u8]| (t[this_blk_index / 8] >> (this_blk_index % 8)) & 1 != 0;
8263 // has_top_right: top_available && right_available, then row_off == 0.
8264 let top_right = if y == 0 || x + bw >= width {
8265 false
8266 } else if blk_row_in_sb == 0 {
8267 // (`col_off + tx_wide_unit < plane_bw_unit` above this is
8268 // `bw_unit < bw_unit`, false for a whole-block transform.)
8269 true
8270 } else if ((blk_col_in_sb + 1) << bw_log2) >= sb_mi_size {
8271 false
8272 } else {
8273 bit(tr_table)
8274 };
8275 // has_bottom_left: bottom_available && left_available, col_off == 0.
8276 let bottom_left = if x == 0 || y + bh >= height {
8277 false
8278 } else if blk_col_in_sb == 0 {
8279 // (`row_off + tx_high_unit < plane_bh_unit` is likewise false.)
8280 (blk_row_in_sb << bh_log2) + bh_unit < sb_mi_size
8281 } else if ((blk_row_in_sb + 1) << bh_log2) >= sb_mi_size {
8282 false
8283 } else {
8284 bit(bl_table)
8285 };
8286 (top_right, bottom_left)
8287 }
8288 for (bw, bh, tr_len, tr_sum, bl_len, bl_sum) in SHAPES {
8289 let (tr, bl) = rect_reach_tables(bw, bh);
8290 let sum = |t: &[u8]| t.iter().map(|&b| u32::from(b)).sum::<u32>();
8291 assert_eq!(
8292 (tr.len(), sum(tr), bl.len(), sum(bl)),
8293 (tr_len, tr_sum, bl_len, bl_sum),
8294 "rect_reach_tables({bw}, {bh}) is not libaom's has_tr_{bw}x{bh}/has_bl_{bw}x{bh}"
8295 );
8296 // Two superblocks across and down, so the superblock-relative
8297 // position (and not the frame position) is what decides.
8298 for sb_y in [0usize, 64] {
8299 for sb_x in [0usize, 64] {
8300 for y in (sb_y..sb_y + 64).step_by(bh) {
8301 for x in (sb_x..sb_x + 64).step_by(bw) {
8302 let got = Reach::of_rect(bw, bh, x, y, 256, 256, fctx);
8303 let want = libaom_reach(bw, bh, x, y, 256, 256, fctx);
8304 assert_eq!(
8305 (got.above_right, got.below_left),
8306 want,
8307 "{bw}x{bh} at ({x}, {y})"
8308 );
8309 }
8310 }
8311 }
8312 }
8313 }
8314 }
8315
8316 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
8317 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
8318 /// aomenc gate decodes its stream through ffmpeg and is meaningless
8319 /// without it -- turns it into a hard failure. Without this the require
8320 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
8321 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
8322 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
8323 fn have_ffmpeg() -> bool {
8324 let present = Command::new("ffmpeg")
8325 .arg("-version")
8326 .stdout(Stdio::null())
8327 .stderr(Stdio::null())
8328 .status()
8329 .is_ok_and(|s| s.success());
8330 assert!(
8331 present
8332 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
8333 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
8334 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
8335 );
8336 present
8337 }
8338
8339 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
8340 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
8341 let mut child = Command::new("ffmpeg")
8342 .args([
8343 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
8344 ])
8345 .stdin(Stdio::piped())
8346 .stdout(Stdio::piped())
8347 .stderr(Stdio::piped())
8348 .spawn()
8349 .expect("ffmpeg failed to start");
8350 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
8351 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
8352 // fills before the last input byte is written -- which is exactly what
8353 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
8354 // (measured: 45 min, both processes at 0% CPU). A write error here is
8355 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
8356 // below, are the real diagnosis.
8357 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
8358 let payload = stream.to_vec();
8359 let writer = std::thread::spawn(move || {
8360 let _ = stdin.write_all(&payload);
8361 });
8362 let out = child.wait_with_output().expect("ffmpeg failed to run");
8363 writer.join().expect("ffmpeg stdin writer thread");
8364 assert!(
8365 out.status.success(),
8366 "ffmpeg refused the stream: {}",
8367 String::from_utf8_lossy(&out.stderr)
8368 );
8369 let (luma, chroma) = (width * height, width * height / 4);
8370 assert_eq!(
8371 out.stdout.len(),
8372 luma + 2 * chroma,
8373 "expected one 4:2:0 frame"
8374 );
8375 Picture {
8376 width,
8377 height,
8378 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
8379 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
8380 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
8381 }
8382 }
8383
8384 /// A picture with something of everything in it: a gradient, an edge, a
8385 /// ripple and a block of flat colour, none of them aligned to the block
8386 /// grid.
8387 /// The in-loop filters actually FIRE and the stream still decodes to
8388 /// exactly what the encoder kept as its reconstruction
8389 /// (gate-blind-to-feature: a filter search that always answered "off"
8390 /// would leave every other test just as green, and the BD gate that
8391 /// would notice is `#[ignore]`d).
8392 ///
8393 /// Run:
8394 /// cargo test -p ec-av1 --release --lib -- \
8395 /// encode::tests::the_filter_search_picks_real_filters
8396 #[test]
8397 fn the_filter_search_picks_real_filters() {
8398 let fctx = &crate::decode::FrameCtx::new();
8399 let pictures: Vec<_> = (0..3).map(|i| panned_test_card(128, 128, i * 3)).collect();
8400 let encoded = encode_sequence_with_ctx(&pictures, 120, 0.5, fctx).unwrap();
8401 let fired = encoded
8402 .frames
8403 .iter()
8404 .filter(|f| f.loop_filter.level[0] > 0 || f.cdef.y_pri_strength[0] > 0)
8405 .count();
8406 assert!(
8407 fired > 0,
8408 "no frame of this sequence chose any in-loop filtering: {:?}",
8409 encoded
8410 .frames
8411 .iter()
8412 .map(|f| (f.loop_filter.level, f.cdef.y_pri_strength[0]))
8413 .collect::<Vec<_>>()
8414 );
8415 // The reconstruction the encoder predicts from is the FILTERED one,
8416 // and it is what a decoder of the stream produces -- byte for byte,
8417 // frame for frame.
8418 let decoded = crate::stream::decode_stream(&encoded.stream).unwrap();
8419 assert_eq!(decoded.len(), encoded.frames.len());
8420 for (i, (dec, enc)) in decoded.iter().zip(&encoded.frames).enumerate() {
8421 assert_eq!(dec.y, enc.reconstruction.y, "frame {i} luma");
8422 assert_eq!(dec.u, enc.reconstruction.u, "frame {i} U");
8423 assert_eq!(dec.v, enc.reconstruction.v, "frame {i} V");
8424 }
8425 }
8426
8427 fn test_card(width: usize, height: usize) -> Picture {
8428 let mut picture = Picture::grey(width, height);
8429 for y in 0..height {
8430 for x in 0..width {
8431 let gradient = x as f64 * 200.0 / width as f64;
8432 let ripple = 30.0
8433 * (x as f64 * std::f64::consts::PI / 23.0).sin()
8434 * (y as f64 * std::f64::consts::PI / 37.0).cos();
8435 let edge = if x > width * 3 / 7 && y > height / 3 {
8436 40.0
8437 } else {
8438 0.0
8439 };
8440 picture.y[y * width + x] =
8441 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
8442 }
8443 }
8444 for y in 0..height / 2 {
8445 for x in 0..width / 2 {
8446 let i = y * width / 2 + x;
8447 picture.u[i] = (100 + (x * 60 / (width / 2))) as u16;
8448 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
8449 }
8450 }
8451 picture
8452 }
8453
8454 fn psnr(a: &[u16], b: &[u16]) -> f64 {
8455 let squared: f64 = a
8456 .iter()
8457 .zip(b)
8458 .map(|(&x, &y)| {
8459 let d = f64::from(x) - f64::from(y);
8460 d * d
8461 })
8462 .sum();
8463 if squared == 0.0 {
8464 return f64::INFINITY;
8465 }
8466 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
8467 }
8468
8469 /// The claim the whole encoder rests on: what a decoder produces is what
8470 /// the encoder said it would, sample for sample, on every plane.
8471 ///
8472 /// Prediction reads the reconstruction, so a single sample of drift
8473 /// anywhere would spread into every block below and to the right of it —
8474 /// which is why this is an equality and not a tolerance.
8475 #[test]
8476 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
8477 let fctx = &crate::decode::FrameCtx::new();
8478 if !have_ffmpeg() {
8479 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
8480 return;
8481 }
8482 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] {
8483 let picture = test_card(width, height);
8484 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8485 let decoded = ffmpeg_decode(&encoded.stream, width, height);
8486 assert_eq!(
8487 decoded.y, encoded.reconstruction.y,
8488 "{width}x{height}: luma"
8489 );
8490 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
8491 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
8492 }
8493 // One q index from each of the four coefficient-CDF contexts
8494 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
8495 let (width, height) = (64usize, 64usize);
8496 let picture = test_card(width, height);
8497 let _ = take_tx_depth_hits();
8498 for &q in &[15u8, 45, 100, 200] {
8499 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
8500 let decoded = ffmpeg_decode(&encoded.stream, width, height);
8501 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
8502 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
8503 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
8504 }
8505 // lane-av1tx: the exactness above is only a claim about SPLIT
8506 // transforms if some block actually split one (`gate-blind-to-feature`
8507 // -- with `tx_depth` stuck at 0 every assert here passes on the
8508 // pre-lane stream). The test card's edges split at these four
8509 // quantizers; the counter is per-process (another test encoding in
8510 // parallel can only ADD to it, so this can be masked, never falsely
8511 // failed), so it is read once for the whole q ladder.
8512 let depths = take_tx_depth_hits();
8513 assert!(
8514 depths[1] + depths[2] > 0,
8515 "no block split its transform: depths {depths:?}"
8516 );
8517 }
8518
8519 /// A synthetic screen-content picture -- a few flat colours in a grid of
8520 /// boxes with hard edges and text-like bars, the shape a desktop capture
8521 /// has -- so the palette path is exercised on content it is for.
8522 #[cfg(test)]
8523 fn screen_card(width: usize, height: usize) -> Picture {
8524 const INK: [u16; 4] = [16, 90, 180, 235];
8525 let mut picture = Picture::grey(width, height);
8526 for y in 0..height {
8527 for x in 0..width {
8528 let cell = (x / 24 + y / 24) % 2;
8529 let bar = usize::from(y % 24 < 6 && x % 24 >= 3 && x % 24 < 20);
8530 picture.y[y * width + x] = INK[cell * 2 + bar];
8531 }
8532 }
8533 // Four chroma colours, not two: a two-colour chroma block only ever
8534 // codes a `PaletteSizeUV` of 2, which leaves
8535 // `write_palette_colors_uv`'s cache/delta half (the n-1 shrinking
8536 // deltas and the neighbour cache flags, exercised only when
8537 // neighbouring blocks share colours) unproven by the ffmpeg oracle.
8538 const CHROMA_U: [u16; 4] = [96, 118, 150, 176];
8539 const CHROMA_V: [u16; 4] = [148, 126, 104, 92];
8540 for y in 0..height / 2 {
8541 for x in 0..width / 2 {
8542 let cell = (x / 12 + 2 * (y / 12)) % 4;
8543 picture.u[y * (width / 2) + x] = CHROMA_U[cell];
8544 picture.v[y * (width / 2) + x] = CHROMA_V[cell];
8545 }
8546 }
8547 picture
8548 }
8549
8550 /// The lane's own end-to-end check: on screen content the detector fires,
8551 /// blocks really take a palette (fire count, class
8552 /// `gate-blind-to-feature`), and ffmpeg -- libaom's own reader of every
8553 /// symbol this lane writes -- reconstructs exactly what the encoder did.
8554 /// The film-shaped `test_card` must NOT trip the detector, which is what
8555 /// keeps every non-screen stream byte-identical.
8556 #[test]
8557 fn a_screen_content_picture_codes_palette_blocks_ffmpeg_decodes_exactly() {
8558 let fctx = &crate::decode::FrameCtx::new();
8559 let (width, height) = (192usize, 96usize);
8560 let _ = crate::tile::take_palette_hits();
8561 let picture = screen_card(width, height);
8562 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8563 assert!(
8564 encoded.screen,
8565 "the detector did not fire on screen content -- no palette syntax was coded at all"
8566 );
8567 let hits = crate::tile::take_palette_hits();
8568 assert!(hits[0] > 0, "no block took a palette: {hits:?}");
8569 eprintln!("palette blocks {} sizes {:?}", hits[0], &hits[2..]);
8570 // The chroma half is a claim about the plane-1 syntax only if some
8571 // block really took a chroma palette (`gate-blind-to-feature`): every
8572 // exactness assert below passes on a stream that codes
8573 // `palette_uv_mode == 0` everywhere.
8574 let uv_hits = crate::tile::take_palette_uv_hits();
8575 assert!(uv_hits[0] > 0, "no block took a chroma palette: {uv_hits:?}");
8576 let uv_cached = crate::tile::take_palette_uv_cache_hits();
8577 eprintln!(
8578 "chroma palette blocks {} sizes {:?}, {uv_cached} colours from the neighbour cache",
8579 uv_hits[0],
8580 &uv_hits[2..]
8581 );
8582 assert!(
8583 uv_cached > 0,
8584 "no chroma base colour came out of the neighbour cache -- \
8585 `write_palette_colors_uv`'s cache half is unproven by the oracle below"
8586 );
8587 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
8588 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
8589 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
8590 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
8591 if !have_ffmpeg() {
8592 eprintln!("SKIP the ffmpeg half: no ffmpeg");
8593 return;
8594 }
8595 let decoded = ffmpeg_decode(&encoded.stream, width, height);
8596 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
8597 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
8598 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
8599 // A whole GOP: the inter frames' own intra blocks carry the palette
8600 // syntax too (the three intra arms of the inter writers), which only
8601 // ffmpeg reading the frames back can prove.
8602 let moved: Vec<Picture> = (0..4)
8603 .map(|f| {
8604 let base = screen_card(width, height);
8605 let mut out = Picture::grey(width, height);
8606 for y in 0..height {
8607 for x in 0..width {
8608 let sx = (x + f * 7) % width;
8609 out.y[y * width + x] = base.y[y * width + sx];
8610 }
8611 }
8612 for y in 0..height / 2 {
8613 for x in 0..width / 2 {
8614 let sx = (x + f * 3) % (width / 2);
8615 out.u[y * (width / 2) + x] = base.u[y * (width / 2) + sx];
8616 out.v[y * (width / 2) + x] = base.v[y * (width / 2) + sx];
8617 }
8618 }
8619 out
8620 })
8621 .collect();
8622 let _ = crate::tile::take_palette_hits();
8623 let _ = crate::tile::take_palette_uv_hits();
8624 let gop = encode_sequence_with_ctx(&moved, 100, 0.5, fctx).unwrap();
8625 let gop_hits = crate::tile::take_palette_hits();
8626 let gop_uv_hits = crate::tile::take_palette_uv_hits();
8627 let inter_screen = gop.frames.iter().skip(1).filter(|f| f.screen).count();
8628 eprintln!(
8629 "GOP: {} frames with screen tools after the key frame, {} palette blocks, \
8630 {} chroma palette blocks",
8631 inter_screen, gop_hits[0], gop_uv_hits[0]
8632 );
8633 assert!(
8634 gop_uv_hits[0] > 0,
8635 "no block of the GOP took a chroma palette: {gop_uv_hits:?}"
8636 );
8637 assert!(
8638 inter_screen > 0,
8639 "no inter frame set allow_screen_content_tools"
8640 );
8641 let gop_decoded = crate::stream::decode_stream(&gop.stream).unwrap();
8642 for (i, (ours, frame)) in gop_decoded.iter().zip(gop.frames.iter()).enumerate() {
8643 assert_eq!(ours.y, frame.reconstruction.y, "our decoder: GOP frame {i} luma");
8644 }
8645 if have_ffmpeg() {
8646 let ff = ffmpeg_decode_sequence(&gop.stream, width, height, moved.len());
8647 for (i, (theirs, frame)) in ff.iter().zip(gop.frames.iter()).enumerate() {
8648 assert_eq!(theirs.y, frame.reconstruction.y, "ffmpeg: GOP frame {i} luma");
8649 assert_eq!(theirs.u, frame.reconstruction.u, "ffmpeg: GOP frame {i} U");
8650 assert_eq!(theirs.v, frame.reconstruction.v, "ffmpeg: GOP frame {i} V");
8651 }
8652 }
8653
8654 // The other half of the keep rule: film-shaped content leaves the
8655 // detector (and so the whole sequence header) alone.
8656 let film = encode_key_frame_with_ctx(&test_card(width, height), 100, 0.5, fctx).unwrap();
8657 assert!(!film.screen, "the detector fired on the film-shaped test card");
8658 }
8659
8660 /// The lane's keep-rule measurement: the gate's own screen capture, one
8661 /// KEY FRAME, coded with and without `allow_intrabc` at four quantizers.
8662 /// Setting the bit forces deblocking, CDEF and loop restoration off for
8663 /// that frame, so the table is exactly the filter loss against the bytes
8664 /// the copied blocks save.
8665 #[test]
8666 #[ignore = "needs the real-library manifest and ffmpeg"]
8667 fn probe_intrabc_key_frame() {
8668 let fctx = &crate::decode::FrameCtx::new();
8669 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
8670 .join("../../fixtures");
8671 let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) else {
8672 eprintln!("SKIP probe_intrabc_key_frame: no real-library manifest");
8673 return;
8674 };
8675 let Some(clip) = manifest
8676 .lines()
8677 .skip(1)
8678 .filter_map(|l| l.split('\t').next())
8679 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
8680 else {
8681 eprintln!("SKIP probe_intrabc_key_frame: no OBS recording");
8682 return;
8683 };
8684 let (width, height) = (640usize, 384usize);
8685 let picture = clip_frame(clip, "0", width, height);
8686 eprintln!("| base_q_idx | intrabc | bytes | PSNR | blocks | searches/found/won |");
8687 for q in [5u8, 20, 35, 45] {
8688 for on in [false, true] {
8689 force_intrabc(Some(on));
8690 let _ = crate::tile::take_intrabc_hits();
8691 let _ = take_intrabc_search();
8692 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
8693 let hits = crate::tile::take_intrabc_hits();
8694 let search = take_intrabc_search();
8695 eprintln!(
8696 "| {q} | {} | {} | {:.2} dB | {} (dv hist {:?}) | {}/{}/{} |",
8697 if encoded.allow_intrabc { "on" } else { "off" },
8698 encoded.stream.len(),
8699 psnr_all(&encoded.reconstruction, &picture),
8700 hits[0],
8701 &hits[1..],
8702 search[0], search[1], search[2],
8703 );
8704 }
8705 }
8706 force_intrabc(None);
8707 }
8708
8709 /// lane-av1ibc's own end-to-end check: a repeated-pattern screen card
8710 /// sets `allow_intrabc` (so every in-loop filter is off), blocks really
8711 /// take a block vector (fire count + DV histogram, class
8712 /// `gate-blind-to-feature`), and both our own decoder and ffmpeg --
8713 /// libaom's reader of the `use_intrabc`/`assign_dv` syntax -- reconstruct
8714 /// exactly what the encoder did.
8715 #[test]
8716 fn a_repeated_pattern_key_frame_codes_intrabc_blocks_ffmpeg_decodes_exactly() {
8717 let fctx = &crate::decode::FrameCtx::new();
8718 // Wide enough for the wavefront rule (`INTRABC_DELAY_SB64` = 4
8719 // superblocks of 64) and tall enough for a source superblock row
8720 // above the blocks that copy from it.
8721 let (width, height) = (512usize, 256usize);
8722 let picture = screen_card(width, height);
8723 let _ = crate::tile::take_intrabc_hits();
8724 // The default is OFF (it measured worse on the real screen capture --
8725 // see [`intrabc_enabled`]); this gate proves the SYNTAX, so it turns
8726 // the arm on for its own encode and puts it back straight after.
8727 force_intrabc(Some(true));
8728 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8729 force_intrabc(None);
8730 assert!(
8731 encoded.allow_intrabc,
8732 "allow_intrabc was not set on a fully periodic screen card (source repeat share {:.1}%)",
8733 intrabc_source_share() * 100.0
8734 );
8735 let hits = crate::tile::take_intrabc_hits();
8736 eprintln!(
8737 "intrabc blocks {} DV magnitude histogram (1,2,4,8,16,32+ px) {:?}, source repeat share {:.1}%",
8738 hits[0],
8739 &hits[1..],
8740 intrabc_source_share() * 100.0
8741 );
8742 let search = take_intrabc_search();
8743 eprintln!(
8744 "intrabc searches {} found-valid {} won-RD {}",
8745 search[0], search[1], search[2]
8746 );
8747 assert!(
8748 hits[0] > 0,
8749 "no block took a block vector -- the `use_intrabc` syntax is unproven: {hits:?}"
8750 );
8751 let via_us = crate::stream::decode_stream(&encoded.stream).unwrap();
8752 assert_eq!(via_us[0].y, encoded.reconstruction.y, "our decoder: luma");
8753 assert_eq!(via_us[0].u, encoded.reconstruction.u, "our decoder: U");
8754 assert_eq!(via_us[0].v, encoded.reconstruction.v, "our decoder: V");
8755 if !have_ffmpeg() {
8756 eprintln!("SKIP the ffmpeg half: no ffmpeg");
8757 return;
8758 }
8759 let decoded = ffmpeg_decode(&encoded.stream, width, height);
8760 assert_eq!(decoded.y, encoded.reconstruction.y, "ffmpeg: luma");
8761 assert_eq!(decoded.u, encoded.reconstruction.u, "ffmpeg: U");
8762 assert_eq!(decoded.v, encoded.reconstruction.v, "ffmpeg: V");
8763 }
8764
8765 /// The minimal repro that isolated the inter-residual desync: a key frame
8766 /// followed by one inter frame whose single superblock carries one
8767 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
8768 /// coefficient, its three sibling blocks all `skip: true`. Before the
8769 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
8770 /// found when processing input") even though every symbol either block
8771 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
8772 /// same coefficient syntax decodes clean on every intra key-frame gate).
8773 #[test]
8774 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
8775 let fctx = &crate::decode::FrameCtx::new();
8776 if !have_ffmpeg() {
8777 eprintln!(
8778 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
8779 );
8780 return;
8781 }
8782 let (width, height) = (64usize, 64usize);
8783 let picture = Picture::grey(width, height);
8784 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8785
8786 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
8787 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
8788
8789 let residual_block = BlockCoeffs {
8790 luma: vec![Coeff {
8791 row: 0,
8792 col: 0,
8793 level: 4,
8794 }],
8795 u: Vec::new(),
8796 v: Vec::new(),
8797 mode: 0,
8798 uv_mode: 0,
8799 skip: false,
8800 eight: None,
8801 dv: None,
8802 palette: None,
8803 palette_uv: None,
8804 tx_depth: 0,
8805 inter: Some(InterInfo {
8806 ref1: None,
8807 mv1: (0, 0),
8808 ref_frame: crate::mvstack::LAST_FRAME,
8809 mode: InterMode::NearestMv,
8810 mv: (0, 0),
8811 ref_mv_idx: 0,
8812 }),
8813 motion_mode: 0,
8814 };
8815 let skipped_block = BlockCoeffs {
8816 skip: true,
8817 inter: Some(InterInfo {
8818 ref1: None,
8819 mv1: (0, 0),
8820 ref_frame: crate::mvstack::LAST_FRAME,
8821 mode: InterMode::NearestMv,
8822 mv: (0, 0),
8823 ref_mv_idx: 0,
8824 }),
8825 ..BlockCoeffs::default()
8826 };
8827 let blocks = vec![
8828 Quadrant::Whole(residual_block),
8829 Quadrant::Whole(skipped_block.clone()),
8830 Quadrant::Whole(skipped_block.clone()),
8831 Quadrant::Whole(skipped_block),
8832 ];
8833 // lane-av1obmc: the header this tile is decoded under carries
8834 // `is_motion_mode_switchable`, so the writer must be armed with it
8835 // too or the decoder reads a `motion_mode` symbol nobody wrote.
8836 crate::tile::arm_motion_mode(inter_header.is_motion_mode_switchable);
8837 crate::tile::arm_warped_motion(inter_header.allow_warped_motion);
8838 let tile =
8839 crate::tile::sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
8840 .unwrap();
8841
8842 // `key.stream` is already a temporal delimiter, the sequence header
8843 // and the key frame's own OBU (`encode_key_frame` built it from the
8844 // same `key_frame_headers(width, height, 100)` this test calls), so
8845 // the inter frame's OBU is appended straight onto it rather than
8846 // re-deriving the key frame's tile bytes.
8847 let mut stream = key.stream.clone();
8848 stream.extend_from_slice(&temporal_delimiter());
8849 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
8850
8851 ffmpeg_decode_sequence(&stream, width, height, 2);
8852 }
8853
8854 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
8855 /// frame size an AV1 decoder allocates, not necessarily the render size
8856 /// (see [`a_frame_round_trips_at_its_own_size`]).
8857 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
8858 // Distinct per call, not per process: the test binary runs callers on
8859 // parallel threads, and a shared name lets one test's cleanup delete
8860 // the stream another test's ffprobe is still reading.
8861 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
8862 let path = std::env::temp_dir().join(format!(
8863 "ec-av1-probe-{}-{}.obu",
8864 std::process::id(),
8865 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
8866 ));
8867 let _ = std::fs::remove_file(&path);
8868 std::fs::write(&path, stream).expect("writing the probe stream");
8869 let out = Command::new("ffprobe")
8870 .args([
8871 "-v",
8872 "error",
8873 "-f",
8874 "obu",
8875 "-select_streams",
8876 "v:0",
8877 "-show_entries",
8878 "stream=width,height",
8879 "-of",
8880 "csv=p=0",
8881 ])
8882 .arg(&path)
8883 .output()
8884 .expect("ffprobe failed to run");
8885 let _ = std::fs::remove_file(&path);
8886 assert!(
8887 out.status.success(),
8888 "ffprobe refused the stream: {}",
8889 String::from_utf8_lossy(&out.stderr)
8890 );
8891 let text = String::from_utf8_lossy(&out.stdout);
8892 let mut fields = text.trim().split(',');
8893 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
8894 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
8895 (width, height)
8896 }
8897
8898 /// A key frame at an arbitrary even size round-trips through ffmpeg over
8899 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
8900 /// picture's own size, and what ffmpeg decodes over that same top-left
8901 /// region equals it sample for sample.
8902 ///
8903 /// This does not check that `ffprobe` reports the picture's own size,
8904 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
8905 /// (block-padded) frame size, the same one libaom itself would code for
8906 /// a non-block-aligned picture. `render_width`/`render_height` (which
8907 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
8908 /// decoder is required to crop pixels by, and ffmpeg's does not --
8909 /// checked empirically against ffprobe here and against a real libaom
8910 /// encode separately. So the coded size, not the render size, is what
8911 /// `ffprobe` is asserted to report below.
8912 #[test]
8913 fn a_frame_round_trips_at_its_own_size() {
8914 let fctx = &crate::decode::FrameCtx::new();
8915 if !have_ffmpeg() {
8916 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
8917 return;
8918 }
8919 // 854x480 is covered separately by
8920 // `an_854x480_picture_round_trips_through_its_padding`, which its own
8921 // doc comment explains was worth keeping as its own test.
8922 for &(width, height) in &[
8923 (1920usize, 1080usize),
8924 (640, 352),
8925 (1280, 720),
8926 (64, 56),
8927 (854, 480),
8928 (216, 96),
8929 (192, 120),
8930 ] {
8931 let picture = test_card(width, height);
8932 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8933 assert_eq!(
8934 (encoded.reconstruction.width, encoded.reconstruction.height),
8935 (width, height),
8936 "{width}x{height}: reconstruction is cropped to the picture's own size"
8937 );
8938 assert_eq!(
8939 ffprobe_size(&encoded.stream),
8940 (width as u32, height as u32),
8941 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
8942 );
8943 let decoded = ffmpeg_decode(&encoded.stream, width, height);
8944 assert_eq!(
8945 decoded.y, encoded.reconstruction.y,
8946 "{width}x{height}: luma"
8947 );
8948 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
8949 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
8950 }
8951 }
8952
8953 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
8954 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
8955 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
8956 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
8957 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
8958 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
8959 /// col`) -- different bits of an 8-byte table, one true, one false. The
8960 /// stride libaom indexes by is fixed at its compile-time maximum
8961 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
8962 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
8963 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
8964 /// row/col position within the (correctly 64-relative) superblock stayed
8965 /// right, only the table's own row stride was wrong. Fixed in
8966 /// `Reach::table_stride`; not an arithmetic-coder desync (an
8967 /// EC_RNG-per-symbol trace against the same debug decoder found the
8968 /// bitstream byte-for-byte identical to libaom's across all 51188
8969 /// symbols of this frame before this bug was found).
8970 ///
8971 /// Since the frame header started writing the true (unpadded) display
8972 /// size into `frame_width`/`frame_height` rather than the padded coded
8973 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
8974 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
8975 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
8976 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
8977 /// the header's own size before output).
8978 #[test]
8979 fn an_854x480_picture_round_trips_through_its_padding() {
8980 let fctx = &crate::decode::FrameCtx::new();
8981 if !have_ffmpeg() {
8982 return;
8983 }
8984 let (width, height) = (854usize, 480usize);
8985 let picture = test_card(width, height);
8986 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
8987 let decoded = ffmpeg_decode(&encoded.stream, width, height);
8988 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
8989 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
8990 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
8991 }
8992
8993 /// [`Reach::of_tu`] against libaom's `has_top_right`/`has_bottom_left`
8994 /// transform-unit path, for every 4x4 unit of every 8x8 block of a
8995 /// superblock, both partition tables:
8996 ///
8997 /// 1. outside a `PARTITION_VERT_A`/`_B` it must answer exactly what the
8998 /// unit-as-its-own-block `Reach::of(4, ..)` answered before r2, so
8999 /// wiring the TU sites onto it changes no existing stream;
9000 /// 2. inside one it must not panic -- `has_tr_vert_tables[BLOCK_4X4]` is
9001 /// NULL in libaom because that lookup never happens, and reading a
9002 /// 4x4 row out of the three-row vert tables is what crashed a real
9003 /// `--enable-tx-size-search=1` stream (r2);
9004 /// 3. and it must be the BLOCK's vert answer where the two tables
9005 /// disagree: the top-right 4x4 unit of the 8x8 block at superblock
9006 /// row 1, column 0 reads its above-right samples from the 8x8 to its
9007 /// upper right, which a vertical AB partition codes AFTER it
9008 /// (`has_tr_vert_8x8` bit 16 = 0, ordinary `has_tr_8x8` bit 16 = 1).
9009 #[test]
9010 fn of_tu_follows_the_block_row_including_under_vert_ab() {
9011 let fctx = &crate::decode::FrameCtx::new();
9012 // The 8x8 square at superblock row 1, column 0, and the TX4 unit in
9013 // its top-right corner (`col_off = 4`, `row_off = 0`): that unit's
9014 // above-right answer is the BLOCK's, which is the whole reason a unit
9015 // asks the block instead of looking itself up (the
9016 // `has_tr_vert_*` tables have no 4x4 row at all, lane-ab16 r2).
9017 let plain = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
9018 assert_eq!(
9019 Reach::of_tu(8, 8, 4, 0, 4, 4, plain).above_right,
9020 plain.above_right,
9021 "ordinary table: the top-right TX4 unit takes the block's row"
9022 );
9023 let guard = Reach::vert_ab_partition();
9024 let vert = Reach::of(8, 0, 8, SUPERBLOCK, SUPERBLOCK, fctx);
9025 assert_eq!(
9026 Reach::of_tu(8, 8, 4, 0, 4, 4, vert).above_right,
9027 vert.above_right,
9028 "vert AB: the unit follows the vert row the block just picked"
9029 );
9030 assert_ne!(
9031 plain.above_right, vert.above_right,
9032 "this position is the cell where the vert tables disagree; pick another if libaom's tables change"
9033 );
9034 drop(guard);
9035 }
9036
9037 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
9038 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
9039 /// reconintra.c`), for every 16x16 and 32x32 block position across three
9040 /// superblocks square -- interior and every superblock edge (top row,
9041 /// left column, right column, bottom row) both sizes reach. Written to
9042 /// catch the class the `table_stride` bug was: an index stride silently
9043 /// wrong for one block size while looking plausible for the other.
9044 #[test]
9045 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
9046 let fctx = &crate::decode::FrameCtx::new();
9047 // Transcribed from has_top_right/has_bottom_left's row_off==0,
9048 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
9049 // 128px reference grid) pinned as libaom pins it, independent of the
9050 // 64px superblock this crate actually codes.
9051 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, _height: usize) -> bool {
9052 if y == 0 || x + side >= width {
9053 return false;
9054 }
9055 let (row, col, per_side) = (
9056 (y % SUPERBLOCK) / side,
9057 (x % SUPERBLOCK) / side,
9058 SUPERBLOCK / side,
9059 );
9060 if row == 0 {
9061 return true;
9062 }
9063 if col + 1 == per_side {
9064 return false;
9065 }
9066 let stride = 128 / side;
9067 let index = row * stride + col;
9068 let table = if side == BLOCK {
9069 [95u8, 87].to_vec()
9070 } else {
9071 vec![255, 85, 119, 85, 127, 85, 119, 85]
9072 };
9073 (table[index / 8] >> (index % 8)) & 1 != 0
9074 }
9075
9076 fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize, _fctx: &crate::decode::FrameCtx) -> bool {
9077 if x == 0 || y + side >= height {
9078 return false;
9079 }
9080 let (row, col, per_side) = (
9081 (y % SUPERBLOCK) / side,
9082 (x % SUPERBLOCK) / side,
9083 SUPERBLOCK / side,
9084 );
9085 if col == 0 {
9086 return row * side + side < SUPERBLOCK;
9087 }
9088 if row + 1 == per_side {
9089 return false;
9090 }
9091 let stride = 128 / side;
9092 let index = row * stride + col;
9093 let table = if side == BLOCK {
9094 [4u8, 4].to_vec()
9095 } else {
9096 vec![84, 16, 84, 0, 84, 16, 84, 0]
9097 };
9098 (table[index / 8] >> (index % 8)) & 1 != 0
9099 }
9100
9101 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
9102 for side in [16usize, BLOCK] {
9103 for y in (0..height).step_by(side) {
9104 for x in (0..width).step_by(side) {
9105 let reach = Reach::of(side, x, y, width, height, fctx);
9106 assert_eq!(
9107 reach.above_right,
9108 libaom_top_right(side, x, y, width, height),
9109 "side={side} x={x} y={y}: above_right"
9110 );
9111 assert_eq!(
9112 reach.below_left,
9113 libaom_bottom_left(side, x, y, height, fctx),
9114 "side={side} x={x} y={y}: below_left"
9115 );
9116 }
9117 }
9118 }
9119 }
9120
9121 /// lane-part32 r6: inside a `PARTITION_VERT_A`/`_B` the 8x8 squares are
9122 /// visited TL, BL, TR, BR, so the TR square (even 8x8 row, odd 8x8
9123 /// column inside the superblock) may read the below-left samples the
9124 /// raster table forbids: `has_bl_8x8` is 0 at exactly those 16 slots
9125 /// where `has_bl_vert_8x8` is 1. Pinned here because no aomenc recipe
9126 /// swept in r6 produced a decodable 16x16-level VERT_B stream (every
9127 /// stream that partitions that small first hits the still-refused
9128 /// HORZ_A/HORZ_B/VERT_A-below-16 or coded-rect-strip-below-16 arms).
9129 /// [`Reach::of_tu`] against a from-scratch transcription of libaom's
9130 /// `has_top_right`/`has_bottom_left` TU branches (`reconintra.c`, luma,
9131 /// `ss_x = ss_y = 0`), which work in MI units where `of_tu` works in
9132 /// pixels -- lane-palette2 r12: the square multi-TU path used the
9133 /// standalone-block tables instead of this rule and granted a 16x16
9134 /// D203 block's top-right 8x8 unit bottom-left pixels libaom refuses.
9135 #[test]
9136 fn of_tu_matches_libaom_has_top_right_and_has_bottom_left_per_unit() {
9137 // libaom, in MI units: bw_unit/bh_unit = block size / 4,
9138 // *_count_unit = tx size / 4.
9139 fn libaom_tr(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
9140 let (plane_bw_unit, count) = (bw / 4, tx / 4);
9141 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
9142 let _ = bh;
9143 if row_off_u > 0 {
9144 col_off_u + count < plane_bw_unit
9145 } else if col_off_u + count < plane_bw_unit {
9146 true
9147 } else {
9148 blk
9149 }
9150 }
9151 fn libaom_bl(bw: usize, bh: usize, col_off: usize, row_off: usize, tx: usize, blk: bool) -> bool {
9152 let (plane_bh_unit, count) = (bh / 4, tx / 4);
9153 let (col_off_u, row_off_u) = (col_off / 4, row_off / 4);
9154 let _ = bw;
9155 if col_off_u > 0 {
9156 false
9157 } else if row_off_u + count < plane_bh_unit {
9158 true
9159 } else {
9160 blk
9161 }
9162 }
9163 for &(bw, bh) in &[(8, 8), (16, 16), (32, 32), (64, 64), (16, 8), (8, 16), (32, 16), (16, 32), (64, 32), (32, 64)] {
9164 for &tx in &[4usize, 8, 16, 32] {
9165 if tx > bw.min(bh) {
9166 continue;
9167 }
9168 for row_off in (0..bh).step_by(tx) {
9169 for col_off in (0..bw).step_by(tx) {
9170 for &blk in &[Reach { above_right: false, below_left: false }, Reach { above_right: true, below_left: true }] {
9171 let got = Reach::of_tu(bw, bh, col_off, row_off, tx, tx, blk);
9172 assert_eq!(
9173 got.above_right,
9174 libaom_tr(bw, bh, col_off, row_off, tx, blk.above_right),
9175 "above_right bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
9176 );
9177 assert_eq!(
9178 got.below_left,
9179 libaom_bl(bw, bh, col_off, row_off, tx, blk.below_left),
9180 "below_left bw={bw} bh={bh} tx={tx} row_off={row_off} col_off={col_off} blk={blk:?}"
9181 );
9182 }
9183 }
9184 }
9185 }
9186 }
9187 }
9188
9189 #[test]
9190 fn vert_ab_partition_flips_below_left_for_the_top_right_8x8() {
9191 let fctx = &crate::decode::FrameCtx::new();
9192 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
9193 // Interior superblock, so neither the frame edge nor the col == 0 /
9194 // last-row early returns answer instead of the table.
9195 let (sb_x, sb_y) = (SUPERBLOCK, SUPERBLOCK);
9196 let mut flipped = 0;
9197 for row in 0..8 {
9198 for col in 1..8 {
9199 let (x, y) = (sb_x + col * 8, sb_y + row * 8);
9200 let raster = Reach::of(8, x, y, width, height, fctx).below_left;
9201 let vert = {
9202 let _guard = Reach::vert_ab_partition();
9203 Reach::of(8, x, y, width, height, fctx).below_left
9204 };
9205 // The TR square of a VERT_A/_B sits at an even row, odd
9206 // column; every other slot must be untouched by the guard.
9207 if row % 2 == 0 && col % 2 == 1 {
9208 assert!(!raster, "raster below_left at row={row} col={col}");
9209 assert!(vert, "vert below_left at row={row} col={col}");
9210 flipped += 1;
9211 } else {
9212 assert_eq!(raster, vert, "guard moved row={row} col={col}");
9213 }
9214 }
9215 }
9216 assert_eq!(flipped, 4 * 4, "expected the 16 8x8 TR slots to flip");
9217 // The guard is scoped: it must not leak past its own block.
9218 assert!(!Reach::of(8, sb_x + 8, sb_y, width, height, fctx).below_left);
9219 }
9220
9221 /// An odd width or height is refused by name, not by however the padder
9222 /// or the block coder would happen to fail on it.
9223 #[test]
9224 fn odd_dimensions_are_refused() {
9225 let fctx = &crate::decode::FrameCtx::new();
9226 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
9227 let picture = Picture::grey(width, height);
9228 let err = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx)
9229 .expect_err(&format!("{width}x{height} is odd and must be refused"));
9230 assert!(
9231 err.to_string().contains("even"),
9232 "{width}x{height}: error was {err}"
9233 );
9234 }
9235 }
9236
9237 /// A sequence at a size that is not a multiple of the block grid decodes
9238 /// to the right frame count and the right size for every frame,
9239 /// including the inter frames whose reference is the previous frame's
9240 /// own (padded) reconstruction.
9241 #[test]
9242 fn sequence_round_trips_at_a_non_multiple_size() {
9243 let fctx = &crate::decode::FrameCtx::new();
9244 if !have_ffmpeg() {
9245 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
9246 return;
9247 }
9248 let (width, height) = (160usize, 96usize);
9249 let pictures: Vec<Picture> = (0..3)
9250 .map(|i| panned_test_card(width, height, i * 3))
9251 .collect();
9252 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
9253 assert_eq!(encoded.frames.len(), 3);
9254 for (i, frame) in encoded.frames.iter().enumerate() {
9255 assert_eq!(
9256 (frame.reconstruction.width, frame.reconstruction.height),
9257 (width, height),
9258 "frame {i}: reconstruction size"
9259 );
9260 }
9261 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
9262 // true (display) size a sequence's frames share, not the padded one.
9263 assert_eq!(
9264 ffprobe_size(&encoded.stream),
9265 (width as u32, height as u32),
9266 "sequence: ffprobe reports the true (display) size"
9267 );
9268 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
9269 assert_eq!(decoded.len(), 3, "decoded frame count");
9270 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
9271 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
9272 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
9273 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
9274 }
9275 }
9276
9277 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
9278 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
9279 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
9280 /// `pos + side_mi / 2 < bound` boundary), which is the case
9281 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
9282 /// refusing. A key frame alone already covered this size; this proves the
9283 /// inter tile writer's parity with it across a real multi-frame export.
9284 #[test]
9285 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
9286 let fctx = &crate::decode::FrameCtx::new();
9287 if !have_ffmpeg() {
9288 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
9289 return;
9290 }
9291 let (width, height) = (1280usize, 720usize);
9292 let pictures: Vec<Picture> = (0..3)
9293 .map(|i| panned_test_card(width, height, i * 3))
9294 .collect();
9295 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
9296 assert_eq!(encoded.frames.len(), 3);
9297 for (i, frame) in encoded.frames.iter().enumerate() {
9298 assert_eq!(
9299 (frame.reconstruction.width, frame.reconstruction.height),
9300 (width, height),
9301 "frame {i}: reconstruction size"
9302 );
9303 }
9304 assert_eq!(
9305 ffprobe_size(&encoded.stream),
9306 (width as u32, height as u32),
9307 "ffprobe reports the true (display) 1280x720 size"
9308 );
9309 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
9310 assert_eq!(decoded.len(), 3, "decoded frame count");
9311 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
9312 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
9313 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
9314 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
9315 }
9316 }
9317
9318 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
9319 /// leaf's own half (`has_half` at the SUB level) itself straddles the
9320 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
9321 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
9322 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
9323 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
9324 /// straddling-16x16 branch), so an inter frame no longer refuses this
9325 /// size either. This only proves the encoder does not error out -- see
9326 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
9327 /// decoder-clean proof (a 3-frame sequence, so the inter path is
9328 /// actually exercised).
9329 #[test]
9330 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
9331 let fctx = &crate::decode::FrameCtx::new();
9332 let (width, height) = (640usize, 360usize);
9333 let picture = Picture::grey(width, height);
9334 encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).expect("key frame now codes the mod-32==8 straddle");
9335
9336 // `encode_sequence`'s second frame is the inter path: same size, now
9337 // wired the same way.
9338 let pictures = vec![picture.clone(), picture];
9339 encode_sequence_with_ctx(&pictures, 100, 0.5, fctx)
9340 .expect("inter frame now codes the mod-32==8 straddle too");
9341 }
9342
9343 /// The r15 fix at production size: three 640x360 key frames (inter is
9344 /// still refused at this size, per the test above, so this stands in for
9345 /// the charter's "3-frame sequence" using three independent key frames of
9346 /// shifted content), each proven decoder-clean through ffmpeg rather than
9347 /// only encoder-clean.
9348 #[test]
9349 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
9350 let fctx = &crate::decode::FrameCtx::new();
9351 if !have_ffmpeg() {
9352 eprintln!(
9353 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
9354 no ffmpeg"
9355 );
9356 return;
9357 }
9358 let (width, height) = (640usize, 360usize);
9359 for shift in [0i64, 7, 19] {
9360 let picture = panned_test_card(width, height, shift);
9361 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
9362 let decoded = ffmpeg_decode(&encoded.stream, width, height);
9363 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
9364 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
9365 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
9366 }
9367 }
9368
9369 /// The 640x360 straddle class, but through the inter path an actual
9370 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
9371 /// proves the leaf-8 inter stream this round wires up is not just
9372 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
9373 #[test]
9374 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
9375 let fctx = &crate::decode::FrameCtx::new();
9376 if !have_ffmpeg() {
9377 eprintln!(
9378 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
9379 );
9380 return;
9381 }
9382 let (width, height) = (640usize, 360usize);
9383 let pictures: Vec<Picture> = (0..4)
9384 .map(|i| panned_test_card(width, height, i * 3))
9385 .collect();
9386 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
9387 assert_eq!(encoded.frames.len(), 4);
9388 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
9389 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
9390 }
9391 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
9392 assert_eq!(decoded.len(), 4, "decoded frame count");
9393 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
9394 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
9395 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
9396 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
9397 }
9398 }
9399
9400 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
9401 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
9402 let out = Command::new("ffmpeg")
9403 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
9404 .args(["-vf", &format!("scale={width}:{height}")])
9405 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
9406 .output()
9407 .expect("ffmpeg failed to run");
9408 assert!(
9409 out.status.success(),
9410 "ffmpeg: {}",
9411 String::from_utf8_lossy(&out.stderr)
9412 );
9413 let (luma, chroma) = (width * height, width * height / 4);
9414 assert_eq!(
9415 out.stdout.len(),
9416 luma + 2 * chroma,
9417 "expected one 4:2:0 frame"
9418 );
9419 Picture {
9420 width,
9421 height,
9422 y: out.stdout[..luma].iter().map(|&v| u16::from(v)).collect(),
9423 u: out.stdout[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
9424 v: out.stdout[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
9425 }
9426 }
9427
9428 /// Prints what the mode search saves over DC prediction alone, for the
9429 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
9430 /// weight the search puts on rate can be swept.
9431 #[test]
9432 #[ignore = "a sweep, not a gate"]
9433 fn probe_lambda() {
9434 let fctx = &crate::decode::FrameCtx::new();
9435 let mut pictures = vec![
9436 ("test card".to_string(), test_card(160, 96)),
9437 ("stripes".to_string(), stripes(160, 96, true)),
9438 ];
9439 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
9440 for entry in clips.split(':').filter(|e| !e.is_empty()) {
9441 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
9442 let name = path.rsplit('/').next().unwrap_or(path).to_string();
9443 pictures.push((name, clip_frame(path, skip, 640, 352)));
9444 }
9445 }
9446 for (name, picture) in pictures {
9447 let dc = ladder(&picture, &[DC_PRED], fctx);
9448 let searched = ladder(&picture, &NON_DIRECTIONAL, fctx);
9449 println!(
9450 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
9451 bd_rate(&dc, &searched) * 100.0,
9452 10f64.powf(searched[1].1),
9453 searched[1].0,
9454 10f64.powf(dc[1].1),
9455 dc[1].0,
9456 );
9457 }
9458 }
9459
9460 /// Prints the whole mode-search ladder, so two builds of the search can be
9461 /// compared against each other rather than each against its own baseline.
9462 #[test]
9463 #[ignore = "a sweep, not a gate"]
9464 fn probe_ladder() {
9465 let fctx = &crate::decode::FrameCtx::new();
9466 for (name, picture) in sweep_pictures() {
9467 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
9468 let points = all
9469 .iter()
9470 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
9471 .collect::<Vec<_>>()
9472 .join(" ");
9473 println!("ladder {name}: {points}");
9474 }
9475 }
9476
9477 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
9478 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
9479 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
9480 #[test]
9481 #[ignore = "a sweep, not a gate"]
9482 fn probe_split() {
9483 let fctx = &crate::decode::FrameCtx::new();
9484 for (name, picture) in sweep_pictures() {
9485 let ladder = |split: bool| {
9486 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
9487 .iter()
9488 .map(|&q| {
9489 let encoded = encode_key_frame_inner(
9490 &picture,
9491 q,
9492 0.5,
9493 &KEY_FRAME_MODES,
9494 split,
9495 (picture.width, picture.height),
9496 unspecified_color_config(), fctx,
9497 )
9498 .unwrap();
9499 (
9500 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
9501 (encoded.stream.len() as f64).log10(),
9502 )
9503 })
9504 .collect();
9505 points.sort_by(|a, b| a.0.total_cmp(&b.0));
9506 points
9507 };
9508 let (whole, split) = (ladder(false), ladder(true));
9509 let blocks = encode_key_frame_inner(
9510 &picture,
9511 90,
9512 0.5,
9513 &KEY_FRAME_MODES,
9514 true,
9515 (picture.width, picture.height),
9516 unspecified_color_config(), fctx,
9517 )
9518 .unwrap()
9519 .modes
9520 .len();
9521 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
9522 println!(
9523 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
9524 bd_rate(&whole, &split) * 100.0
9525 );
9526 }
9527 }
9528
9529 /// A striped picture, running one way or the other. The stripes are what
9530 /// separates a vertical predictor from a horizontal one: a mode search
9531 /// reading a transposed edge would pick the wrong one of the pair, which no
9532 /// symmetric picture would show.
9533 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
9534 let mut picture = Picture::grey(width, height);
9535 for y in 0..height {
9536 for x in 0..width {
9537 let along = if vertical { x } else { y };
9538 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
9539 }
9540 }
9541 picture
9542 }
9543
9544 /// Where two planes first disagree, and by how much: a mismatch reported as
9545 /// a position says which block and which sample of it went wrong, which a
9546 /// pair of thousand-sample arrays does not.
9547 fn first_difference(ours: &[u16], theirs: &[u16], width: usize) -> Option<String> {
9548 let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
9549 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
9550 Some(format!(
9551 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
9552 i % width,
9553 i / width,
9554 ours[i],
9555 theirs[i]
9556 ))
9557 }
9558
9559 /// Every mode the encoder offers has to predict what the decoder predicts,
9560 /// not just the ones a particular picture happens to choose: each is forced
9561 /// over a whole picture and the reconstruction gated against ffmpeg.
9562 #[test]
9563 fn every_mode_decodes_to_what_the_encoder_predicted() {
9564 let fctx = &crate::decode::FrameCtx::new();
9565 if !have_ffmpeg() {
9566 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
9567 return;
9568 }
9569 // 128 wide is a whole number of superblocks and 160 is not: the last
9570 // superblock of a 160-wide row is half a one, whose blocks have no
9571 // above-right samples inside the frame at all.
9572 for (width, height) in [(128, 96), (160, 96)] {
9573 let picture = test_card(width, height);
9574 for mode in KEY_FRAME_MODES {
9575 let encoded = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[mode], fctx).unwrap();
9576 let decoded = ffmpeg_decode(&encoded.stream, width, height);
9577 for (plane, ours, theirs, stride) in [
9578 ("luma", &encoded.reconstruction.y, &decoded.y, width),
9579 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
9580 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
9581 ] {
9582 assert!(
9583 first_difference(ours, theirs, stride).is_none(),
9584 "{width}x{height} mode {mode}, {plane}: {}",
9585 first_difference(ours, theirs, stride).unwrap()
9586 );
9587 }
9588 assert!(
9589 encoded.modes.iter().all(|&m| m == mode),
9590 "mode {mode}: the encoder coded something else"
9591 );
9592 }
9593 }
9594 }
9595
9596 /// The search has to follow the picture: vertical stripes are cheapest
9597 /// predicted from the row above, horizontal ones from the column to the
9598 /// left. Reading the edges the other way round would swap the two answers
9599 /// while leaving every fidelity gate intact.
9600 #[test]
9601 fn the_search_picks_the_direction_the_picture_runs() {
9602 let fctx = &crate::decode::FrameCtx::new();
9603 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
9604 let picture = stripes(128, 96, vertical);
9605 // Only the pair, because on stripes a third mode predicts exactly
9606 // what the right one of the pair does -- PAETH reads the corner and
9607 // the left column, which a striped picture makes equal -- and the
9608 // tie then goes to whichever is cheaper to name, which is not what
9609 // this gate is about.
9610 let encoded =
9611 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[V_PRED, H_PRED], fctx).unwrap();
9612 // The first block of the picture has neither neighbour, so it
9613 // cannot tell the modes apart; every other one can.
9614 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
9615 assert!(
9616 picked * 2 > encoded.modes.len() - 1,
9617 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
9618 encoded.modes.len() - 1,
9619 encoded.modes
9620 );
9621 }
9622 }
9623
9624 /// What the search is for: the same picture, at the same quantizer, coded
9625 /// smaller and more faithfully than DC alone can manage.
9626 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
9627 /// between the two rate-distortion curves in log-rate against PSNR, as a
9628 /// fraction of the reference's rate. Negative means the second curve costs
9629 /// less for the same picture.
9630 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
9631 let low = reference[0].0.max(other[0].0);
9632 let high = reference[reference.len() - 1]
9633 .0
9634 .min(other[other.len() - 1].0);
9635 // lane-av1tx: `TxMode::Select` moved the directional ladder clear of
9636 // the non-directional one on the synthetic diagonals -- every point
9637 // both higher in PSNR *and* lower in rate -- so there is no PSNR band
9638 // to integrate over any more. A curve that dominates that way has
9639 // saved everything the measure can express (the
9640 // `instrument-at-bound` class: the answer is at the instrument's own
9641 // edge, not undefined), so name it rather than panicking; anything
9642 // less clean than strict dominance still is.
9643 if high <= low {
9644 let ref_lo_rate = reference.iter().map(|p| p.1).fold(f64::MAX, f64::min);
9645 let other_hi_rate = other.iter().map(|p| p.1).fold(f64::MIN, f64::max);
9646 let dominates = other[0].0 > reference[reference.len() - 1].0
9647 && other_hi_rate <= ref_lo_rate;
9648 assert!(
9649 dominates,
9650 "the two ladders have to overlap in PSNR: {reference:?} vs {other:?}"
9651 );
9652 return -1.0;
9653 }
9654 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
9655 let i = curve
9656 .windows(2)
9657 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
9658 .unwrap_or(0);
9659 let (x0, y0) = curve[i];
9660 let (x1, y1) = curve[i + 1];
9661 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
9662 };
9663 let steps = 64;
9664 let mut area = 0.0;
9665 for step in 0..steps {
9666 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
9667 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
9668 }
9669 10f64.powf(area / f64::from(steps)) - 1.0
9670 }
9671
9672 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
9673 /// fidelity.
9674 fn ladder(picture: &Picture, modes: &[u8], fctx: &crate::decode::FrameCtx) -> Vec<(f64, f64)> {
9675 // A mode ablation measures the MODE search: the palette would code
9676 // these synthetic two-colour pictures losslessly under every arm and
9677 // leave nothing to compare (see [`force_screen`]).
9678 force_screen(Some(false));
9679 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
9680 .iter()
9681 .map(|&q| {
9682 let encoded = encode_key_frame_with_modes_with_ctx(picture, q, 0.5, modes, fctx).unwrap();
9683 (
9684 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
9685 (encoded.stream.len() as f64).log10(),
9686 )
9687 })
9688 .collect();
9689 points.sort_by(|a, b| a.0.total_cmp(&b.0));
9690 points
9691 }
9692
9693 /// What the search is for: the same pictures cost less to code at the same
9694 /// fidelity than DC prediction alone can manage. A picture that runs one
9695 /// way saves far more than a busy one, which is the shape a working
9696 /// directional pair has.
9697 #[test]
9698 fn the_search_beats_dc_alone() {
9699 let fctx = &crate::decode::FrameCtx::new();
9700 for (name, picture, want) in [
9701 ("test card", test_card(160, 96), -0.05),
9702 ("stripes", stripes(160, 96, true), -0.40),
9703 ] {
9704 let saved = bd_rate(
9705 &ladder(&picture, &[DC_PRED], fctx),
9706 &ladder(&picture, &NON_DIRECTIONAL, fctx),
9707 );
9708 assert!(
9709 saved < want,
9710 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
9711 saved * 100.0,
9712 -want * 100.0
9713 );
9714 }
9715 }
9716
9717 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
9718 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
9719 fn sweep_pictures() -> Vec<(String, Picture)> {
9720 let mut pictures = vec![
9721 ("test card".to_string(), test_card(160, 96)),
9722 ("stripes".to_string(), stripes(160, 96, true)),
9723 ("diagonal".to_string(), diagonal(160, 96, true)),
9724 ];
9725 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
9726 for entry in clips.split(':').filter(|e| !e.is_empty()) {
9727 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
9728 let name = path.rsplit('/').next().unwrap_or(path).to_string();
9729 pictures.push((name, clip_frame(path, skip, 640, 352)));
9730 }
9731 }
9732 pictures
9733 }
9734
9735 /// What the six directional modes are worth, per picture, at whatever
9736 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
9737 /// no further, and how often the search picks one.
9738 #[test]
9739 #[ignore = "a sweep, not a gate"]
9740 fn probe_directional() {
9741 let fctx = &crate::decode::FrameCtx::new();
9742 for (name, picture) in sweep_pictures() {
9743 let dc = ladder(&picture, &[DC_PRED], fctx);
9744 let flat = ladder(&picture, &NON_DIRECTIONAL, fctx);
9745 let all = ladder(&picture, &KEY_FRAME_MODES, fctx);
9746 let encoded = encode_key_frame_with_ctx(&picture, 90, 0.5, fctx).unwrap();
9747 let directional = encoded
9748 .modes
9749 .iter()
9750 .filter(|&&m| (3..=8).contains(&m))
9751 .count();
9752 // A picture whose ladders sit at different fidelities altogether
9753 // has no BD-rate to report -- see the flat-sample-window class.
9754 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
9755 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
9756 };
9757 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
9758 if overlap(a, b) {
9759 format!("{:+.2}%", bd_rate(a, b) * 100.0)
9760 } else {
9761 "no overlap".to_string()
9762 }
9763 };
9764 println!(
9765 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
9766 against(&flat, &all),
9767 against(&dc, &all),
9768 encoded.modes.len(),
9769 );
9770 }
9771 }
9772
9773 /// A picture whose stripes run along a diagonal, one way or the other.
9774 /// This is to the directional modes what [`stripes`] is to the vertical and
9775 /// horizontal pair: a predictor that walked the edge in the wrong direction
9776 /// would answer the two pictures the same way round.
9777 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
9778 let mut picture = Picture::grey(width, height);
9779 for y in 0..height {
9780 for x in 0..width {
9781 let along = if down_right { x + height - y } else { x + y };
9782 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
9783 }
9784 }
9785 picture
9786 }
9787
9788 /// The mode picked by the most blocks of a picture, ignoring the first
9789 /// block, which has no neighbours to tell the modes apart with.
9790 fn favourite_mode(picture: &Picture, fctx: &crate::decode::FrameCtx) -> (u8, usize, usize) {
9791 // A mode ablation measures the MODE search: the palette would code
9792 // these synthetic two-colour pictures losslessly under every arm and
9793 // leave nothing to compare (see [`force_screen`]).
9794 force_screen(Some(false));
9795 let encoded = encode_key_frame_with_ctx(picture, 100, 0.5, fctx).unwrap();
9796 let blocks = &encoded.modes[1..];
9797 let mut counts = [0usize; 13];
9798 for &mode in blocks {
9799 counts[usize::from(mode)] += 1;
9800 }
9801 let (mode, count) = counts
9802 .iter()
9803 .enumerate()
9804 .max_by_key(|&(_, count)| *count)
9805 .expect("thirteen modes");
9806 (mode as u8, *count, blocks.len())
9807 }
9808
9809 /// The search has to follow a diagonal the way it runs: stripes down and to
9810 /// the right are cheapest predicted at 135 degrees, stripes down and to the
9811 /// left at 45. A walk that stepped the wrong way along the edge, or read
9812 /// the above row where it should read the left column, would swap these.
9813 #[test]
9814 fn the_search_picks_the_diagonal_the_picture_runs() {
9815 let fctx = &crate::decode::FrameCtx::new();
9816 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
9817 let picture = diagonal(160, 96, down_right);
9818 let (mode, count, blocks) = favourite_mode(&picture, fctx);
9819 assert_eq!(
9820 mode, want,
9821 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
9822 );
9823 }
9824 }
9825
9826 /// What the directional modes are for: a picture that runs along a diagonal
9827 /// costs far less to code with them than the seven that read only their own
9828 /// edges can manage, and a picture that runs no particular way costs no
9829 /// more. The second half is the one that bites: a mode set the search
9830 /// cannot price is a mode set that loses rate on content that does not want
9831 /// it, which is what costing the mode symbol is for.
9832 #[test]
9833 fn the_diagonals_beat_the_modes_that_read_no_further() {
9834 let fctx = &crate::decode::FrameCtx::new();
9835 for (name, picture, want) in [
9836 ("down-right", diagonal(160, 96, true), -0.20),
9837 ("down-left", diagonal(160, 96, false), -0.20),
9838 ("test card", test_card(160, 96), 0.01),
9839 ] {
9840 let saved = bd_rate(
9841 &ladder(&picture, &NON_DIRECTIONAL, fctx),
9842 &ladder(&picture, &KEY_FRAME_MODES, fctx),
9843 );
9844 assert!(
9845 saved < want,
9846 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
9847 saved * 100.0,
9848 -want * 100.0
9849 );
9850 }
9851 }
9852
9853 /// A mode the encoder cannot predict must be refused rather than coded as
9854 /// something else, and a search with nothing to choose from likewise.
9855 #[test]
9856 fn a_mode_the_encoder_cannot_predict_is_refused() {
9857 let fctx = &crate::decode::FrameCtx::new();
9858 let picture = test_card(64, 64);
9859 let message = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[13], fctx)
9860 .unwrap_err()
9861 .to_string();
9862 assert!(
9863 message.contains("intra mode 13"),
9864 "the refusal must name the mode, got {message}"
9865 );
9866 assert!(encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[], fctx).is_err());
9867 }
9868
9869 /// The picture that comes back is the picture that went in, to within the
9870 /// quantizer. A prediction that read the wrong neighbours, or a block
9871 /// written into the wrong place, would still decode to what the encoder
9872 /// reconstructed — it is this gate that says the reconstruction is of the
9873 /// right picture.
9874 #[test]
9875 fn the_encoded_picture_is_the_one_that_went_in() {
9876 let fctx = &crate::decode::FrameCtx::new();
9877 let picture = test_card(160, 96);
9878 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
9879 let luma = psnr(&encoded.reconstruction.y, &picture.y);
9880 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
9881 for (plane, (got, want)) in [
9882 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
9883 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
9884 ]
9885 .iter()
9886 .enumerate()
9887 {
9888 let chroma = psnr(got, want);
9889 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
9890 }
9891 }
9892
9893 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
9894 /// does the opposite. Both are monotone, which is what a rate-distortion
9895 /// loop above this will assume.
9896 #[test]
9897 fn fidelity_and_rate_move_with_the_quantizer() {
9898 let fctx = &crate::decode::FrameCtx::new();
9899 let picture = test_card(128, 128);
9900 let mut previous: Option<(usize, f64)> = None;
9901 for &q in &[70u8, 90, 110] {
9902 let encoded = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
9903 let quality = psnr(&encoded.reconstruction.y, &picture.y);
9904 if let Some((bytes, better)) = previous {
9905 assert!(
9906 encoded.stream.len() < bytes,
9907 "q {q}: {} bytes",
9908 encoded.stream.len()
9909 );
9910 assert!(quality < better, "q {q}: PSNR {quality}");
9911 }
9912 previous = Some((encoded.stream.len(), quality));
9913 }
9914
9915 let mut previous = None;
9916 for &deadzone in &[0.5f64, 0.3, 0.15] {
9917 let encoded = encode_key_frame_with_ctx(&picture, 100, deadzone, fctx).unwrap();
9918 let quality = psnr(&encoded.reconstruction.y, &picture.y);
9919 if let Some((bytes, better)) = previous {
9920 assert!(
9921 encoded.stream.len() < bytes,
9922 "deadzone {deadzone}: {} bytes",
9923 encoded.stream.len()
9924 );
9925 assert!(quality < better, "deadzone {deadzone}: PSNR {quality}");
9926 }
9927 previous = Some((encoded.stream.len(), quality));
9928 }
9929
9930 // Bytes must not jump up across a q-context boundary: a wrong CDF
9931 // table for the far side would show up as a rate discontinuity here,
9932 // even though a coarser quantizer always codes no more than a finer
9933 // one on the same picture.
9934 //
9935 // corner-cut (lane-av1rd3): the bound is 5% rather than exact. Since
9936 // chroma searches its own mode, a coarser quantizer can pick a
9937 // *different* uv_mode on a block whose modes now cost nearly the
9938 // same, and the search prices that symbol against the static default
9939 // CDF while the writer codes it against an adapted one -- 311 -> 319
9940 // bytes at q 120->121 on this picture. The table this gate is really
9941 // watching would move the rate by far more than the mode churn does.
9942 // lane-av1tx widened it again, 5% -> 10%: under `TxMode::Select` the
9943 // same block can also change transform DEPTH between two neighbouring
9944 // quantizers (297 -> 315 bytes at q 120->121 here), and the depth
9945 // symbol is priced off the static CDF row 0 for the same reason the
9946 // uv_mode one is.
9947 // Ceiling: a q-context table wrong by under 10% would pass. Upgrade
9948 // path is pricing through the adapting CDF state (what
9949 // `predicted_coeff_bits_track_the_tile_the_writer_wrote` measures the
9950 // drift of), after which the exact bound comes back.
9951 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
9952 let lo_bytes = encode_key_frame_with_ctx(&picture, lo, 0.5, fctx).unwrap().stream.len();
9953 let hi_bytes = encode_key_frame_with_ctx(&picture, hi, 0.5, fctx).unwrap().stream.len();
9954 assert!(
9955 hi_bytes as f64 <= lo_bytes as f64 * 1.10,
9956 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
9957 );
9958 }
9959 }
9960
9961 /// A flat picture is a flat stream: every block predicts its neighbours'
9962 /// average, which is the picture's own value, and codes nothing.
9963 #[test]
9964 fn a_flat_picture_costs_almost_nothing() {
9965 let fctx = &crate::decode::FrameCtx::new();
9966 let mut picture = Picture::grey(128, 128);
9967 picture.y.fill(97);
9968 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
9969 // The first block has no neighbour and predicts 128, so it carries a
9970 // DC; every block after it predicts 97 and carries nothing.
9971 assert!(
9972 encoded.stream.len() < 100,
9973 "{} bytes for a flat picture",
9974 encoded.stream.len()
9975 );
9976 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
9977 assert_eq!(s, 97, "sample {i} of a flat picture");
9978 }
9979 }
9980
9981 /// The sizes the encoder refuses, refused for a reason rather than by
9982 /// panicking somewhere below. Sizes off the 32x32 block grid encode fine
9983 /// (see `a_frame_round_trips_at_its_own_size`) -- the true frame edge
9984 /// lands past the halfway point of whichever block it falls in, so
9985 /// `PARTITION_NONE` or a single gathered split flag still says everything
9986 /// the spec needs. lane-av1-rect r7 wired the 8x8-leaf path for a 16x16
9987 /// leaf straddling on exactly one axis (e.g. 40x32), and lane-av1rect the
9988 /// both-axes cut (e.g. 40x40, both dims mod 32 == 8), which spec 5.11.4
9989 /// codes with NO partition symbol at all -- `PARTITION_SPLIT` inferred,
9990 /// down to the in-frame 8x8s, no rectangular transform anywhere (the old
9991 /// refusal here claimed otherwise and was wrong; see
9992 /// `crate::stream::tests::a_sweep_of_doubly_straddling_sizes_round_trips_
9993 /// through_ffmpeg`). No size refusal is left: an 8x8 leaf can never
9994 /// straddle either, because `MiCols`/`MiRows` are always EVEN (spec
9995 /// 5.9.5 `compute_image_size`: `2 * ((frame_width + 7) >> 3)`), so the
9996 /// true edge always lands on an 8-luma-sample boundary in mi terms and a
9997 /// 4x4 leaf -- which neither writer has -- is never asked for. What is
9998 /// still refused is a malformed picture.
9999 #[test]
10000 fn a_picture_off_the_block_grid_encodes_and_a_malformed_one_is_refused() {
10001 let fctx = &crate::decode::FrameCtx::new();
10002 encode_key_frame_with_ctx(&Picture::grey(40, 40), 100, 0.5, fctx)
10003 .expect("40x40 cuts a 16x16 leaf on both axes, which is an inferred split");
10004 encode_key_frame_with_ctx(&Picture::grey(36, 40), 100, 0.5, fctx)
10005 .expect("36 luma columns still round up to an even MiCols");
10006
10007 let mut short = Picture::grey(64, 64);
10008 short.u.truncate(10);
10009 assert!(encode_key_frame_with_ctx(&short, 100, 0.5, fctx).is_err());
10010 }
10011
10012 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
10013 /// column half only (`has_half` false on cols, true on rows) -- exactly
10014 /// the single-axis straddle lane-av1-rect r7 wires through
10015 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
10016 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
10017 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
10018 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
10019 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
10020 /// `partition_context_lookup` entry this writer ever produces (no 4x4
10021 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
10022 /// leaf regardless of neighbour state -- our writer already agreed with
10023 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
10024 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
10025 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
10026 /// it does not regress the gate. r11 tell-for-tell traced two further,
10027 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
10028 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
10029 /// leaves, when the second leaf's true above (or left) neighbour is the
10030 /// first leaf itself -- fixed by threading the first leaf's mode into the
10031 /// second leaf's context, mi-precise, like `record_mi` already does for
10032 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
10033 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
10034 /// `reduced_tx_set` is false), but this crate's key frames set
10035 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
10036 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
10037 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
10038 /// symbol bits to desync everything after it. Fixed with a new
10039 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
10040 /// eset/size slot). Both fixes are provably correct against libaom
10041 /// source and each closed part of the gap (leaf0's `eob` went from a
10042 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
10043 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
10044 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
10045 /// (do not reuse r11's committed logs, which predate its own fixes) and
10046 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
10047 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
10048 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
10049 /// every other `write_block` caller at 16x16 and up already passes
10050 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
10051 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
10052 /// different amount of arithmetic range and derailed everything after
10053 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
10054 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
10055 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
10056 /// never updating those coarse arrays itself -- so a *second* straddling
10057 /// 16x16 quadrant stacked above or left of the first (never covered by
10058 /// r11's same-call `prev_leaf` override, which only threads state
10059 /// between the two leaves of one shared quadrant) read whatever stale
10060 /// mode sat in that slot before either leaf ran. Fixed by writing the
10061 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
10062 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
10063 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
10064 /// offset of a single unit; fixing (3)+(4) together still leaves a
10065 /// residual divergence one leaf further in -- the decoder now reads
10066 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
10067 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
10068 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
10069 /// desyncs the stream by exactly the width of one earlier symbol -- not
10070 /// yet isolated to a single named symbol. r15 found the last bug: the
10071 /// header fix from r14 explained the rng skew fully, and the remaining
10072 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
10073 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
10074 /// loop, once per leaf, so the first leaf's write clobbered the true
10075 /// external neighbour mode the second leaf of the *same* straddling
10076 /// quadrant still needed for its non-adjacency axis (a column-straddle
10077 /// case: two leaves share one `outer_at` column index, so leaf 1's
10078 /// write to `left_mode[r]` overwrote the real western neighbour before
10079 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
10080 /// doing it once, after the whole leaf loop, from the last (bottom/
10081 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
10082 #[test]
10083 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
10084 let fctx = &crate::decode::FrameCtx::new();
10085 if !have_ffmpeg() {
10086 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
10087 return;
10088 }
10089 let (width, height) = (40usize, 32usize);
10090 let picture = test_card(width, height);
10091 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
10092 assert_eq!(
10093 (encoded.reconstruction.width, encoded.reconstruction.height),
10094 (width, height)
10095 );
10096 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
10097 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
10098 }
10099 let decoded = ffmpeg_decode(&encoded.stream, width, height);
10100 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
10101 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
10102 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
10103 }
10104
10105 /// A frame of real video, rather than a picture built to be easy.
10106 ///
10107 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
10108 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
10109 /// encoder's reconstruction has to survive the same equality gate as the
10110 /// synthetic pictures — real video reaches contexts a test card does not.
10111 #[test]
10112 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
10113 let fctx = &crate::decode::FrameCtx::new();
10114 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
10115 eprintln!(
10116 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
10117 set EC_AV1_CLIP to a clip"
10118 );
10119 return;
10120 };
10121 if !have_ffmpeg() {
10122 eprintln!(
10123 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
10124 );
10125 return;
10126 }
10127 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
10128 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
10129 // test quick while still spanning many superblocks.
10130 let (width, height) = (640usize, 352usize);
10131 let picture = clip_frame(&clip, &skip, width, height);
10132
10133 let encoded = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
10134 let decoded = ffmpeg_decode(&encoded.stream, width, height);
10135 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
10136 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
10137 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
10138 eprintln!(
10139 "{} bytes, luma PSNR {:.2} dB",
10140 encoded.stream.len(),
10141 psnr(&decoded.y, &picture.y)
10142 );
10143 }
10144
10145 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
10146 /// sequence of these is a translation a motion search can actually find
10147 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
10148 /// inter frame's rate against the key frame's is measuring the same
10149 /// picture moving, not two different pictures.
10150 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
10151 let mut picture = Picture::grey(width, height);
10152 for y in 0..height {
10153 for x in 0..width {
10154 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
10155 let gradient = sx * 200.0 / width as f64;
10156 let ripple = 30.0
10157 * (sx * std::f64::consts::PI / 23.0).sin()
10158 * (y as f64 * std::f64::consts::PI / 37.0).cos();
10159 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
10160 40.0
10161 } else {
10162 0.0
10163 };
10164 picture.y[y * width + x] =
10165 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u16;
10166 }
10167 }
10168 for y in 0..height / 2 {
10169 for x in 0..width / 2 {
10170 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
10171 let i = y * width / 2 + x;
10172 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u16;
10173 picture.v[i] = (200 - (y * 80 / (height / 2))) as u16;
10174 }
10175 }
10176 picture
10177 }
10178
10179 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
10180 fn ffmpeg_decode_sequence(
10181 stream: &[u8],
10182 width: usize,
10183 height: usize,
10184 frames: usize,
10185 ) -> Vec<Picture> {
10186 let mut child = Command::new("ffmpeg")
10187 .args([
10188 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
10189 ])
10190 .stdin(Stdio::piped())
10191 .stdout(Stdio::piped())
10192 .stderr(Stdio::piped())
10193 .spawn()
10194 .expect("ffmpeg failed to start");
10195 // lane-t900 r10: the stream goes down stdin on ITS OWN THREAD. Writing
10196 // it inline deadlocks the moment ffmpeg's stdout pipe buffer (64 KiB)
10197 // fills before the last input byte is written -- which is exactly what
10198 // a 1.1 MB fixture decoding to 150 MB of raw 10-bit frames does
10199 // (measured: 45 min, both processes at 0% CPU). A write error here is
10200 // swallowed on purpose: ffmpeg's own exit status and stderr, asserted
10201 // below, are the real diagnosis.
10202 let mut stdin = child.stdin.take().expect("ffmpeg stdin");
10203 let payload = stream.to_vec();
10204 let writer = std::thread::spawn(move || {
10205 let _ = stdin.write_all(&payload);
10206 });
10207 let out = child.wait_with_output().expect("ffmpeg failed to run");
10208 writer.join().expect("ffmpeg stdin writer thread");
10209 assert!(
10210 out.status.success(),
10211 "ffmpeg refused the stream: {}",
10212 String::from_utf8_lossy(&out.stderr)
10213 );
10214 let (luma, chroma) = (width * height, width * height / 4);
10215 let frame_bytes = luma + 2 * chroma;
10216 assert_eq!(
10217 out.stdout.len(),
10218 frame_bytes * frames,
10219 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
10220 String::from_utf8_lossy(&out.stderr)
10221 );
10222 (0..frames)
10223 .map(|i| {
10224 let base = i * frame_bytes;
10225 Picture {
10226 width,
10227 height,
10228 y: out.stdout[base..base + luma].iter().map(|&v| u16::from(v)).collect(),
10229 u: out.stdout[base + luma..base + luma + chroma].iter().map(|&v| u16::from(v)).collect(),
10230 v: out.stdout[base + luma + chroma..base + frame_bytes].iter().map(|&v| u16::from(v)).collect(),
10231 }
10232 })
10233 .collect()
10234 }
10235
10236 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
10237 /// makes for a key frame, extended down the reference chain: each inter
10238 /// frame's reconstruction predicts from the previous frame's own decoded
10239 /// reconstruction, so a single sample of drift anywhere would propagate
10240 /// into every frame after it -- which is why every frame is checked, not
10241 /// just the last one, and why this is an equality and not a tolerance.
10242 #[test]
10243 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
10244 let fctx = &crate::decode::FrameCtx::new();
10245 if !have_ffmpeg() {
10246 eprintln!(
10247 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
10248 );
10249 return;
10250 }
10251 let (width, height) = (128usize, 64usize);
10252 let pictures: Vec<Picture> = (0..5)
10253 .map(|i| panned_test_card(width, height, i * 3))
10254 .collect();
10255 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
10256 assert_eq!(encoded.frames.len(), 5);
10257
10258 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
10259 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
10260 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
10261 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
10262 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
10263 }
10264
10265 eprintln!("frame bytes luma PSNR (dB) inter share");
10266 for (i, frame) in encoded.frames.iter().enumerate() {
10267 eprintln!(
10268 "{i:5} {:5} {:14.2} {:11.2}",
10269 frame.stream.len(),
10270 psnr(&frame.reconstruction.y, &pictures[i].y),
10271 frame.inter_block_share
10272 );
10273 }
10274 }
10275
10276 /// The same sequence through OUR OWN decoder, sample-exact against the
10277 /// encoder's reconstruction. ffmpeg stays the bitstream oracle
10278 /// ([[shared-oracle-blindness]]) -- but a stream ffmpeg REFUSES yields no
10279 /// divergence point at all, while our decoder can be traced symbol by
10280 /// symbol (`EC_TRACE_MODE_STEP`) on the very stream that broke. This is
10281 /// the instrument the inter `TxMode::Select` hunt lacked; on failure it
10282 /// names the first differing frame, plane and position.
10283 #[test]
10284 fn every_frame_of_a_sequence_decodes_through_our_own_decoder() {
10285 let fctx = &crate::decode::FrameCtx::new();
10286 // 256x128, not the 128x64 this started at: once a leaf could search
10287 // its second reference (lane-av1comp4) the small card's every
10288 // eligible block went to a compound winner, which commits its flat
10289 // transform, and the split below stopped firing on content that
10290 // still splits at every larger size ([[gate-blind-to-feature]] --
10291 // the guard is right, the fixture had shrunk under it).
10292 let (width, height) = (256usize, 128usize);
10293 let pictures: Vec<Picture> =
10294 (0..5).map(|i| panned_test_card(width, height, i * 3)).collect();
10295 let _ = take_inter_tx_split_hits();
10296 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
10297 let split = take_inter_tx_split_hits();
10298 eprintln!("inter var-tx: {} blocks flat, {} split", split[0], split[1]);
10299 // [[gate-blind-to-feature]]: with inter `TxMode::Select` on, this
10300 // content splits -- a green round trip in which the split never fires
10301 // would prove only the flat path.
10302 if tx_select() && tx_select_inter() {
10303 assert!(split[1] > 0, "the inter var-tx split never fired");
10304 }
10305 let decoded = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
10306 assert_eq!(decoded.len(), encoded.frames.len(), "frame count");
10307 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
10308 let recon = &frame.reconstruction;
10309 for (plane, got, want, stride) in [
10310 ("luma", &dec.y, &recon.y, width),
10311 ("U", &dec.u, &recon.u, width / 2),
10312 ("V", &dec.v, &recon.v, width / 2),
10313 ] {
10314 assert_eq!(got.len(), want.len(), "frame {i}: {plane} size");
10315 if let Some(at) = got.iter().zip(want).position(|(a, b)| a != b) {
10316 panic!(
10317 "frame {i}: {plane} differs first at ({}, {}): decoded {} vs \
10318 reconstruction {} ({} of {} samples differ)",
10319 at % stride,
10320 at / stride,
10321 got[at],
10322 want[at],
10323 got.iter().zip(want).filter(|(a, b)| a != b).count(),
10324 got.len(),
10325 );
10326 }
10327 }
10328 }
10329 }
10330
10331 /// The rate term the mode search ranks every decision by has to be the
10332 /// rate the writer then spends. The search prices a block's coefficients
10333 /// through `tile::coeff_bits` -- the writer's own symbol chain, but
10334 /// against the default CDFs a tile starts from and the contexts of a
10335 /// block whose neighbours coded nothing -- while the tile writer codes
10336 /// them against a state that has been adapting all frame (the
10337 /// price-the-narrowing class). This measures that drift: the sum of what
10338 /// the search paid for the coefficients it kept, against the bytes the
10339 /// writer actually emitted for the whole tile (which also carries the
10340 /// partition/mode/skip/mv syntax the sum leaves out, so the writer is
10341 /// expected to be the larger of the two).
10342 #[test]
10343 fn predicted_coeff_bits_track_the_tile_the_writer_wrote() {
10344 let fctx = &crate::decode::FrameCtx::new();
10345 let (width, height) = (256usize, 128usize);
10346 let pictures: Vec<Picture> = (0..5)
10347 .map(|i| panned_test_card(width, height, i * 2))
10348 .collect();
10349 let _ = take_predicted_bits();
10350 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
10351 let predicted = take_predicted_bits();
10352 assert_eq!(predicted.len(), encoded.frames.len());
10353
10354 eprintln!("frame predicted bits written bits drift");
10355 // Split by sign: a NEGATIVE drift is the search OVER-pricing (the
10356 // defect this gate exists to catch), a positive one is the written
10357 // side carrying syntax the coefficient sum leaves out -- and since
10358 // lane-av1mv an extra reference's `NEWMV` puts a whole MV residual
10359 // on that side, so the two directions no longer share a bound.
10360 let mut worst_over: f64 = 0.0;
10361 let mut worst_under: f64 = 0.0;
10362 for (i, (frame, &bits)) in encoded.frames.iter().zip(&predicted).enumerate() {
10363 let written = frame.tile.len() as f64 * 8.0;
10364 let drift = (written - bits) / written;
10365 worst_over = worst_over.max(-drift);
10366 worst_under = worst_under.max(drift);
10367 eprintln!("{i:5} {bits:14.0} {written:12.0} {:+6.2}%", drift * 100.0);
10368 }
10369 // Measured 2026-09-06 on this sequence: -13.5% at the key frame,
10370 // -8.1%, -3.8%, -2.1%, +1.8% down the inter frames. The search
10371 // over-prices every frame but the last (its sum EXCLUDES the
10372 // partition/mode/skip/mv syntax the written side carries, so the true
10373 // coefficient over-price is larger still): the writer's CDFs adapt to
10374 // the content while the search's stay at the defaults. The bound is
10375 // set just above the worst measured point -- a widening drift is the
10376 // thing this gate exists to catch.
10377 assert!(
10378 worst_over <= 0.16,
10379 "the search's rate term OVER-priced by {:.2}% against the bits the writer spent",
10380 worst_over * 100.0
10381 );
10382 // Measured 2026-09-06 with the extra-reference `NEWMV` in: +18.9% at
10383 // the worst inter frame, where nearly every block now codes an MV
10384 // residual and a reference the coefficient sum never counts. Re-measured
10385 // at +29.6% once the encoder's grid published compound blocks properly
10386 // (compound share 8.8% -> 11.5%): a compound block carries a second
10387 // reference tree, a compound mode symbol and -- for the half-new modes
10388 // -- an MV residual, none of which the coefficient sum counts.
10389 // lane-av1txbits: pricing against the tables the frame's writer really
10390 // starts from collapses the over-price above to nothing, so the whole
10391 // remaining gap is the syntax the coefficient sum leaves out. That is
10392 // the default on a non-screen frame since lane-av1price2 (this
10393 // fixture is one), and it reads +32.6% here.
10394 // lane-av1obmc: every eligible single-reference inter block now also
10395 // carries a `motion_mode` symbol the coefficient sum never counts,
10396 // and an OBMC block carries the more expensive of the two values --
10397 // re-measured at +35.0% here with `EC_AV1_OBMC=1`. Like
10398 // `EC_AV1_PRICE_FRAME_CDFS=1` before it, that knob changes encoder
10399 // decisions, so this bound and the byte pins above FAIL BY DESIGN
10400 // under it; the default path (no motion_mode syntax at all) is the
10401 // one they are measured on.
10402 assert!(
10403 worst_under <= 0.34,
10404 "the writer spent {:.2}% more than the search priced -- more than \
10405 the mode/mv syntax outside the coefficient sum explains",
10406 worst_under * 100.0
10407 );
10408 }
10409
10410 /// The census behind step (1) of the pricer lane: for every transform
10411 /// block the writer really codes, what the search priced those levels at
10412 /// against what the writer spent on them, split by table set and non-zero
10413 /// count. One average hides the interesting part -- the classes the
10414 /// estimate is systematically wrong about (all-zero blocks, the
10415 /// one-coefficient blocks the inter search lives on) -- so the split is
10416 /// printed and only the total is asserted on.
10417 #[test]
10418 fn pricer_error_census_by_block_class() {
10419 let fctx = &crate::decode::FrameCtx::new();
10420 let (width, height) = (256usize, 128usize);
10421 let pictures: Vec<Picture> = (0..5)
10422 .map(|i| panned_test_card(width, height, i * 2))
10423 .collect();
10424 crate::tile::pricer_census_on();
10425 let _ = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
10426 let rows = crate::tile::take_pricer_census();
10427 assert!(!rows.is_empty(), "the census saw no transform block");
10428
10429 println!("| set | nz | blocks | priced bits | written bits | error |");
10430 println!("|---|---|---|---|---|---|");
10431 let (mut priced_all, mut written_all) = (0.0, 0.0);
10432 for ((set, bucket), (blocks, priced, written)) in &rows {
10433 priced_all += priced;
10434 written_all += written;
10435 println!(
10436 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
10437 crate::tile::census_bucket_label(*bucket),
10438 if *written > 0.0 {
10439 (priced - written) / written * 100.0
10440 } else {
10441 0.0
10442 }
10443 );
10444 }
10445 println!(
10446 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
10447 rows.values().map(|r| r.0).sum::<u64>(),
10448 (priced_all - written_all) / written_all * 100.0
10449 );
10450 assert!(written_all > 0.0);
10451 }
10452
10453 /// Step (2) of the pricer lane: the same census, but on the REAL clips
10454 /// the BD gate scores -- one film clip and the screen capture -- so the
10455 /// question the film/screen split raises can be answered from data. Real
10456 /// tables (`EC_AV1_PRICE_FRAME_CDFS=1`) make both film clips smaller and
10457 /// the screen capture larger, and the census says why: on a screen
10458 /// capture the frame's own starting tables are the tables of a frame that
10459 /// coded PALETTE and long runs of zero blocks, so they are far from the
10460 /// tables the writer ends the frame with; the pricer error does not fall
10461 /// the way it does on film.
10462 ///
10463 /// Not a gate -- it prints. Run it once per mode:
10464 /// EC_AV1_PRICE_FRAME_CDFS=0 cargo test -p ec-av1 --release --lib -- \
10465 /// --ignored pricer_error_census_on_clips --nocapture
10466 #[test]
10467 #[ignore = "reads the real library, needs ffmpeg"]
10468 fn pricer_error_census_on_clips() {
10469 if !have_ffmpeg() {
10470 eprintln!("SKIP pricer_error_census_on_clips: no ffmpeg");
10471 return;
10472 }
10473 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
10474 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
10475 let film = fixtures.join("video/h264-1080p-23.976-8bit.mp4");
10476 if film.exists() {
10477 clips.push(("film 1080p".to_string(), film));
10478 }
10479 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
10480 && let Some(p) = manifest
10481 .lines()
10482 .skip(1)
10483 .filter_map(|l| l.split('\t').next())
10484 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
10485 {
10486 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
10487 }
10488 assert!(!clips.is_empty(), "no source clip available");
10489 let (width, height, frames) = (640usize, 384usize, 6usize);
10490 for (name, path) in &clips {
10491 let fctx = &crate::decode::FrameCtx::new();
10492 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
10493 SCREEN_FRAMES.iter().for_each(|c| {
10494 c.store(0, std::sync::atomic::Ordering::Relaxed);
10495 });
10496 let _ = crate::tile::take_pricing_hits();
10497 crate::tile::pricer_census_on();
10498 let _ = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
10499 let rows = crate::tile::take_pricer_census();
10500 let (price_default, price_real) = crate::tile::take_pricing_hits();
10501 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
10502 println!(
10503 "\n## {name} ({frames} frames at {width}x{height}, q=100): screen frames \
10504 {screen_on}, pricer armings default={price_default} real={price_real}"
10505 );
10506 println!("| set | nz | blocks | priced bits | written bits | error |");
10507 println!("|---|---|---|---|---|---|");
10508 let (mut priced_all, mut written_all) = (0.0, 0.0);
10509 for ((set, bucket), (blocks, priced, written)) in &rows {
10510 priced_all += priced;
10511 written_all += written;
10512 println!(
10513 "| {set} | {} | {blocks} | {priced:.0} | {written:.0} | {:+.1}% |",
10514 crate::tile::census_bucket_label(*bucket),
10515 if *written > 0.0 { (priced - written) / written * 100.0 } else { 0.0 }
10516 );
10517 }
10518 println!(
10519 "| ALL | | {} | {priced_all:.0} | {written_all:.0} | {:+.1}% |",
10520 rows.values().map(|r| r.0).sum::<u64>(),
10521 (priced_all - written_all) / written_all * 100.0
10522 );
10523 assert!(written_all > 0.0, "{name}: the census saw no transform block");
10524 }
10525 }
10526
10527 /// Low motion has to actually buy something: at least one inter frame of
10528 /// a panning sequence has to cost fewer bytes than the key frame that
10529 /// starts it, and the inter-block share it prints has to be non-zero --
10530 /// a search that never picks an inter mode would still pass a rate gate
10531 /// on a picture with no motion in it (the class this repo calls
10532 /// gate-blind-to-feature), so the share is printed even though it is not
10533 /// asserted on beyond being reachable at all.
10534 #[test]
10535 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
10536 let fctx = &crate::decode::FrameCtx::new();
10537 let (width, height) = (256usize, 128usize);
10538 let pictures: Vec<Picture> = (0..5)
10539 .map(|i| panned_test_card(width, height, i * 2))
10540 .collect();
10541 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
10542
10543 let key_bytes = encoded.frames[0].stream.len();
10544 eprintln!("frame bytes inter share");
10545 for (i, frame) in encoded.frames.iter().enumerate() {
10546 eprintln!(
10547 "{i:5} {:5} {:11.2}",
10548 frame.stream.len(),
10549 frame.inter_block_share
10550 );
10551 }
10552 assert!(
10553 encoded.frames[1..]
10554 .iter()
10555 .any(|f| f.stream.len() < key_bytes),
10556 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
10557 );
10558 assert!(
10559 encoded.frames[1..]
10560 .iter()
10561 .any(|f| f.inter_block_share > 0.0),
10562 "no inter frame coded a single inter block -- the search never fired"
10563 );
10564 }
10565
10566 /// A manual perf probe, not a gate: prints where a key frame's and an
10567 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
10568 /// measures before it optimizes rather than guessing. Run with
10569 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
10570 #[test]
10571 #[ignore = "a perf probe, not a gate"]
10572 fn stage_timing_breakdown() {
10573 let fctx = &crate::decode::FrameCtx::new();
10574 use std::time::Instant;
10575
10576 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
10577 let picture = test_card(width, height);
10578
10579 let t = Instant::now();
10580 let dc_only = encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &[DC_PRED], fctx).unwrap();
10581 let dc_only_t = t.elapsed();
10582
10583 let t = Instant::now();
10584 let non_directional =
10585 encode_key_frame_with_modes_with_ctx(&picture, 100, 0.5, &NON_DIRECTIONAL, fctx).unwrap();
10586 let non_directional_t = t.elapsed();
10587
10588 let t = Instant::now();
10589 let all_modes = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
10590 let all_modes_t = t.elapsed();
10591
10592 eprintln!(
10593 "\n=== key frame {width}x{height} ===\n\
10594 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
10595 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
10596 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
10597 dc_only.stream.len(),
10598 non_directional.stream.len(),
10599 all_modes.stream.len(),
10600 );
10601
10602 // One inter frame predicting off the key frame's own
10603 // reconstruction, the (256, 256)-padded surface encode_sequence
10604 // itself would hand encode_inter_frame.
10605 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
10606 let padded_pic = picture.padded_to(SUPERBLOCK);
10607 let t = Instant::now();
10608 let inter =
10609 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();
10610 let inter_t = t.elapsed();
10611 eprintln!(
10612 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
10613 {:.2})",
10614 inter.stream.len(),
10615 inter.inter_block_share
10616 );
10617 }
10618
10619 // Isolated per-call cost of the trial pipeline's own stages, at both
10620 // transform sizes the search runs, averaged over enough calls to
10621 // rise above `Instant::now`'s own noise.
10622 for side in [16usize, 32] {
10623 const N: u32 = 20_000;
10624 let residual: Vec<i32> = (0..side * side)
10625 .map(|i| ((i * 37 % 61) as i32) - 30)
10626 .collect();
10627
10628 let t = Instant::now();
10629 let mut levels = Vec::new();
10630 for _ in 0..N {
10631 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
10632 }
10633 let forward_t = t.elapsed() / N;
10634
10635 let t = Instant::now();
10636 for _ in 0..N {
10637 std::hint::black_box(dequant_and_inverse(&levels, side, 8, 100));
10638 }
10639 let inverse_t = t.elapsed() / N;
10640
10641 let set = if side == 32 {
10642 crate::cdf_state::TxbSet::Luma32
10643 } else {
10644 crate::cdf_state::TxbSet::Luma16
10645 };
10646 let t = Instant::now();
10647 for _ in 0..N {
10648 std::hint::black_box(crate::tile::coeff_bits(&levels, set, 2, 0, 0));
10649 }
10650 let entropy_t = t.elapsed() / N;
10651
10652 let above = vec![128u8; side * 2];
10653 let left = vec![128u8; side * 2];
10654 let mut prediction = vec![0u8; side * side];
10655 let t = Instant::now();
10656 for _ in 0..N {
10657 intra_predict_u8(
10658 D45_PRED,
10659 0,
10660 Some(&above),
10661 Some(&left),
10662 Some(128),
10663 side,
10664 side,
10665 false,
10666 false,
10667 &mut prediction, fctx,
10668 );
10669 }
10670 let predict_t = t.elapsed() / N;
10671
10672 eprintln!(
10673 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
10674 predict (1 directional mode): {predict_t:>9.2?}\n\
10675 forward_and_quantize: {forward_t:>9.2?}\n\
10676 dequant_and_inverse: {inverse_t:>9.2?}\n\
10677 coeff_bits: {entropy_t:>9.2?}"
10678 );
10679 }
10680 }
10681
10682 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
10683 /// (motion search, [`crate::mc::predict`], transform+quantize,
10684 /// `coeff_bits`), plus what is left over once those are subtracted --
10685 /// the thirteen-mode intra-candidate loop `search_inter_block` still
10686 /// runs on every inter block (its own transform/quant/entropy calls are
10687 /// already inside buckets 2/3, so "left over" here is everything NOT
10688 /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
10689 /// symbol-cost lookups outside `coeff_bits`).
10690 ///
10691 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
10692 #[test]
10693 #[ignore = "a perf probe, not a gate"]
10694 fn stage_timing_breakdown_inter() {
10695 let fctx = &crate::decode::FrameCtx::new();
10696 use std::time::Instant;
10697
10698 let (width, height) = (1280usize, 720);
10699 let picture = test_card(width, height);
10700 let key = encode_key_frame_with_ctx(&picture, 100, 0.5, fctx).unwrap();
10701 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
10702 let padded_pic = picture.padded_to(SUPERBLOCK);
10703
10704 stage_reset();
10705 let t = Instant::now();
10706 let inter =
10707 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();
10708 let total_t = t.elapsed();
10709 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
10710 let accounted = motion_search + transform_quant + entropy;
10711 // motion_search already contains interpolation's own time (every
10712 // candidate the search costs calls crate::mc::predict), so it is not
10713 // added again here -- interpolation is reported alongside as "of
10714 // which interpolation", not as a fifth additive bucket.
10715 let other = total_t.saturating_sub(accounted);
10716
10717 eprintln!(
10718 "\n=== inter frame {width}x{height}, one frame ===\n\
10719 total: {total_t:>9.2?} ({} bytes)\n\
10720 motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
10721 {interpolation:>9.2?})\n\
10722 transform + quantize: {transform_quant:>9.2?}\n\
10723 coeff_bits (entropy pricing): {entropy:>9.2?}\n\
10724 everything else (13-mode intra {other:>9.2?}\n\
10725 candidate loop's own predict/bookkeeping, NEARESTMV's own \
10726 predict, RD glue):",
10727 inter.stream.len(),
10728 );
10729 }
10730
10731 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
10732 /// frames (a dark/flat one, a detailed one, a normal film one) at two
10733 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
10734 /// None`, the baseline this same build produces without
10735 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
10736 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
10737 /// go in the lane report, which is where "ship as default" is decided --
10738 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
10739 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
10740 #[test]
10741 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
10742 fn prune_k_quality_sweep() {
10743 let fctx = &crate::decode::FrameCtx::new();
10744 if !have_ffmpeg() {
10745 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
10746 return;
10747 }
10748 let (width, height) = (640usize, 352usize);
10749 let frames: &[(&str, &str, &str)] = &[
10750 // (label, clip, seek) -- a near-black scene, a busy one, and an
10751 // ordinary film frame, each from a different real file.
10752 (
10753 "dark/flat",
10754 "/home/user/Videos/reela.mp4",
10755 "3",
10756 ),
10757 (
10758 "detailed",
10759 "/home/user/Downloads/reelb.mkv",
10760 "1200",
10761 ),
10762 (
10763 "film",
10764 "/home/user/Videos/Films/reelc.mkv",
10765 "600",
10766 ),
10767 ];
10768 for &(label, clip, skip) in frames {
10769 if !std::path::Path::new(clip).exists() {
10770 eprintln!("SKIP {label}: {clip} not present on this machine");
10771 continue;
10772 }
10773 let picture = clip_frame(clip, skip, width, height);
10774 for &q in &[60u8, 150] {
10775 // SAFETY (not literally unsafe, just process-global): this is
10776 // a single-threaded #[ignore] probe, run by hand, never
10777 // alongside other tests that read Search::top_k.
10778 set_test_top_k_override(None);
10779 let baseline = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
10780 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
10781 eprint!(
10782 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
10783 baseline.stream.len(),
10784 baseline_psnr
10785 );
10786 for &k in &[3usize, 4, 6] {
10787 set_test_top_k_override(Some(k));
10788 let pruned = encode_key_frame_with_ctx(&picture, q, 0.5, fctx).unwrap();
10789 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
10790 eprint!(
10791 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
10792 pruned.stream.len(),
10793 pruned_psnr,
10794 pruned_psnr - baseline_psnr
10795 );
10796 }
10797 eprintln!();
10798 }
10799 }
10800 set_test_top_k_override(None);
10801 }
10802
10803 /// Two consecutive decoded frames from one clip, for an inter-frame
10804 /// sweep -- [`clip_frame`] alone only ever gives one.
10805 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
10806 let out = Command::new("ffmpeg")
10807 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
10808 .args(["-vf", &format!("scale={width}:{height}")])
10809 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
10810 .output()
10811 .expect("ffmpeg failed to run");
10812 assert!(
10813 out.status.success(),
10814 "ffmpeg: {}",
10815 String::from_utf8_lossy(&out.stderr)
10816 );
10817 let (luma, chroma) = (width * height, width * height / 4);
10818 let frame_len = luma + 2 * chroma;
10819 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
10820 std::array::from_fn(|i| {
10821 let bytes = &out.stdout[i * frame_len..][..frame_len];
10822 Picture {
10823 width,
10824 height,
10825 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
10826 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
10827 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
10828 }
10829 })
10830 }
10831
10832 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
10833 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
10834 /// then one inter frame off it (`search_inter_block`'s own intra
10835 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
10836 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
10837 /// padding step complicates the comparison. Prints bytes and luma PSNR
10838 /// for the inter frame alone, unpruned vs each `K`.
10839 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
10840 #[test]
10841 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
10842 fn prune_k_quality_sweep_inter() {
10843 let fctx = &crate::decode::FrameCtx::new();
10844 if !have_ffmpeg() {
10845 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
10846 return;
10847 }
10848 let (width, height) = (1280usize, 704usize);
10849 let frames: &[(&str, &str, &str)] = &[
10850 (
10851 "dark/flat",
10852 "/home/user/Videos/reela.mp4",
10853 "3",
10854 ),
10855 (
10856 "detailed",
10857 "/home/user/Downloads/reelb.mkv",
10858 "1200",
10859 ),
10860 (
10861 "film",
10862 "/home/user/Videos/Films/reelc.mkv",
10863 "600",
10864 ),
10865 ];
10866 for &(label, clip, skip) in frames {
10867 if !std::path::Path::new(clip).exists() {
10868 eprintln!("SKIP {label}: {clip} not present on this machine");
10869 continue;
10870 }
10871 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
10872 for &q in &[60u8, 150] {
10873 // SAFETY (not literally unsafe, just process-global): a
10874 // single-threaded #[ignore] probe, run by hand, never
10875 // alongside other tests that read Search::top_k.
10876 set_test_top_k_override_inter(None);
10877 let key = encode_key_frame_with_ctx(&key_source, q, 0.5, fctx).unwrap();
10878 let baseline = encode_inter_frame(
10879 &inter_source,
10880 &key.reconstruction,
10881 q,
10882 0.5,
10883 1,
10884 flat_order_hints(1, 0, false),
10885 (width, height), None, None, None, fctx, None,
10886 )
10887 .unwrap();
10888 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
10889 eprint!(
10890 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
10891 baseline.stream.len(),
10892 baseline_psnr
10893 );
10894 for &k in &[3usize, 4, 6] {
10895 set_test_top_k_override_inter(Some(k));
10896 let pruned = encode_inter_frame(
10897 &inter_source,
10898 &key.reconstruction,
10899 q,
10900 0.5,
10901 1,
10902 flat_order_hints(1, 0, false),
10903 (width, height), None, None, None, fctx, None,
10904 )
10905 .unwrap();
10906 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
10907 eprint!(
10908 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
10909 pruned.stream.len(),
10910 pruned_psnr,
10911 pruned_psnr - baseline_psnr
10912 );
10913 }
10914 eprintln!();
10915 }
10916 }
10917 set_test_top_k_override_inter(None);
10918 }
10919
10920 /// `frames` consecutive pictures out of a real clip, scaled to a whole
10921 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
10922 /// to an arbitrary count for the fixture regression gate below.
10923 fn clip_frames(
10924 clip: &str,
10925 skip: &str,
10926 width: usize,
10927 height: usize,
10928 frames: usize,
10929 ) -> Vec<Picture> {
10930 clip_frames_vf(clip, skip, &format!("scale={width}:{height}"), width, height, frames)
10931 }
10932
10933 /// [`clip_frames`] with the filter chain spelled out, so a caller can ask
10934 /// for a native-resolution CROP instead of a downscale (the downscale is
10935 /// what destroys a screen capture's exact repeats -- class
10936 /// `gate-recipe-confound`). `width`/`height` must be what `vf` produces.
10937 fn clip_frames_vf(
10938 clip: &str,
10939 skip: &str,
10940 vf: &str,
10941 width: usize,
10942 height: usize,
10943 frames: usize,
10944 ) -> Vec<Picture> {
10945 let out = Command::new("ffmpeg")
10946 .args(["-v", "error", "-ss", skip, "-i", clip])
10947 .args(["-frames:v", &frames.to_string()])
10948 .args(["-vf", vf])
10949 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
10950 .output()
10951 .expect("ffmpeg failed to run");
10952 assert!(
10953 out.status.success(),
10954 "ffmpeg: {}",
10955 String::from_utf8_lossy(&out.stderr)
10956 );
10957 let (luma, chroma) = (width * height, width * height / 4);
10958 let frame_len = luma + 2 * chroma;
10959 assert_eq!(
10960 out.stdout.len(),
10961 frame_len * frames,
10962 "expected {frames} 4:2:0 frames"
10963 );
10964 (0..frames)
10965 .map(|i| {
10966 let bytes = &out.stdout[i * frame_len..][..frame_len];
10967 Picture {
10968 width,
10969 height,
10970 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
10971 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
10972 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
10973 }
10974 })
10975 .collect()
10976 }
10977
10978 /// The standing regression gate on real content: 12 frames of a real
10979 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
10980 /// this crate's own input regardless of its own source codec), encoded
10981 /// as an AV1 GOP and checked against three numeric floors so a
10982 /// compatibility or quality regression fails the suite instead of
10983 /// waiting for a downstream repo's gate to catch it (as happened for a
10984 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
10985 /// refusal, both caught only that way).
10986 ///
10987 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
10988 /// that geometry is already covered elsewhere), chosen only so encode
10989 /// time and gate numbers are not muddied by an edge-block class this
10990 /// test is not about.
10991 ///
10992 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
10993 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
10994 /// below carry a margin off those measured numbers (PSNR floor =
10995 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
10996 #[test]
10997 fn real_clip_encodes_within_its_quality_and_size_budget() {
10998 let fctx = &crate::decode::FrameCtx::new();
10999 if !have_ffmpeg() {
11000 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
11001 return;
11002 }
11003 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11004 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
11005 if !clip.exists() {
11006 eprintln!(
11007 "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing",
11008 clip.display()
11009 );
11010 return;
11011 }
11012 let (width, height, frame_count) = (640usize, 384usize, 12usize);
11013 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
11014 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
11015 assert_eq!(encoded.frames.len(), frame_count);
11016
11017 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
11018 // stream and hands back every frame -- a stream a downstream
11019 // decoder refuses is the exact class of regression this gate
11020 // exists for.
11021 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
11022 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
11023
11024 // Gate 2: quality vs the source did not silently collapse.
11025 let mean_psnr: f64 = decoded
11026 .iter()
11027 .zip(&source)
11028 .map(|(d, s)| psnr(&d.y, &s.y))
11029 .sum::<f64>()
11030 / frame_count as f64;
11031 assert!(
11032 mean_psnr >= 44.91,
11033 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
11034 );
11035
11036 // Gate 3: the stream did not silently bloat.
11037 assert!(
11038 encoded.stream.len() <= 80_340,
11039 "stream grew to {} bytes, over the 80340-byte ceiling",
11040 encoded.stream.len()
11041 );
11042 }
11043
11044 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
11045 /// straddle size: 640x384 is exact on both axes (32-aligned), so
11046 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
11047 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
11048 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
11049 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
11050 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
11051 /// card; this one is the real-clip gate, same three floors.
11052 ///
11053 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
11054 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
11055 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
11056 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
11057 #[test]
11058 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
11059 let fctx = &crate::decode::FrameCtx::new();
11060 if !have_ffmpeg() {
11061 eprintln!(
11062 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
11063 no ffmpeg"
11064 );
11065 return;
11066 }
11067 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11068 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
11069 if !clip.exists() {
11070 eprintln!(
11071 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
11072 {} missing",
11073 clip.display()
11074 );
11075 return;
11076 }
11077 let (width, height, frame_count) = (704usize, 400usize, 8usize);
11078 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
11079 let encoded = encode_sequence_with_ctx(&source, 100, 0.5, fctx).unwrap();
11080 assert_eq!(encoded.frames.len(), frame_count);
11081
11082 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
11083 // stream and hands back every frame.
11084 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
11085 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
11086
11087 // Gate 2: quality vs the source did not silently collapse.
11088 let mean_psnr: f64 = decoded
11089 .iter()
11090 .zip(&source)
11091 .map(|(d, s)| psnr(&d.y, &s.y))
11092 .sum::<f64>()
11093 / frame_count as f64;
11094 assert!(
11095 mean_psnr >= 44.98,
11096 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
11097 );
11098
11099 // Gate 3: the stream did not silently bloat.
11100 assert!(
11101 encoded.stream.len() <= 62_703,
11102 "stream grew to {} bytes, over the 62703-byte ceiling",
11103 encoded.stream.len()
11104 );
11105 }
11106
11107 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
11108 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
11109 /// facade -- timed end to end, so the edith export-time projection is a
11110 /// real number rather than a guess from the isolated key/inter numbers
11111 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
11112 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
11113 #[test]
11114 #[ignore = "a perf probe, not a gate"]
11115 fn sequence_bench_sanity() {
11116 let fctx = &crate::decode::FrameCtx::new();
11117 use std::time::Instant;
11118 let (width, height) = (1280usize, 720usize);
11119 let pictures: Vec<Picture> = (0..24)
11120 .map(|i| panned_test_card(width, height, i * 3))
11121 .collect();
11122 let t = Instant::now();
11123 let encoded = encode_sequence_with_ctx(&pictures, 100, 0.5, fctx).unwrap();
11124 let elapsed = t.elapsed();
11125 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
11126 eprintln!(
11127 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
11128 elapsed / 24
11129 );
11130 }
11131
11132 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
11133 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
11134 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
11135 /// -- --ignored --nocapture`.
11136 #[test]
11137 #[ignore = "a calibration probe, not a gate"]
11138 fn calibration_sweep_base_q_idx() {
11139 let fctx = &crate::decode::FrameCtx::new();
11140 if !have_ffmpeg() {
11141 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
11142 return;
11143 }
11144 let (width, height, frames) = (640usize, 384usize, 12usize);
11145 for clip in [
11146 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
11147 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
11148 ] {
11149 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11150 .join("../../fixtures/video")
11151 .join(clip);
11152 if !path.exists() {
11153 eprintln!("SKIP {clip}: fixture missing");
11154 continue;
11155 }
11156 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
11157 eprintln!("--- {clip} ---");
11158 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
11159 let encoded = encode_sequence_with_ctx(&source, q, 0.5, fctx).unwrap();
11160 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
11161 let mean_psnr: f64 = decoded
11162 .iter()
11163 .zip(&source)
11164 .map(|(d, s)| psnr(&d.y, &s.y))
11165 .sum::<f64>()
11166 / frames as f64;
11167 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
11168 eprintln!(
11169 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
11170 encoded.stream.len()
11171 );
11172 }
11173 }
11174 }
11175
11176 // -----------------------------------------------------------------------
11177 // The encoder's standing BD-rate baseline against libaom and rav1e.
11178 // Every PSNR below is measured on FFMPEG-DECODED pixels, never on an
11179 // encoder's own reconstruction ([[shared-oracle-blindness]]): our decoder
11180 // agreeing with our encoder proves nothing about the bitstream.
11181 // -----------------------------------------------------------------------
11182
11183 /// All-plane PSNR of a decoded picture against its source, on the same
11184 /// 8-bit scale [`psnr`] uses.
11185 fn psnr_all(decoded: &Picture, source: &Picture) -> f64 {
11186 let cat = |p: &Picture| {
11187 let mut v = Vec::with_capacity(p.y.len() + p.u.len() + p.v.len());
11188 v.extend_from_slice(&p.y);
11189 v.extend_from_slice(&p.u);
11190 v.extend_from_slice(&p.v);
11191 v
11192 };
11193 psnr(&cat(decoded), &cat(source))
11194 }
11195
11196 /// The pictures back as the planar 8-bit bytes an encoder reads.
11197 fn raw_yuv420p(source: &[Picture]) -> Vec<u8> {
11198 let mut raw = Vec::new();
11199 for p in source {
11200 for plane in [&p.y, &p.u, &p.v] {
11201 raw.extend(plane.iter().map(|&s| s as u8));
11202 }
11203 }
11204 raw
11205 }
11206
11207 /// A (all-plane PSNR, log10 bytes) ladder from another AV1 encoder driven
11208 /// through ffmpeg: one point per entry of `points`, each a quality flag
11209 /// set. Returns the ladder ordered by fidelity and the total encode wall
11210 /// clock. The stream is decoded back through [`ffmpeg_decode_sequence`],
11211 /// so both curves are measured by the same decoder.
11212 fn external_ladder(
11213 source: &[Picture],
11214 width: usize,
11215 height: usize,
11216 encoder: &str,
11217 points: &[Vec<String>],
11218 ) -> (Vec<(f64, f64)>, f64) {
11219 // [[pid-keyed-temp-path]]: parallel test binaries must not share a name.
11220 let dir = std::env::temp_dir();
11221 let raw_path = dir.join(format!("ec-av1-bd-{}-{encoder}.yuv", std::process::id()));
11222 std::fs::write(&raw_path, raw_yuv420p(source)).expect("raw source");
11223 let mut ladder = Vec::new();
11224 let mut wall = 0.0;
11225 for (i, params) in points.iter().enumerate() {
11226 let obu = dir.join(format!("ec-av1-bd-{}-{encoder}-{i}.obu", std::process::id()));
11227 let start = std::time::Instant::now();
11228 let out = Command::new("ffmpeg")
11229 .args(["-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p"])
11230 .args(["-s", &format!("{width}x{height}"), "-r", "24", "-i"])
11231 .arg(&raw_path)
11232 .args(["-an", "-threads", "1"])
11233 .args(["-g", &source.len().to_string(), "-c:v", encoder])
11234 .args(params)
11235 .args(["-f", "obu"])
11236 .arg(&obu)
11237 .output()
11238 .expect("ffmpeg failed to run");
11239 wall += start.elapsed().as_secs_f64();
11240 assert!(
11241 out.status.success(),
11242 "{encoder} {params:?}: {}",
11243 String::from_utf8_lossy(&out.stderr)
11244 );
11245 let stream = std::fs::read(&obu).expect("reference stream");
11246 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
11247 let mean: f64 = decoded
11248 .iter()
11249 .zip(source)
11250 .map(|(d, s)| psnr_all(d, s))
11251 .sum::<f64>()
11252 / source.len() as f64;
11253 ladder.push((mean, (stream.len() as f64).log10()));
11254 let _ = std::fs::remove_file(&obu);
11255 }
11256 let _ = std::fs::remove_file(&raw_path);
11257 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
11258 (ladder, wall)
11259 }
11260
11261 /// First differing sample between two pictures, as
11262 /// `(plane, index, left, right)` -- so a gate failure names the plane and
11263 /// the sample instead of just "differs". A length difference counts as a
11264 /// mismatch of that plane at the first index past the shorter one.
11265 fn first_plane_mismatch(a: &Picture, b: &Picture) -> Option<(&'static str, usize, i64, i64)> {
11266 for (plane, l, r) in [("Y", &a.y, &b.y), ("U", &a.u, &b.u), ("V", &a.v, &b.v)] {
11267 if let Some(i) = l.iter().zip(r.iter()).position(|(x, y)| x != y) {
11268 return Some((plane, i, i64::from(l[i]), i64::from(r[i])));
11269 }
11270 if l.len() != r.len() {
11271 return Some((plane, l.len().min(r.len()), l.len() as i64, r.len() as i64));
11272 }
11273 }
11274 None
11275 }
11276
11277 /// The same ladder for this encoder, at four `base_q_idx` points. The PSNR
11278 /// comes from ffmpeg's decode of our own stream, and at EVERY point the
11279 /// stream is decoded twice -- by ffmpeg and by our own
11280 /// [`crate::stream::decode_stream`] -- and all three pictures (encoder
11281 /// reconstruction, ffmpeg's decode, our decode) are asserted sample-exact
11282 /// in Y, U and V over every shown frame in display order. That is itself
11283 /// a gate: it proves the bitstream says what the encoder thinks, in the
11284 /// only two decoders that read it.
11285 fn our_ladder(
11286 name: &str,
11287 source: &[Picture],
11288 width: usize,
11289 height: usize,
11290 fctx: &crate::decode::FrameCtx,
11291 ) -> (Vec<(f64, f64)>, f64) {
11292 let mut ladder = Vec::new();
11293 let mut wall = 0.0;
11294 for &q in &[150u8, 120, 90, 60] {
11295 let start = std::time::Instant::now();
11296 let encoded = encode_sequence_with_ctx(source, q, 0.5, fctx).unwrap();
11297 wall += start.elapsed().as_secs_f64();
11298 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, source.len());
11299 let ours = crate::stream::decode_stream(&encoded.stream).expect("our decoder");
11300 assert_eq!(
11301 ours.len(),
11302 source.len(),
11303 "{name} q={q}: our decoder's display-order frame count"
11304 );
11305 for (i, (d, e)) in decoded.iter().zip(&encoded.frames).enumerate() {
11306 if let Some((plane, s, got, want)) = first_plane_mismatch(d, &e.reconstruction) {
11307 panic!(
11308 "{name} q={q} frame {i} plane {plane} sample {s}: ffmpeg decoded \
11309 {got}, the encoder reconstructed {want}"
11310 );
11311 }
11312 }
11313 for (i, (o, e)) in ours.iter().zip(&encoded.frames).enumerate() {
11314 if let Some((plane, s, got, want)) = first_plane_mismatch(o, &e.reconstruction) {
11315 panic!(
11316 "{name} q={q} frame {i} plane {plane} sample {s}: our decoder decoded \
11317 {got}, the encoder reconstructed {want}"
11318 );
11319 }
11320 }
11321 let mean: f64 = decoded
11322 .iter()
11323 .zip(source)
11324 .map(|(d, s)| psnr_all(d, s))
11325 .sum::<f64>()
11326 / source.len() as f64;
11327 ladder.push((mean, (encoded.stream.len() as f64).log10()));
11328 }
11329 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
11330 (ladder, wall)
11331 }
11332
11333 /// The [`crate::encoder::Pyramid`] this run's ladder is coded under, from
11334 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]`. Unset
11335 /// keeps the flat one-key-then-all-inter ladder the baseline was measured
11336 /// on, so the gate's default recipe is unchanged.
11337 fn pyramid_from_env() -> Option<crate::encoder::Pyramid> {
11338 let spec = std::env::var("EC_AV1_PYRAMID").ok()?;
11339 let mut f = spec.split(':');
11340 let mini_gop = f.next()?.parse().ok()?;
11341 let d = crate::encoder::Pyramid::default();
11342 Some(crate::encoder::Pyramid {
11343 mini_gop,
11344 arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset),
11345 leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset),
11346 })
11347 }
11348
11349 /// [`our_ladder`] through the streaming facade with a coding pyramid: the
11350 /// four points are the same `base_q_idx` ladder, but each stream is
11351 /// reordered (hidden `ALTREF` first, `show_existing_frame` last per
11352 /// group) and each level is coded at its own quantizer offset. Returns
11353 /// the ladder, the wall, and — per pyramid level over the whole ladder —
11354 /// how many frames and how many bytes it spent.
11355 fn our_ladder_pyramid(
11356 name: &str,
11357 source: &[Picture],
11358 width: usize,
11359 height: usize,
11360 pyramid: crate::encoder::Pyramid,
11361 ) -> (Vec<(f64, f64)>, f64, [usize; 4], [usize; 4]) {
11362 use crate::encoder::{Av1Encoder, Colour, EncoderConfig, Level};
11363 let slot = |l: Level| match l {
11364 Level::Key => 0,
11365 Level::Arf => 1,
11366 Level::Leaf => 2,
11367 Level::ShowExisting => 3,
11368 };
11369 let mut ladder = Vec::new();
11370 let mut wall = 0.0;
11371 let (mut counts, mut bytes) = ([0usize; 4], [0usize; 4]);
11372 for &q in &[150u8, 120, 90, 60] {
11373 let config = EncoderConfig {
11374 width,
11375 height,
11376 base_q_idx: q,
11377 gop: source.len(),
11378 colour: Colour::Unspecified,
11379 tile_cols_log2: 0,
11380 tile_rows_log2: 0,
11381 };
11382 let start = std::time::Instant::now();
11383 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
11384 let mut packets = Vec::new();
11385 for picture in source {
11386 packets.extend(enc.encode_frames(picture).unwrap());
11387 }
11388 packets.extend(enc.flush().unwrap());
11389 wall += start.elapsed().as_secs_f64();
11390 let mut stream = Vec::new();
11391 for p in &packets {
11392 counts[slot(p.level)] += 1;
11393 bytes[slot(p.level)] += p.data.len();
11394 stream.extend_from_slice(&p.data);
11395 }
11396 // [[gate-blind-to-hidden-frames]]: a reordered stream is only
11397 // correct if the DISPLAY-order output still has one frame per
11398 // source picture, in the right order -- checked against our own
11399 // decoder as well as ffmpeg's, both below.
11400 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
11401 assert_eq!(ours.len(), source.len(), "{name} q={q}: our display-order count");
11402 let decoded = ffmpeg_decode_sequence(&stream, width, height, source.len());
11403 for (i, (d, o)) in decoded.iter().zip(&ours).enumerate() {
11404 if let Some((plane, s, got, want)) = first_plane_mismatch(d, o) {
11405 panic!(
11406 "{name} q={q} display frame {i} plane {plane} sample {s}: ffmpeg \
11407 decoded {got}, our decoder decoded {want}"
11408 );
11409 }
11410 }
11411 let mean: f64 = decoded
11412 .iter()
11413 .zip(source)
11414 .map(|(d, s)| psnr_all(d, s))
11415 .sum::<f64>()
11416 / source.len() as f64;
11417 ladder.push((mean, (stream.len() as f64).log10()));
11418 }
11419 ladder.sort_by(|a, b| a.0.total_cmp(&b.0));
11420 (ladder, wall, counts, bytes)
11421 }
11422
11423 /// Byte-exactness gate for encoder work that is meant to change only
11424 /// how long the encoder takes.
11425 ///
11426 /// The BD gate above measures quality, which a speed lane can move by a
11427 /// hair without failing anything; this pins the streams themselves.
11428 /// Re-measured on the lane-av1lr merge with main d5fc99e0 (per-64x64
11429 /// `cdef_idx` literals and per-unit loop restoration syntax are new bits
11430 /// in the tile) and again on lane-av1mv's merge of it: an extra
11431 /// reference's `NEWMV` is a coded-bits change too, judged by the BD gate
11432 /// above, not by this pin. Re-pinned on lane-av1price2: the search now
11433 /// prices coefficients against the tables the frame's writer really
11434 /// starts from on every non-screen frame (`tile::arm_pricing_cdfs`), a
11435 /// decision change the BD gate judges. Re-pinned again on
11436 /// lane-av1skipctx: the search now prices `txb_skip`/`dc_sign` at the
11437 /// real neighbour contexts ([`Plane::coef_ctx`]) instead of zero, which
11438 /// is the same kind of decision change. Re-pinned on lane-av1lambda:
11439 /// [`LAMBDA_SCALE`] moved 0.1 -> 0.05, so every RD decision in the
11440 /// search moved with it.
11441 #[test]
11442 fn the_encoders_own_streams_are_byte_identical_to_their_pins() {
11443 if !have_ffmpeg() {
11444 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no ffmpeg");
11445 return;
11446 }
11447 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
11448 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
11449 if !clip.exists() {
11450 eprintln!("SKIP the_encoders_own_streams_are_byte_identical_to_their_pins: no clip");
11451 return;
11452 }
11453 let source = clip_frames(clip.to_str().unwrap(), "0", 640, 384, 4);
11454 // FNV-1a over the stream: a witness that every coded bit is where it
11455 // was, which a byte count alone is not.
11456 let fnv = |b: &[u8]| {
11457 b.iter().fold(0xcbf2_9ce4_8422_2325u64, |h, &v| {
11458 (h ^ u64::from(v)).wrapping_mul(0x0000_0100_0000_01b3)
11459 })
11460 };
11461 let pins: [(u8, usize, u64); 2] =
11462 [(150, 7130, 0x0415_8aec_b26b_195a), (60, 26185, 0x9e7b_b2c7_672b_c381)];
11463 for (q, bytes, hash) in pins {
11464 let encoded = encode_sequence(&source, q, 0.5).unwrap();
11465 assert_eq!(
11466 (encoded.stream.len(), fnv(&encoded.stream)),
11467 (bytes, hash),
11468 "q={q}: the encoder's stream moved"
11469 );
11470 }
11471 }
11472
11473 /// A ladder is only a ladder if both axes rise together.
11474 fn assert_monotone(name: &str, ladder: &[(f64, f64)]) {
11475 assert_eq!(ladder.len(), 4, "{name}: wanted four quality points");
11476 for w in ladder.windows(2) {
11477 assert!(
11478 w[1].0 > w[0].0 && w[1].1 > w[0].1,
11479 "{name}: not monotone, {ladder:?}"
11480 );
11481 }
11482 }
11483
11484 /// The sweep behind [`screen_content`]'s two constants
11485 /// (`unswept-decision-constants`): the share of 16x16 luma blocks with at
11486 /// most N distinct colours, per gate clip, at the size the gate codes.
11487 /// `cargo test -p ec-av1 --release --lib -- --ignored probe_screen_detect --nocapture`
11488 #[test]
11489 #[ignore = "reads the real library"]
11490 fn probe_screen_detect() {
11491 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
11492 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
11493 for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] {
11494 let path = fixtures.join("video").join(name);
11495 if path.exists() {
11496 clips.push((name.to_string(), path));
11497 }
11498 }
11499 if let Ok(manifest) = std::fs::read_to_string(fixtures.join("real-library-manifest.tsv"))
11500 && let Some(p) = manifest
11501 .lines()
11502 .skip(1)
11503 .filter_map(|l| l.split('\t').next())
11504 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
11505 {
11506 clips.push(("screen".to_string(), std::path::PathBuf::from(p)));
11507 }
11508 let (width, height) = (640usize, 384usize);
11509 for (name, path) in &clips {
11510 let frames = clip_frames(path.to_str().unwrap(), "0", width, height, 4);
11511 for (f, picture) in frames.iter().enumerate() {
11512 let y: Vec<u8> = picture.y.iter().map(|&v| v as u8).collect();
11513 let mut hist = [0usize; 257];
11514 let mut blocks = 0usize;
11515 for by in (0..height).step_by(16) {
11516 for bx in (0..width).step_by(16) {
11517 let mut seen = [false; 256];
11518 let mut colors = 0usize;
11519 for row in 0..16 {
11520 for col in 0..16 {
11521 let v = usize::from(y[(by + row) * width + bx + col]);
11522 if !seen[v] {
11523 seen[v] = true;
11524 colors += 1;
11525 }
11526 }
11527 }
11528 hist[colors] += 1;
11529 blocks += 1;
11530 }
11531 }
11532 let share = |limit: usize| {
11533 100.0 * hist[2..=limit.min(256)].iter().sum::<usize>() as f64
11534 / blocks.max(1) as f64
11535 };
11536 eprintln!(
11537 "{name} frame {f}: <=4 {:.1}% <=8 {:.1}% <=16 {:.1}% <=32 {:.1}% <=64 {:.1}% <=128 {:.1}%",
11538 share(4),
11539 share(8),
11540 share(16),
11541 share(32),
11542 share(64),
11543 share(128),
11544 );
11545 }
11546 }
11547 }
11548
11549 /// The missing instrument: what this encoder costs against libaom and
11550 /// rav1e at matched fidelity, and how long it takes to get there.
11551 ///
11552 /// Recipe, identical on all three sides: 12 consecutive frames of each
11553 /// clip scaled to 640x384 (a whole number of superblocks), one key frame
11554 /// then 11 inter frames (`-g 12`, matching our own sequence shape), one
11555 /// tile, `-threads 1`, no film grain synthesis (neither reference enables
11556 /// it by default), 4:2:0 8-bit in and out. Reference points:
11557 /// libaom-av1: `-cpu-used 6 -b:v 0 -crf {5,20,35,45}`
11558 /// librav1e: `-rav1e-params speed=6:quantizer={50,100,150,200}:
11559 /// tile_cols=1:tile_rows=1:threads=1`
11560 /// ours: `base_q_idx {60,90,120,150}`. Every PSNR is all-plane, on
11561 /// ffmpeg-decoded frames of each encoder's own stream.
11562 ///
11563 /// Measured 2026-09-06 after the in-loop filters (lane-av1filt: per-frame
11564 /// deblocking levels and CDEF strengths, both chosen by re-decoding the
11565 /// coded tile -- `crate::filter_search`), 12 frames, this box (wall = the
11566 /// four encodes of that ladder together):
11567 ///
11568 /// | clip | ours (q 150/120/90/60) | BD-rate vs libaom | vs rav1e | wall ours:aom:rav1e |
11569 /// |---|---|---|---|---|
11570 /// | 1080p fixture | 42.11 dB/17774 B .. 50.99 dB/76838 B | +143.6% | +94.0% | 9.2s:1.1s:2.6s |
11571 /// | 2160p fixture | 42.84 dB/12480 B .. 51.43 dB/46557 B | +179.5% | +128.8% | 8.6s:1.0s:2.2s |
11572 /// | screen capture | 39.76 dB/9536 B .. 48.87 dB/29189 B | +88.0% | +21.5% | 7.2s:1.0s:2.1s |
11573 ///
11574 /// Re-measured 2026-09-06 after lane-av1fwd, which changed only how long
11575 /// the encoder takes -- every stream it writes is byte-identical, so the
11576 /// BD columns are this box's own re-run of the same recipe rather than a
11577 /// quality move (+141.3/+174.2/+88.9 vs libaom, +91.9/+124.5/+21.6 vs
11578 /// rav1e). What moved is the wall of the four encodes:
11579 ///
11580 /// | clip | wall ours before | after | instructions:u before -> after |
11581 /// |---|---|---|---|
11582 /// | 1080p fixture | 9.2s | 7.2s | 191.5G -> 139.8G (-27.0%) |
11583 /// | 2160p fixture | 8.6s | 6.9s | 183.5G -> 136.4G (-25.6%) |
11584 /// | screen capture | 7.2s | 6.7s | 157.2G -> 122.5G (-22.1%) |
11585 ///
11586 /// Three exact steps, none of which touches a coded bit: the coefficient
11587 /// rate pricer stopped rebuilding every CDF table per candidate
11588 /// (`tile::coeff_bits`), the filter search stopped re-decoding its own
11589 /// tile once per candidate (`decode::FilterReplay`), and the forward
11590 /// transform stopped transforming the all-zero residual that 70% of its
11591 /// calls carry.
11592 ///
11593 /// The three steps of that lane, same recipe (vs libaom, then vs rav1e):
11594 ///
11595 /// | step | 1080p | 2160p | screen |
11596 /// |---|---|---|---|
11597 /// | no in-loop filter | +234.0 / +171.9 | +260.3 / +203.2 | +318.5 / +155.3 |
11598 /// | + deblocking | +198.2 / +143.1 | +218.1 / +162.4 | +136.9 / +52.7 |
11599 /// | + CDEF | +143.6 / +94.0 | +179.5 / +128.8 | +88.0 / +21.5 |
11600 ///
11601 /// Loop restoration is NOT in yet: it is the one filter whose parameters
11602 /// are per restoration UNIT inside the tile payload, so it needs both
11603 /// tile writers to code `lr` syntax and an encoder-visible post-CDEF
11604 /// buffer to solve against -- neither of which this frame-header-level
11605 /// search reaches.
11606 ///
11607 /// The baseline it replaced, before an inter frame's blocks chose their
11608 /// own partition, was +501.4/+504.4/+440.9 against libaom and
11609 /// +364.4/+401.0/+206.0 against rav1e at 5.1/4.6/5.9 s.
11610 ///
11611 /// So: roughly 2.5-3x libaom's rate and 1.5-2x rav1e's at matched
11612 /// fidelity, while spending far more time than either (the partition
11613 /// search's own cost, uncut: see the two intra-pruning variants measured
11614 /// and rejected in the lane report). No
11615 /// threshold is asserted yet -- this run sets the baseline; the gate
11616 /// asserts four monotone points per ladder, and at EVERY ladder point of
11617 /// EVERY clip it decodes our stream twice -- with ffmpeg and with our own
11618 /// `crate::stream::decode_stream` -- and asserts the encoder's
11619 /// reconstruction, ffmpeg's decode and our decode sample-exact in Y, U
11620 /// and V over every shown frame in display order. A failure names the
11621 /// clip, the q, the frame, the plane and the first differing sample.
11622 /// (Under `EC_AV1_PYRAMID` the frames come out of the streaming facade,
11623 /// which exposes no per-packet reconstruction, so that path asserts the
11624 /// two decoders against each other on all three planes.)
11625 ///
11626 /// Run:
11627 /// cargo test -p ec-av1 --release --lib -- --ignored \
11628 /// bd_rate_vs_libaom_and_rav1e --nocapture
11629 #[test]
11630 #[ignore = "the encoder BD-rate baseline: minutes per clip, needs ffmpeg"]
11631 fn bd_rate_vs_libaom_and_rav1e() {
11632 if !have_ffmpeg() {
11633 eprintln!("SKIP bd_rate_vs_libaom_and_rav1e: no ffmpeg");
11634 return;
11635 }
11636 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
11637 let mut clips: Vec<(String, std::path::PathBuf)> = Vec::new();
11638 for name in ["h264-1080p-23.976-8bit.mp4", "h264-2160p-23.976-8bit.mp4"] {
11639 let path = fixtures.join("video").join(name);
11640 if path.exists() {
11641 clips.push((name.to_string(), path));
11642 } else {
11643 eprintln!("SKIP clip {name}: missing");
11644 }
11645 }
11646 // Screen capture: the repo carries no screen-capture fixture, so take
11647 // the first OBS recording the real-library manifest names.
11648 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
11649 Ok(manifest) => {
11650 let screen = manifest
11651 .lines()
11652 .skip(1)
11653 .filter_map(|l| l.split('\t').next())
11654 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists());
11655 match screen {
11656 Some(p) => clips.push((
11657 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
11658 std::path::PathBuf::from(p),
11659 )),
11660 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
11661 }
11662 }
11663 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
11664 }
11665 assert!(!clips.is_empty(), "no source clip available");
11666
11667 let (width, height, frames) = (640usize, 384usize, 12usize);
11668 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
11669 .iter()
11670 .map(|q| {
11671 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
11672 .map(String::from)
11673 .to_vec()
11674 })
11675 .collect();
11676 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
11677 .iter()
11678 .map(|q| {
11679 vec![
11680 "-rav1e-params".to_string(),
11681 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
11682 ]
11683 })
11684 .collect();
11685 println!(
11686 "\n{frames} frames of each clip at {width}x{height}, gop={frames}, 1 tile, 1 thread"
11687 );
11688 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e |");
11689 println!("|---|---|---|---|---|");
11690 for (name, path) in &clips {
11691 let fctx = &crate::decode::FrameCtx::new();
11692 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
11693 let _ = take_partition_hits();
11694 let _ = crate::tile::take_palette_hits();
11695 SCREEN_FRAMES.iter().for_each(|c| {
11696 c.store(0, std::sync::atomic::Ordering::Relaxed);
11697 });
11698 let _ = take_uv_mode_hits();
11699 let _ = crate::tile::take_inter_mode_hits();
11700 let _ = crate::tile::take_drl_hits();
11701 let _ = crate::tile::take_ref_hits();
11702 let _ = crate::tile::take_compound_mode_hits();
11703 let _ = crate::tile::take_compound_pair_hits();
11704 let _ = crate::tile::take_compound_size_hits();
11705 let _ = crate::tile::take_compound_leaf_mode_hits();
11706 let _ = crate::motion::take_census();
11707 let (ours, ours_wall) = match pyramid_from_env() {
11708 None => our_ladder(name, &source, width, height, fctx),
11709 Some(pyramid) => {
11710 let (ladder, wall, counts, bytes) =
11711 our_ladder_pyramid(name, &source, width, height, pyramid);
11712 eprintln!(
11713 "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \
11714 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
11715 counts[0], counts[1], counts[2], counts[3],
11716 bytes[0], bytes[1], bytes[2], bytes[3],
11717 );
11718 (ladder, wall)
11719 }
11720 };
11721 // How often the inter split actually fired over this clip's four
11722 // encodes, against the whole 32x32 that was the only outcome
11723 // before (gate-blind-to-feature).
11724 let [whole32, split32, whole16, split16] = take_partition_hits();
11725 // Which inter modes actually fired over this clip's four encodes,
11726 // and at which DRL index -- a mode nobody picks is a mode the BD
11727 // number cannot be crediting (gate-blind-to-feature).
11728 let [nearest, near, global, new] = crate::tile::take_inter_mode_hits();
11729 let [drl0, drl1, drl2, drl3] = crate::tile::take_drl_hits();
11730 let refs = crate::tile::take_ref_hits();
11731 let modes_total = (nearest + near + global + new).max(1);
11732 eprintln!(
11733 "{name}: inter modes NEAREST {nearest} ({:.1}%) NEAR {near} ({:.1}%) \
11734 GLOBAL {global} ({:.1}%) NEW {new} ({:.1}%); drl idx 0/1/2/3+ \
11735 {drl0}/{drl1}/{drl2}/{drl3}",
11736 100.0 * nearest as f64 / modes_total as f64,
11737 100.0 * near as f64 / modes_total as f64,
11738 100.0 * global as f64 / modes_total as f64,
11739 100.0 * new as f64 / modes_total as f64,
11740 );
11741 // The compound census: what share of the coded inter blocks took
11742 // a compound reference at all, which compound mode they took, and
11743 // which pair (gate-blind-to-feature -- a compound mode nobody
11744 // picks cannot be what a BD number credits).
11745 let comp_modes = crate::tile::take_compound_mode_hits();
11746 let comp_pairs = crate::tile::take_compound_pair_hits();
11747 let comp_sizes = crate::tile::take_compound_size_hits();
11748 let comp_leaf = crate::tile::take_compound_leaf_mode_hits();
11749 let comp_total: usize = comp_modes.iter().sum();
11750 eprintln!(
11751 "{name}: compound {comp_total} of {} inter blocks ({:.1}%); modes \
11752 NEAREST_NEAREST {} NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} \
11753 GLOBAL_GLOBAL {} NEW_NEW {}; pairs LAST+GOLDEN {} LAST+ALTREF {}",
11754 modes_total + comp_total,
11755 100.0 * comp_total as f64 / (modes_total + comp_total) as f64,
11756 comp_modes[0], comp_modes[1], comp_modes[2], comp_modes[3],
11757 comp_modes[6], comp_modes[7],
11758 comp_pairs[3], comp_pairs[6],
11759 );
11760 eprintln!(
11761 "{name}: leaf (16x16 and below) compound modes NEAREST_NEAREST {} \
11762 NEAR_NEAR {} NEAREST_NEW {} NEW_NEAREST {} GLOBAL_GLOBAL {} NEW_NEW {}",
11763 comp_leaf[0], comp_leaf[1], comp_leaf[2], comp_leaf[3], comp_leaf[6],
11764 comp_leaf[7],
11765 );
11766 eprintln!(
11767 "{name}: compound by size 8x8 {} 16x16 {} 32x32 {}",
11768 comp_sizes[1], comp_sizes[2], comp_sizes[3],
11769 );
11770 // Where the wall-owning stage actually goes: how many candidate
11771 // evaluations (one `mc::predict` + SAD each) a search spends, how
11772 // many of them are subpel, and how often the winner is the seed
11773 // it started from -- the census the seeded search is judged by.
11774 let [calls, evals, subpel, rounds, near_pred, unmoved] = crate::motion::take_census();
11775 let per = |n: u64| n as f64 / calls.max(1) as f64;
11776 eprintln!(
11777 "{name}: motion search {calls} calls, {evals} candidate evals ({:.1}/call, \
11778 {:.1}% of them subpel), {rounds} integer rounds ({:.2}/call); winner within \
11779 +-1 pel of pred_mv {:.1}%, winner = starting seed {:.1}%",
11780 per(evals),
11781 100.0 * subpel as f64 / evals.max(1) as f64,
11782 per(rounds),
11783 100.0 * near_pred as f64 / calls.max(1) as f64,
11784 100.0 * unmoved as f64 / calls.max(1) as f64,
11785 );
11786 eprintln!(
11787 "{name}: references LAST {} GOLDEN {} (LAST2 {} LAST3 {} BWD {} ALT2 {} ALT {})",
11788 refs[0], refs[3], refs[1], refs[2], refs[4], refs[5], refs[6]
11789 );
11790 eprintln!(
11791 "{name}: inter 32x32 split into 16s {split32} of {} blocks ({:.1}%); \
11792 16x16 leaves split into 8s {split16} of {} ({:.1}%)",
11793 whole32 + split32,
11794 100.0 * split32 as f64 / (whole32 + split32).max(1) as f64,
11795 whole16 + split16,
11796 100.0 * split16 as f64 / (whole16 + split16).max(1) as f64
11797 );
11798 // The deblocking level each of this clip's frames chose
11799 // (lane-av1filt): 0 everywhere would mean the filter never fires.
11800 let levels = crate::filter_search::take_chosen_levels();
11801 type Chosen = ((u8, u8), (u8, u8), (u8, u8));
11802 let mean = |f: fn(&Chosen) -> u8| {
11803 levels.iter().map(|l| f(l) as f64).sum::<f64>() / levels.len().max(1) as f64
11804 };
11805 eprintln!(
11806 "{name}: over {} frames -- deblock luma mean {:.1} chroma {:.1}; \
11807 cdef luma pri {:.1}/sec {:.1}, chroma pri {:.1}/sec {:.1}",
11808 levels.len(),
11809 mean(|l| l.0.0),
11810 mean(|l| l.0.1),
11811 mean(|l| l.1.0),
11812 mean(|l| l.1.1),
11813 mean(|l| l.2.0),
11814 mean(|l| l.2.1),
11815 );
11816 // How many strength presets each frame's CDEF list carried and
11817 // how the 64x64 units spread over them (lane-av1lr): `bits 0`
11818 // everywhere would mean the per-unit choice never fires.
11819 let presets = crate::filter_search::take_cdef_presets();
11820 let mut by_bits = [0usize; 4];
11821 for (b, _) in &presets {
11822 by_bits[usize::from(*b)] += 1;
11823 }
11824 let units: usize = presets.iter().flat_map(|(_, c)| c).sum();
11825 let on_extra: usize = presets
11826 .iter()
11827 .flat_map(|(_, c)| c.iter().skip(1))
11828 .sum();
11829 eprintln!(
11830 "{name}: cdef_bits frames {}/{}/{}/{} (0/1/2/3); {} of {} 64x64 units \
11831 on a non-default preset ({:.1}%)",
11832 by_bits[0],
11833 by_bits[1],
11834 by_bits[2],
11835 by_bits[3],
11836 on_extra,
11837 units,
11838 100.0 * on_extra as f64 / units.max(1) as f64
11839 );
11840 // How the 64x64 luma restoration units split between
11841 // RESTORE_NONE and Wiener (lane-av1lr).
11842 let (lr_none, lr_wiener) = crate::filter_search::take_lr_histogram();
11843 eprintln!(
11844 "{name}: lr units none={lr_none} wiener={lr_wiener} ({:.1}% restored)",
11845 100.0 * lr_wiener as f64 / (lr_none + lr_wiener).max(1) as f64
11846 );
11847 // Which chroma modes the search actually wins with, against the
11848 // unconditional DC_PRED that was the only outcome before
11849 // (gate-blind-to-feature).
11850 // Screen-content detection and the palette it turns on
11851 // (gate-blind-to-feature): how many frames set
11852 // `allow_screen_content_tools`, how many blocks took a palette,
11853 // and of what size. A film clip must print `screen frames on=0`.
11854 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
11855 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
11856 // Which tables the SEARCH priced against, per frame arming
11857 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
11858 // real starting ones. A film clip must show every inter arming on
11859 // the real side, a screen clip none of them.
11860 let (price_default, price_real) = crate::tile::take_pricing_hits();
11861 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
11862 let palette = crate::tile::take_palette_hits();
11863 eprintln!(
11864 "{name}: screen frames on={screen_on} off={screen_off}; palette blocks {} sizes {}",
11865 palette[0],
11866 (2..=8)
11867 .filter(|&n| palette[n] > 0)
11868 .map(|n| format!("{n}={}", palette[n]))
11869 .collect::<Vec<_>>()
11870 .join(" ")
11871 );
11872 let palette_uv = crate::tile::take_palette_uv_hits();
11873 eprintln!(
11874 "{name}: chroma palette blocks {} sizes {}",
11875 palette_uv[0],
11876 (2..=8)
11877 .filter(|&n| palette_uv[n] > 0)
11878 .map(|n| format!("{n}={}", palette_uv[n]))
11879 .collect::<Vec<_>>()
11880 .join(" ")
11881 );
11882 let uv = take_uv_mode_hits();
11883 let uv_total: usize = uv.iter().sum();
11884 eprintln!(
11885 "{name}: uv modes {}",
11886 uv.iter()
11887 .enumerate()
11888 .filter(|&(_, &n)| n > 0)
11889 .map(|(m, &n)| format!(
11890 "{}={n} ({:.1}%)",
11891 UV_MODE_NAMES[m],
11892 100.0 * n as f64 / uv_total.max(1) as f64
11893 ))
11894 .collect::<Vec<_>>()
11895 .join(" ")
11896 );
11897 // Which transform depth the intra blocks of this clip's key
11898 // frames resolved to (lane-av1tx): depth 0 is one transform over
11899 // the whole block, 1 and 2 its halvings.
11900 let depths = take_tx_depth_hits();
11901 let depth_total: usize = depths.iter().sum();
11902 eprintln!(
11903 "{name}: intra tx depths {}",
11904 depths
11905 .iter()
11906 .enumerate()
11907 .map(|(d, &n)| format!(
11908 "{d}={n} ({:.1}%)",
11909 100.0 * n as f64 / depth_total.max(1) as f64
11910 ))
11911 .collect::<Vec<_>>()
11912 .join(" ")
11913 );
11914 // And which var-tx depth this clip's INTER blocks resolved to
11915 // (lane-av1tx2): 0 is one transform over the whole block, 1 its
11916 // four halves.
11917 let splits = take_inter_tx_split_hits();
11918 let split_total: usize = splits.iter().sum();
11919 eprintln!(
11920 "{name}: inter var-tx depths {}",
11921 splits
11922 .iter()
11923 .enumerate()
11924 .map(|(d, &n)| format!(
11925 "{d}={n} ({:.1}%)",
11926 100.0 * n as f64 / split_total.max(1) as f64
11927 ))
11928 .collect::<Vec<_>>()
11929 .join(" ")
11930 );
11931 // lane-av1obmc: how many blocks actually CODED a motion_mode
11932 // symbol and which value they took, by footprint -- "OBMC is on"
11933 // as a measurement rather than a claim (class
11934 // `gate-blind-to-feature`).
11935 let mm = crate::tile::take_motion_mode_hits();
11936 eprintln!(
11937 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
11938 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
11939 eligible)",
11940 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
11941 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
11942 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
11943 mm.iter().sum::<usize>(),
11944 );
11945 let (aom, aom_wall) =
11946 external_ladder(&source, width, height, "libaom-av1", &aom_points);
11947 let (rav1e, rav1e_wall) =
11948 external_ladder(&source, width, height, "librav1e", &rav1e_points);
11949 assert_monotone(&format!("{name}: ours"), &ours);
11950 assert_monotone(&format!("{name}: libaom"), &aom);
11951 assert_monotone(&format!("{name}: rav1e"), &rav1e);
11952 let points = ours
11953 .iter()
11954 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
11955 .collect::<Vec<_>>()
11956 .join(", ");
11957 println!(
11958 "| {name} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
11959 bd_rate(&aom, &ours) * 100.0,
11960 bd_rate(&rav1e, &ours) * 100.0,
11961 );
11962 println!(
11963 "| references | libaom {} | rav1e {} | | |",
11964 aom.iter()
11965 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
11966 .collect::<Vec<_>>()
11967 .join(", "),
11968 rav1e
11969 .iter()
11970 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
11971 .collect::<Vec<_>>()
11972 .join(", "),
11973 );
11974 }
11975 }
11976 /// The video stream's coded size, from ffprobe.
11977 fn probe_dims(clip: &str) -> Option<(usize, usize)> {
11978 let out = Command::new("ffprobe")
11979 .args(["-v", "error", "-select_streams", "v:0"])
11980 .args(["-show_entries", "stream=width,height", "-of", "csv=p=0"])
11981 .arg(clip)
11982 .output()
11983 .ok()?;
11984 let text = String::from_utf8_lossy(&out.stdout);
11985 let mut f = text.trim().split(',');
11986 Some((f.next()?.trim().parse().ok()?, f.next()?.trim().parse().ok()?))
11987 }
11988
11989 /// The NATIVE-resolution arm of the BD gate (all three clips). The default gate
11990 /// downscales the OBS capture to 640x384, which destroys exactly the
11991 /// pixel-identical 16x16 repeats intrabc and (part of) the palette exist
11992 /// for (class `gate-recipe-confound`), so every screen-tool decision taken
11993 /// on that recipe is taken on content the tool cannot serve. This arm
11994 /// crops -- never scales -- a superblock-aligned window out of the middle
11995 /// of the capture at its own resolution (at most 1920x1024, so the wall
11996 /// stays in the minutes) and runs the same 12-frame, four-quantizer
11997 /// ladder against libaom `cpu-used 6` and rav1e `speed=6`, one tile, one
11998 /// thread, with the same three-way (encoder / ffmpeg / our decoder)
11999 /// sample-exactness assertion `our_ladder` makes.
12000 ///
12001 /// It is its own `--ignored` test so the default gate's wall does not
12002 /// grow. Every variant is an environment knob, and each of those is a
12003 /// `OnceLock` read once per process, so a variant is a separate run:
12004 ///
12005 /// cargo test -p ec-av1 --release --lib -- --ignored \
12006 /// bd_rate_screen_native --nocapture # baseline
12007 /// EC_AV1_INTRABC=1 ... same command # intra block copy
12008 /// EC_AV1_PAL_MAXCOLORS=256 ... same command # palette bound
12009 /// EC_AV1_TILES=1:1 EC_AV1_TILE_THREADS=4 ... # 2x2 tiles
12010 /// EC_AV1_PYRAMID=4:-16:8 ... same command # coding pyramid
12011 ///
12012 /// Under `EC_AV1_PYRAMID` this arm codes its ladder through the streaming
12013 /// facade ([`our_ladder_pyramid`]), which exposes no per-packet
12014 /// reconstruction: that path asserts ffmpeg's decode against our own
12015 /// decoder on all three planes in display order, and prints the per-level
12016 /// frame and byte census.
12017 ///
12018 /// All three gate clips are rows by default. `EC_AV1_NATIVE_FILM=1`,
12019 /// `EC_AV1_NATIVE_FILM4K=1` and `EC_AV1_NATIVE_SCREEN=1` select a subset:
12020 /// setting any one of them keeps only the selected rows.
12021 #[test]
12022 #[ignore = "the native-resolution BD arm: minutes per row, needs ffmpeg"]
12023 fn bd_rate_screen_native() {
12024 if !have_ffmpeg() {
12025 eprintln!("SKIP bd_rate_screen_native: no ffmpeg");
12026 return;
12027 }
12028 let fixtures = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures");
12029 let on = |k: &str| std::env::var(k).ok().as_deref() == Some("1");
12030 let (film, film4k, screen) = (
12031 on("EC_AV1_NATIVE_FILM"),
12032 on("EC_AV1_NATIVE_FILM4K"),
12033 on("EC_AV1_NATIVE_SCREEN"),
12034 );
12035 // No selector at all means every clip; any selector means that subset.
12036 let all = !(film || film4k || screen);
12037 let mut clips: Vec<(String, String)> = Vec::new();
12038 for (want, label, file) in [
12039 (all || film, "film 1080p", "h264-1080p-23.976-8bit.mp4"),
12040 (all || film4k, "film 2160p", "h264-2160p-23.976-8bit.mp4"),
12041 ] {
12042 if !want {
12043 continue;
12044 }
12045 let path = fixtures.join("video").join(file);
12046 match path.exists() {
12047 true => clips.push((label.to_string(), path.to_str().unwrap().to_string())),
12048 false => eprintln!("SKIP {label}: {file} missing"),
12049 }
12050 }
12051 if all || screen {
12052 match std::fs::read_to_string(fixtures.join("real-library-manifest.tsv")) {
12053 Ok(manifest) => match manifest
12054 .lines()
12055 .skip(1)
12056 .filter_map(|l| l.split('\t').next())
12057 .find(|p| p.contains("/OBS/") && p.ends_with(".mkv") && std::path::Path::new(p).exists())
12058 {
12059 Some(p) => clips.push((
12060 format!("screen capture ({})", p.rsplit('/').next().unwrap_or(p)),
12061 p.to_string(),
12062 )),
12063 None => eprintln!("SKIP screen capture: no OBS recording in the manifest exists"),
12064 },
12065 Err(e) => eprintln!("SKIP screen capture: no real-library manifest ({e})"),
12066 }
12067 }
12068 if clips.is_empty() {
12069 eprintln!("SKIP bd_rate_screen_native: no clip");
12070 return;
12071 }
12072
12073 let frames = 12usize;
12074 let aom_points: Vec<Vec<String>> = [5, 20, 35, 45]
12075 .iter()
12076 .map(|q| {
12077 ["-cpu-used", "6", "-b:v", "0", "-crf", &q.to_string()]
12078 .map(String::from)
12079 .to_vec()
12080 })
12081 .collect();
12082 let rav1e_points: Vec<Vec<String>> = [50, 100, 150, 200]
12083 .iter()
12084 .map(|q| {
12085 vec![
12086 "-rav1e-params".to_string(),
12087 format!("speed=6:quantizer={q}:tile_cols=1:tile_rows=1:threads=1"),
12088 ]
12089 })
12090 .collect();
12091 println!(
12092 "\nnative crop, {frames} frames, gop={frames}; tiles {:?}, tile threads {}, \
12093 intrabc {}, palette maxcolors {}",
12094 armed_tiles(),
12095 crate::par::tile_threads(),
12096 intrabc_enabled(),
12097 palette_max_colors(),
12098 );
12099 println!("| clip | ours PSNR/bytes per point | BD-rate vs libaom | BD-rate vs rav1e | wall ours:libaom:rav1e (noisy) |");
12100 println!("|---|---|---|---|---|");
12101 for (name, path) in &clips {
12102 let fctx = &crate::decode::FrameCtx::new();
12103 let Some((nw, nh)) = probe_dims(path) else {
12104 eprintln!("SKIP {name}: ffprobe gave no size");
12105 continue;
12106 };
12107 // A whole number of 128-wide superblocks, at most 1920x1024, out
12108 // of the middle of the frame; the offsets stay even for 4:2:0.
12109 let cw = nw.min(1920) / 128 * 128;
12110 let ch = nh.min(1024) / 128 * 128;
12111 assert!(cw >= 128 && ch >= 128, "{name}: {nw}x{nh} is smaller than a superblock");
12112 let (x, y) = ((nw - cw) / 2 & !1, (nh - ch) / 2 & !1);
12113 let source = clip_frames_vf(
12114 path,
12115 "0",
12116 &format!("crop={cw}:{ch}:{x}:{y}"),
12117 cw,
12118 ch,
12119 frames,
12120 );
12121 SCREEN_FRAMES.iter().for_each(|c| {
12122 c.store(0, std::sync::atomic::Ordering::Relaxed);
12123 });
12124 let _ = crate::tile::take_palette_hits();
12125 let _ = crate::tile::take_palette_uv_hits();
12126 let _ = crate::tile::take_intrabc_hits();
12127 let _ = take_intrabc_search();
12128 let (ours, ours_wall) = match pyramid_from_env() {
12129 None => our_ladder(name, &source, cw, ch, fctx),
12130 Some(pyramid) => {
12131 let (ladder, wall, counts, bytes) =
12132 our_ladder_pyramid(name, &source, cw, ch, pyramid);
12133 eprintln!(
12134 "{name}: pyramid {pyramid:?} -- frames key {} arf {} leaf {} \
12135 show_existing {}; bytes key {} arf {} leaf {} show_existing {}",
12136 counts[0], counts[1], counts[2], counts[3],
12137 bytes[0], bytes[1], bytes[2], bytes[3],
12138 );
12139 (ladder, wall)
12140 }
12141 };
12142 // gate-blind-to-feature: what the screen tools actually did at
12143 // native resolution, over this clip's four encodes.
12144 let screen_on = SCREEN_FRAMES[1].load(std::sync::atomic::Ordering::Relaxed);
12145 let screen_off = SCREEN_FRAMES[0].load(std::sync::atomic::Ordering::Relaxed);
12146 // Which tables the SEARCH priced against, per frame arming
12147 // (`tile::arm_pricing_cdfs`): the default tables or the frame's
12148 // real starting ones. A film clip must show every inter arming on
12149 // the real side, a screen clip none of them.
12150 let (price_default, price_real) = crate::tile::take_pricing_hits();
12151 eprintln!("{name}: pricer armings default={price_default} real={price_real}");
12152 // lane-av1obmc2: the same motion_mode census the 640x384 gate
12153 // prints (class `gate-blind-to-feature`) -- how many blocks coded
12154 // the symbol at each footprint and how many took OBMC. Without it
12155 // the native table, which is the standing keep table, could not
12156 // say whether the tool fired at all.
12157 let mm = crate::tile::take_motion_mode_hits();
12158 eprintln!(
12159 "{name}: motion_mode 32x32 SIMPLE={} OBMC={} WARP={} | 16x16 SIMPLE={} OBMC={} \
12160 WARP={} | 8x8 SIMPLE={} OBMC={} WARP={} ({:.1}% OBMC / {:.1}% WARP of {} \
12161 eligible)",
12162 mm[0], mm[1], mm[2], mm[3], mm[4], mm[5], mm[6], mm[7], mm[8],
12163 100.0 * (mm[1] + mm[4] + mm[7]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
12164 100.0 * (mm[2] + mm[5] + mm[8]) as f64 / mm.iter().sum::<usize>().max(1) as f64,
12165 mm.iter().sum::<usize>(),
12166 );
12167 let palette = crate::tile::take_palette_hits();
12168 let palette_uv = crate::tile::take_palette_uv_hits();
12169 let ibc = crate::tile::take_intrabc_hits();
12170 let search = take_intrabc_search();
12171 eprintln!(
12172 "{name}: screen frames on={screen_on} off={screen_off} ({:.1}% on); \
12173 palette blocks luma {} chroma {}; intrabc blocks {} (searched {} / valid {} / \
12174 won {})",
12175 100.0 * screen_on as f64 / (screen_on + screen_off).max(1) as f64,
12176 palette[0],
12177 palette_uv[0],
12178 ibc[0],
12179 search[0],
12180 search[1],
12181 search[2],
12182 );
12183 let (aom, aom_wall) = external_ladder(&source, cw, ch, "libaom-av1", &aom_points);
12184 let (rav1e, rav1e_wall) = external_ladder(&source, cw, ch, "librav1e", &rav1e_points);
12185 assert_monotone(&format!("{name}: ours"), &ours);
12186 assert_monotone(&format!("{name}: libaom"), &aom);
12187 assert_monotone(&format!("{name}: rav1e"), &rav1e);
12188 let points = ours
12189 .iter()
12190 .map(|(p, b)| format!("{p:.2} dB/{:.0} B", 10f64.powf(*b)))
12191 .collect::<Vec<_>>()
12192 .join(", ");
12193 println!(
12194 "| {name} {cw}x{ch} | {points} | {:+.1}% | {:+.1}% | {ours_wall:.1}s:{aom_wall:.1}s:{rav1e_wall:.1}s |",
12195 bd_rate(&aom, &ours) * 100.0,
12196 bd_rate(&rav1e, &ours) * 100.0,
12197 );
12198 }
12199 }
12200}