forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcd61dc0Tahinli3 months ago728 commits

encode.rs4895 lines, 199.5 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 is predicted
9//! DC, which is the mode the tile writer codes for it. Block sizes and
10//! transform types are what a loop above this would choose between.
11//!
12//! The encoder carries its own reconstruction, because prediction reads it: a
13//! block predicts from the reconstructed samples above and to its left, exactly
14//! as the decoder will. That makes the reconstruction a claim about what a
15//! decoder produces, and it is gated as one — sample for sample against ffmpeg.
16
17use ec_av1_syntax::sequence::{ColorConfig, OperatingPoint, SequenceHeader};
18use ec_av1_syntax::{
19 ChromaSamplePosition, FrameHeader, FrameType, PRIMARY_REF_NONE, QuantizationParams, TileInfo,
20 TxMode,
21};
22use ec_core::{Error, Result};
23
24use crate::cdf;
25use crate::cdf_state::TxbSet;
26use crate::frame::frame_obu;
27use crate::intra::{D67_PRED, DC_PRED, KEY_FRAME_MODES, V_PRED};
28use crate::mc;
29use crate::motion;
30use crate::mvstack::{MiGrid, MiInfo, MvStack, find_mv_stack};
31use crate::obu::temporal_delimiter;
32use crate::quant::ac_q;
33use crate::sequence::sequence_header_obu;
34use crate::tile::{
35 BlockCoeffs, Coeff, INTRA_MODE_CTX, InterInfo, InterMode, Quadrant, Superblock, partition_bits,
36 sb_coeff_inter_frame_tile, sb_coeff_key_frame_tile,
37};
38use crate::transform::{dequant_and_inverse, forward_and_quantize};
39
40/// The side of the larger of the two luma blocks this encoder codes, in
41/// samples.
42const BLOCK: usize = 32;
43
44/// The side of the smaller one, which a 32x32 block may be split into four of.
45const SUB: usize = 16;
46
47/// The side of a superblock, which is what the partition tree starts from.
48pub(crate) const SUPERBLOCK: usize = 64;
49
50/// How heavily the mode search weighs rate against squared error, in units of
51/// the quantizer's reconstruction step squared per bit.
52///
53/// Swept three times over his clips and three synthetic pictures
54/// (`probe_lambda`, `probe_directional` and `probe_ladder`, and the tables in
55/// the three lane reports). The first sweep, before the mode symbol was
56/// costed, put the best point at 0.05; costing it moved the point to 0.1. The
57/// third sweep, after the levels were costed through the writer's own CDFs
58/// too, left it there: against 0.2 the ladders are worth -1.19% against -0.98%
59/// on film and -0.20% against -0.14% on screen capture.
60const LAMBDA_SCALE: f64 = 0.1;
61
62/// [`LAMBDA_SCALE`], or whatever `EC_AV1_LAMBDA` names when the sweep that
63/// picks it is the thing running. A release build has no such knob.
64fn lambda_scale() -> f64 {
65 let swept = std::env::var("EC_AV1_LAMBDA")
66 .ok()
67 .and_then(|v| v.parse::<f64>().ok());
68 match swept {
69 Some(scale) if cfg!(test) => scale,
70 _ => LAMBDA_SCALE,
71 }
72}
73
74/// Whether a 32x32 block may be split into four 16x16 ones when the trial says
75/// four cost less. Set from the measurement in the lane report.
76const SPLIT_BLOCKS: bool = true;
77
78/// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
79/// by calling [`encode_key_frame_inner`] both ways.
80pub(crate) fn split_blocks() -> bool {
81 SPLIT_BLOCKS
82}
83
84/// One 8-bit planar 4:2:0 picture.
85#[derive(Clone, Debug, PartialEq, Eq)]
86pub struct Picture {
87 /// The picture's width in luma samples.
88 pub width: usize,
89 /// Its height in luma samples.
90 pub height: usize,
91 /// The luma plane, `width * height` samples in raster order.
92 pub y: Vec<u8>,
93 /// The U plane, at half the width and half the height.
94 pub u: Vec<u8>,
95 /// The V plane, the same shape as U.
96 pub v: Vec<u8>,
97}
98
99impl Picture {
100 /// A mid-grey picture of the given size.
101 #[must_use]
102 pub fn grey(width: usize, height: usize) -> Self {
103 Self {
104 width,
105 height,
106 y: vec![128; width * height],
107 u: vec![128; width * height / 4],
108 v: vec![128; width * height / 4],
109 }
110 }
111
112 pub(crate) fn check(&self) -> Result<()> {
113 if self.width == 0
114 || !self.width.is_multiple_of(BLOCK)
115 || !self.height.is_multiple_of(BLOCK)
116 || !self.height.is_multiple_of(BLOCK)
117 {
118 return Err(Error::unsupported(
119 "AV1 encode",
120 "the picture must be a whole number of 32x32 blocks in each direction",
121 ));
122 }
123 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
124 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
125 return Err(Error::unsupported(
126 "AV1 encode",
127 "each plane must carry one sample per position at 4:2:0",
128 ));
129 }
130 Ok(())
131 }
132
133 /// What the public entry points require of the picture they are handed,
134 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
135 /// needs a whole chroma sample per two luma ones) and one sample per
136 /// position on each plane.
137 pub(crate) fn check_even(&self) -> Result<()> {
138 if self.width == 0
139 || self.height == 0
140 || !self.width.is_multiple_of(2)
141 || !self.height.is_multiple_of(2)
142 {
143 return Err(Error::unsupported(
144 "AV1 encode",
145 "the picture's width and height must each be even and nonzero",
146 ));
147 }
148 let (luma, chroma) = (self.width * self.height, self.width * self.height / 4);
149 if self.y.len() != luma || self.u.len() != chroma || self.v.len() != chroma {
150 return Err(Error::unsupported(
151 "AV1 encode",
152 "each plane must carry one sample per position at 4:2:0",
153 ));
154 }
155 Ok(())
156 }
157
158 /// This picture, padded by edge replication to the next whole number of
159 /// `align`-sample blocks in each direction — [`BLOCK`] for a lone key
160 /// frame (the block coder's own requirement), [`SUPERBLOCK`] for a
161 /// sequence (what the inter tile writer's partition needs on top of
162 /// that). Identity (a plain clone, not a copy through the replication
163 /// loop) when the picture is already that size — the multiple-of-32 (or
164 /// -64) fast path is unchanged.
165 pub(crate) fn padded_to(&self, align: usize) -> Picture {
166 let padded_width = self.width.next_multiple_of(align);
167 let padded_height = self.height.next_multiple_of(align);
168 if padded_width == self.width && padded_height == self.height {
169 return self.clone();
170 }
171 Picture {
172 width: padded_width,
173 height: padded_height,
174 y: pad_plane(
175 &self.y,
176 self.width,
177 self.height,
178 padded_width,
179 padded_height,
180 ),
181 u: pad_plane(
182 &self.u,
183 self.width / 2,
184 self.height / 2,
185 padded_width / 2,
186 padded_height / 2,
187 ),
188 v: pad_plane(
189 &self.v,
190 self.width / 2,
191 self.height / 2,
192 padded_width / 2,
193 padded_height / 2,
194 ),
195 }
196 }
197}
198
199/// Pads one plane to `(padded_width, padded_height)` by repeating its last
200/// row and column, so the block coder always sees a whole number of blocks.
201/// [`crop_plane`] undoes this on the way back out.
202fn pad_plane(
203 source: &[u8],
204 width: usize,
205 height: usize,
206 padded_width: usize,
207 padded_height: usize,
208) -> Vec<u8> {
209 let mut out = vec![0u8; padded_width * padded_height];
210 for row in 0..padded_height {
211 let src = source[row.min(height - 1) * width..][..width].as_ref();
212 let dst = &mut out[row * padded_width..][..padded_width];
213 dst[..width].copy_from_slice(src);
214 dst[width..].fill(src[width - 1]);
215 }
216 out
217}
218
219/// The top-left `width` x `height` region of a plane that is `padded_width`
220/// wide, which is the render-size crop [`Picture::padded`]'s replication
221/// exists to let a decoder undo.
222fn crop_plane(source: &[u8], padded_width: usize, width: usize, height: usize) -> Vec<u8> {
223 let mut out = Vec::with_capacity(width * height);
224 for row in 0..height {
225 out.extend_from_slice(&source[row * padded_width..][..width]);
226 }
227 out
228}
229
230/// [`Encoded::reconstruction`] cropped to `(width, height)`: the render-size
231/// region a decoder produces, which is the public contract for what a caller
232/// sees back — the padded planes the encoder coded against never leave this
233/// module. Identity when the reconstruction is already that size.
234pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
235 let reconstruction = &encoded.reconstruction;
236 let cropped = if reconstruction.width == width && reconstruction.height == height {
237 reconstruction.clone()
238 } else {
239 Picture {
240 width,
241 height,
242 y: crop_plane(&reconstruction.y, reconstruction.width, width, height),
243 u: crop_plane(
244 &reconstruction.u,
245 reconstruction.width / 2,
246 width / 2,
247 height / 2,
248 ),
249 v: crop_plane(
250 &reconstruction.v,
251 reconstruction.width / 2,
252 width / 2,
253 height / 2,
254 ),
255 }
256 };
257 Encoded {
258 stream: encoded.stream.clone(),
259 modes: encoded.modes.clone(),
260 inter_block_share: encoded.inter_block_share,
261 reconstruction: cropped,
262 tile: encoded.tile.clone(),
263 mi_cols: encoded.mi_cols,
264 mi_rows: encoded.mi_rows,
265 base_q_idx: encoded.base_q_idx,
266 }
267}
268
269/// What one call to [`encode_key_frame`] produced.
270#[derive(Clone, Debug)]
271pub struct Encoded {
272 /// The AV1 stream: a temporal delimiter, a sequence header OBU and a frame
273 /// OBU carrying one tile.
274 pub stream: Vec<u8>,
275 /// What a decoder will produce from `stream` — the encoder's own
276 /// reconstruction, which its prediction was built on.
277 pub reconstruction: Picture,
278 /// The luma intra mode each block was coded under, in the order the blocks
279 /// are coded — raster order among the quadrants of each superblock, and
280 /// among the four 16x16 blocks of a quadrant that was split.
281 pub modes: Vec<u8>,
282 /// The fraction of this frame's 32x32 blocks that were coded inter (any
283 /// of `NEARESTMV` skipped, `NEARESTMV` coded, or `NEWMV`). Always `0.0`
284 /// for a key frame, which has no such choice — so a caller can tell a
285 /// frame with no motion worth coding from one that never got the chance.
286 pub inter_block_share: f64,
287 /// The tile payload alone, undecorated by any OBU framing, and the frame
288 /// header fields a decoder of it needs: `mi_cols`/`mi_rows`/`base_q_idx`.
289 /// `crate::decode`'s tests are the only reader; a real decoder gets these
290 /// off the wire by parsing `stream`'s OBUs instead.
291 pub(crate) tile: Vec<u8>,
292 pub(crate) mi_cols: u32,
293 pub(crate) mi_rows: u32,
294 pub(crate) base_q_idx: u8,
295}
296
297/// The sequence and frame headers a picture of this size is coded under: one
298/// tile, one transform size per block, no in-loop filtering, no CDF adaptation
299/// and no tool the tile writer does not code.
300///
301/// # Errors
302/// Returns an error when the picture is larger than the 16-bit frame size the
303/// sequence header carries.
304pub fn key_frame_headers(
305 width: usize,
306 height: usize,
307 base_q_idx: u8,
308) -> Result<(SequenceHeader, FrameHeader)> {
309 key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
310}
311
312/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
313/// studio (limited) range: what this crate's sequence header carried before
314/// [`crate::encoder`]'s facade could configure it, and what
315/// [`key_frame_headers`] still asks for.
316fn unspecified_color_config() -> ColorConfig {
317 ColorConfig {
318 bit_depth: 8,
319 mono_chrome: false,
320 num_planes: 3,
321 color_primaries: 2,
322 transfer_characteristics: 2,
323 matrix_coefficients: 2,
324 color_range: false,
325 subsampling_x: 1,
326 subsampling_y: 1,
327 chroma_sample_position: ChromaSamplePosition::Unknown,
328 separate_uv_delta_q: false,
329 }
330}
331
332/// [`key_frame_headers`] with the sequence header's colour config named
333/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
334/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
335/// which is all a player picks a colour transform from and which
336/// [`crate::encoder::Colour`] is the facade's own name for.
337///
338/// # Errors
339/// The same as [`key_frame_headers`].
340pub(crate) fn key_frame_headers_colour(
341 width: usize,
342 height: usize,
343 base_q_idx: u8,
344 color_config: ColorConfig,
345) -> Result<(SequenceHeader, FrameHeader)> {
346 let bits = |n: usize| -> Result<u32> {
347 let n = u32::try_from(n).map_err(|_| too_large())?;
348 if n == 0 || n > 1 << 16 {
349 return Err(too_large());
350 }
351 Ok((32 - (n - 1).leading_zeros()).max(1))
352 };
353 let (frame_width_bits, frame_height_bits) = (bits(width)?, bits(height)?);
354 let (w, h) = (width as u32, height as u32);
355 let seq = SequenceHeader {
356 seq_profile: 0,
357 operating_points: vec![OperatingPoint {
358 seq_level_idx: 8,
359 ..OperatingPoint::default()
360 }],
361 frame_width_bits,
362 frame_height_bits,
363 max_frame_width: w,
364 max_frame_height: h,
365 use_128x128_superblock: false,
366 enable_filter_intra: false,
367 enable_intra_edge_filter: false,
368 enable_order_hint: true,
369 order_hint_bits: 7,
370 enable_superres: false,
371 enable_cdef: false,
372 enable_restoration: false,
373 seq_force_screen_content_tools: 0,
374 seq_force_integer_mv: 0,
375 color_config,
376 still_picture: false,
377 reduced_still_picture_header: false,
378 timing_info: None,
379 decoder_model_info: None,
380 initial_display_delay_present_flag: false,
381 operating_point: 0,
382 operating_point_idc: 0,
383 frame_id_numbers_present_flag: false,
384 delta_frame_id_length: 0,
385 additional_frame_id_length: 0,
386 enable_interintra_compound: false,
387 enable_masked_compound: false,
388 enable_warped_motion: false,
389 enable_dual_filter: false,
390 enable_jnt_comp: false,
391 enable_ref_frame_mvs: false,
392 film_grain_params_present: false,
393 };
394 // spec `compute_image_size` (5.9.15): MiCols/MiRows come from the frame's
395 // own (true, unpadded) width and height, not from any block-grid
396 // alignment — a decoder derives these straight from `frame_width`/
397 // `frame_height` below, so this must match it exactly.
398 let (mi_cols, mi_rows) = (2 * ((w + 7) >> 3), 2 * ((h + 7) >> 3));
399 let header = FrameHeader {
400 frame_type: FrameType::Key,
401 frame_is_intra: true,
402 show_frame: true,
403 error_resilient_mode: true,
404 // The tile writer keeps the same CDF state the decoder does and
405 // updates it in the same order, so the frame lets the decoder adapt.
406 disable_cdf_update: false,
407 // Nothing reads the state this frame leaves behind: a key frame always
408 // starts from the defaults, and this encoder emits one frame.
409 disable_frame_end_update_cdf: true,
410 force_integer_mv: true,
411 refresh_frame_flags: 0xFF,
412 primary_ref_frame: PRIMARY_REF_NONE,
413 frame_width: w,
414 frame_height: h,
415 upscaled_width: w,
416 render_width: w,
417 render_height: h,
418 mi_cols,
419 mi_rows,
420 tile_info: TileInfo {
421 uniform_spacing: true,
422 cols: 1,
423 rows: 1,
424 mi_col_starts: vec![0, mi_cols],
425 mi_row_starts: vec![0, mi_rows],
426 tile_size_bytes: 1,
427 ..TileInfo::default()
428 },
429 quantization: QuantizationParams {
430 base_q_idx,
431 ..QuantizationParams::default()
432 },
433 tx_mode: TxMode::Largest,
434 // Forces `get_tx_set` (spec 5.11.48) to `TX_SET_INTRA_2` for every
435 // intra transform below 32x32, not only 16x16 -- the set this crate
436 // carries a table for at 8x8/16x16 (`INTRA_TX_TYPE_SET2_8`/`_16`).
437 // This bit is part of the bitstream (spec 5.9.2's `reduced_tx_set`),
438 // so a decoder honouring the header picks the same CDF the writer
439 // used only if this is set here too, not only on the inter variant
440 // below -- an r14 lane-av1-rect fix: a key frame's own header used to
441 // default this to `false`, so `av1_get_ext_tx_set_type` picked the
442 // 7-symbol `TX_SET_INTRA_1` table on the decoder side while the
443 // writer coded against the 5-symbol `TX_SET_INTRA_2` one, diverging
444 // the arithmetic coder's `rng` register from the very first 8x8-leaf
445 // luma transform onward with no symbol value ever differing.
446 reduced_tx_set: true,
447 ..FrameHeader::default()
448 };
449 Ok((seq, header))
450}
451
452/// The frame header for a shown inter frame that predicts from the single
453/// slot `last_slot` (every `ref_frame_idx` entry names it) and refreshes that
454/// same slot with itself once coded. The sequence header is [`key_frame_headers`]'s,
455/// reused verbatim: an inter frame never changes the sequence.
456///
457/// # Errors
458/// Returns an error under the same conditions as [`key_frame_headers`].
459pub fn inter_frame_headers(
460 width: usize,
461 height: usize,
462 base_q_idx: u8,
463 order_hint: u32,
464 last_slot: u8,
465) -> Result<(SequenceHeader, FrameHeader)> {
466 let (seq, key) = key_frame_headers(width, height, base_q_idx)?;
467 let header = FrameHeader {
468 frame_type: FrameType::Inter,
469 frame_is_intra: false,
470 show_frame: true,
471 error_resilient_mode: false,
472 disable_cdf_update: false,
473 disable_frame_end_update_cdf: true,
474 force_integer_mv: false,
475 order_hint,
476 primary_ref_frame: 0,
477 refresh_frame_flags: 1 << last_slot,
478 ref_frame_idx: [last_slot; ec_av1_syntax::REFS_PER_FRAME],
479 allow_high_precision_mv: false,
480 interpolation_filter: ec_av1_syntax::InterpolationFilter::Eighttap,
481 is_motion_mode_switchable: false,
482 use_ref_frame_mvs: false,
483 // Forces `get_tx_set` (spec 5.11.48) to the two-symbol
484 // `TX_SET_INTER_3` for every inter transform below 32x32 -- the only
485 // set this crate carries a table for at 16x16 (see
486 // `crate::cdf::INTER_TX_TYPE_SET3_16`'s doc comment). A 32x32 inter
487 // transform is unaffected (its `txSzSqrUp == TX_32X32` branch already
488 // reads `TX_SET_INTER_3` regardless of this flag). An intra transform
489 // IS affected below 16x16 too, not only at 16x16 (r11 lane-av1-rect:
490 // the earlier claim here was wrong and desynced the 8x8-leaf straddle
491 // path) -- with this flag set, `get_tx_set`'s intra branch returns
492 // `TX_SET_INTRA_2` at every size up to 16x16, so `TX_8X8` reads
493 // [`crate::cdf::INTRA_TX_TYPE_SET2_8`], not `SET1_8`.
494 reduced_tx_set: true,
495 ..key
496 };
497 Ok((seq, header))
498}
499
500fn too_large() -> Error {
501 Error::unsupported(
502 "AV1 encode",
503 "the picture is larger than a frame size can carry",
504 )
505}
506
507/// One plane of the picture being coded, and the reconstruction being built
508/// beside it.
509struct Plane<'a> {
510 source: &'a [u8],
511 reconstruction: Vec<u8>,
512 width: usize,
513 height: usize,
514 /// The frame's true, decodable extent in this plane's own units --
515 /// `mi_cols`/`mi_rows` (spec `compute_image_size`) converted to samples,
516 /// not `width`/`height` above, which is the padded coding-surface size.
517 /// A decoder's `BlockDecoded` bookkeeping (spec 7.4) and its `mb_to_
518 /// right_edge`/`mb_to_bottom_edge` clamps (libaom's
519 /// `av1/common/reconintra.c` `build_intra_predictors`) never see past
520 /// this bound, even though the padded reconstruction buffer holds real
521 /// (if never-decoded-by-a-real-decoder) samples out there -- reading
522 /// those instead of stopping here is what desyncs prediction at the true
523 /// edge.
524 true_width: usize,
525 true_height: usize,
526}
527
528impl Plane<'_> {
529 /// The reconstructed samples a block at `(x, y)` predicts from: the row
530 /// above it, the column to its left and the sample between them, each
531 /// missing where the block sits against an edge of the frame.
532 ///
533 /// `reach` says whether the samples above the block's right and below its
534 /// left are decoded, which is what a directional mode reads into; where
535 /// they are not, or where the frame ends first, the edge is shorter and
536 /// the predictor repeats its last sample, exactly as the decoder's clamp
537 /// to `aboveLimit` and `leftLimit` does (spec 7.11.2.2).
538 fn edges(
539 &self,
540 x: usize,
541 y: usize,
542 side: usize,
543 reach: Reach,
544 ) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<u8>) {
545 // Even a block's *own* edge is clamped to the true frame bound, not
546 // just a `reach` extension: libaom's `av1_predict_intra_block`
547 // (`av1/common/reconintra.c`) derives `xr`/`yd` -- the distance from
548 // this block's own right/bottom to the frame edge -- from
549 // `mb_to_right_edge`/`mb_to_bottom_edge`, which are built from
550 // `mi_cols`/`mi_rows` (the true, decodable extent), never from any
551 // padded coding surface. `n_top_px`/`n_left_px` (how many *real*
552 // samples the row/column above/left holds before the decoder starts
553 // repeating the last one, same clamp as spec 7.11.2.2's `aboveLimit`/
554 // `leftLimit`) is `min(side, xr + side)` even for a block whose own
555 // extent straddles that edge legally (`has_half`) -- the transform
556 // still covers the whole block, but prediction does not get to read
557 // real reconstructed pixels past the true edge for its own row/column,
558 // only for the padded tail it invents.
559 let own_across = x + side.min(self.true_width.saturating_sub(x));
560 let across = if reach.above_right {
561 own_across + side.min(self.true_width.saturating_sub(own_across))
562 } else {
563 own_across
564 }
565 .min(self.width);
566 let own_down = y + side.min(self.true_height.saturating_sub(y));
567 let down = if reach.below_left {
568 own_down + side.min(self.true_height.saturating_sub(own_down))
569 } else {
570 own_down
571 }
572 .min(self.height);
573 // `across`/`down` can still fall at or below `x`/`y` for a sub-block
574 // whose own origin already sits past the true edge -- only reachable
575 // through a partition trial priced for comparison on a split this
576 // frame's straddling quadrant will go on to refuse (see
577 // `a_picture_off_the_block_grid_is_refused`), never through a block
578 // this encoder actually commits. Such a block has no true-edge
579 // samples above or left of it at all, same as `y == 0`/`x == 0`.
580 let above = (y > 0 && across > x)
581 .then(|| self.reconstruction[(y - 1) * self.width + x..][..across - x].to_vec());
582 let left = (x > 0 && down > y).then(|| {
583 (y..down)
584 .map(|row| self.reconstruction[row * self.width + x - 1])
585 .collect::<Vec<_>>()
586 });
587 let corner = (x > 0 && y > 0).then(|| self.reconstruction[(y - 1) * self.width + x - 1]);
588 (above, left, corner)
589 }
590
591 /// Codes one block under one mode without committing it: hands back the
592 /// levels, the block the decoder would reconstruct, the squared error
593 /// against the source and an estimate of what the levels cost in bits.
594 fn trial(&self, at: At, mode: u8, base_q_idx: u8, deadzone: f64) -> Trial {
595 let At {
596 x, y, side, reach, ..
597 } = at;
598 let (above, left, corner) = self.edges(x, y, side, reach);
599 let mut prediction = vec![0u8; side * side];
600 crate::intra::predict(
601 mode,
602 above.as_deref(),
603 left.as_deref(),
604 corner,
605 side,
606 &mut prediction,
607 );
608
609 let mut residual = vec![0i32; side * side];
610 for row in 0..side {
611 for col in 0..side {
612 residual[row * side + col] =
613 i32::from(self.source[(y + row) * self.width + x + col])
614 - i32::from(prediction[row * side + col]);
615 }
616 }
617 #[cfg(test)]
618 let t = std::time::Instant::now();
619 let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone);
620 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
621 #[cfg(test)]
622 stage_add(2, t.elapsed());
623
624 let mut reconstruction = vec![0u8; side * side];
625 let mut sse = 0.0;
626 for row in 0..side {
627 for col in 0..side {
628 let i = row * side + col;
629 let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;
630 reconstruction[i] = sample;
631 let error = f64::from(
632 i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample),
633 );
634 sse += error * error;
635 }
636 }
637 // What the levels cost is priced through the same CDFs the tile writer
638 // will code them with, so the search ranks modes -- and the partition
639 // trial ranks trees -- by the bits they actually spend.
640 #[cfg(test)]
641 let t = std::time::Instant::now();
642 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
643 // What the search used before it could price a block exactly: a
644 // level costs its magnitude's width plus a sign and a run. Kept
645 // reachable from the sweep so the two rate terms can be compared
646 // on one build.
647 levels
648 .iter()
649 .filter(|&&level| level != 0)
650 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
651 .sum()
652 } else {
653 crate::tile::coeff_bits(&levels, at.set)
654 };
655 #[cfg(test)]
656 stage_add(3, t.elapsed());
657 Trial {
658 levels,
659 reconstruction,
660 sse,
661 bits,
662 }
663 }
664
665 /// [`Self::trial`] with the prediction already built, so that an inter
666 /// block's motion-compensated prediction can go through the same
667 /// residual/quantize/reconstruct path an intra block's does. `skip`
668 /// takes the prediction as the reconstruction outright, coding no
669 /// residual at all — what a `NEARESTMV` block that names no coefficients
670 /// codes.
671 #[allow(clippy::too_many_arguments)]
672 fn code_from_prediction(
673 &self,
674 x: usize,
675 y: usize,
676 side: usize,
677 prediction: &[u8],
678 skip: bool,
679 base_q_idx: u8,
680 deadzone: f64,
681 set: TxbSet,
682 ) -> Trial {
683 if skip {
684 let mut sse = 0.0;
685 for row in 0..side {
686 for col in 0..side {
687 let error = f64::from(
688 i32::from(self.source[(y + row) * self.width + x + col])
689 - i32::from(prediction[row * side + col]),
690 );
691 sse += error * error;
692 }
693 }
694 return Trial {
695 levels: vec![0i32; side * side],
696 reconstruction: prediction.to_vec(),
697 sse,
698 bits: 0.0,
699 };
700 }
701 let mut residual = vec![0i32; side * side];
702 for row in 0..side {
703 for col in 0..side {
704 residual[row * side + col] =
705 i32::from(self.source[(y + row) * self.width + x + col])
706 - i32::from(prediction[row * side + col]);
707 }
708 }
709 #[cfg(test)]
710 let t = std::time::Instant::now();
711 let levels = forward_and_quantize(&residual, side, 8, i32::from(base_q_idx), deadzone);
712 let coded = dequant_and_inverse(&levels, side, 8, i32::from(base_q_idx));
713 #[cfg(test)]
714 stage_add(2, t.elapsed());
715 let mut reconstruction = vec![0u8; side * side];
716 let mut sse = 0.0;
717 for row in 0..side {
718 for col in 0..side {
719 let i = row * side + col;
720 let sample = (i32::from(prediction[i]) + coded[i]).clamp(0, 255) as u8;
721 reconstruction[i] = sample;
722 let error = f64::from(
723 i32::from(self.source[(y + row) * self.width + x + col]) - i32::from(sample),
724 );
725 sse += error * error;
726 }
727 }
728 #[cfg(test)]
729 let t = std::time::Instant::now();
730 let bits = if cfg!(test) && std::env::var_os("EC_AV1_ESTIMATE").is_some() {
731 levels
732 .iter()
733 .filter(|&&level| level != 0)
734 .map(|&level| 2.0 + 2.0 * f64::from(level.unsigned_abs() + 1).log2())
735 .sum()
736 } else {
737 crate::tile::coeff_bits(&levels, set)
738 };
739 #[cfg(test)]
740 stage_add(3, t.elapsed());
741 Trial {
742 levels,
743 reconstruction,
744 sse,
745 bits,
746 }
747 }
748
749 /// Writes a trial's reconstruction back into the plane.
750 fn commit(&mut self, x: usize, y: usize, side: usize, trial: &Trial) {
751 for row in 0..side {
752 self.reconstruction[(y + row) * self.width + x..][..side]
753 .copy_from_slice(&trial.reconstruction[row * side..][..side]);
754 }
755 }
756
757 /// Codes one block under a fixed mode, committing it, and hands back what
758 /// it cost: its squared error and the bits its levels spend.
759 fn code_block(
760 &mut self,
761 at: At,
762 mode: u8,
763 base_q_idx: u8,
764 deadzone: f64,
765 ) -> (Vec<Coeff>, f64, f64) {
766 let trial = self.trial(at, mode, base_q_idx, deadzone);
767 self.commit(at.x, at.y, at.side, &trial);
768 (coeffs(&trial.levels, at.side), trial.sse, trial.bits)
769 }
770
771 /// The source samples of one square, contiguous — what a motion search
772 /// compares its candidates' predictions against ([`motion::search`]'s
773 /// `source`), since [`Self::source`] itself is the whole plane, strided
774 /// by [`Self::width`].
775 fn source_block(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
776 (y..y + side)
777 .flat_map(|row| self.source[row * self.width + x..][..side].to_vec())
778 .collect()
779 }
780
781 /// The reconstructed samples of one square, so that a partition trial can
782 /// be undone.
783 fn snapshot(&self, x: usize, y: usize, side: usize) -> Vec<u8> {
784 (y..y + side)
785 .flat_map(|row| self.reconstruction[row * self.width + x..][..side].to_vec())
786 .collect()
787 }
788
789 /// Puts a snapshot back.
790 fn restore(&mut self, x: usize, y: usize, side: usize, samples: &[u8]) {
791 for row in 0..side {
792 self.reconstruction[(y + row) * self.width + x..][..side]
793 .copy_from_slice(&samples[row * side..][..side]);
794 }
795 }
796
797 /// The SAD-plus-mode-cost score [`Self::search_block`] ranks candidates
798 /// by, exposed so [`search_inter_block`]'s intra-candidate loop can
799 /// prescreen by the identical rule rather than a second one that could
800 /// drift from it.
801 fn intra_scores(
802 &self,
803 at: At,
804 modes: &[u8],
805 mode_bits: &[f64; 13],
806 lambda: f64,
807 ) -> Vec<(f64, u8)> {
808 let At {
809 x, y, side, reach, ..
810 } = at;
811 let (above, left, corner) = self.edges(x, y, side, reach);
812 modes
813 .iter()
814 .map(|&mode| {
815 let mut prediction = vec![0u8; side * side];
816 crate::intra::predict(
817 mode,
818 above.as_deref(),
819 left.as_deref(),
820 corner,
821 side,
822 &mut prediction,
823 );
824 let sad: f64 = (0..side * side)
825 .map(|i| {
826 let (row, col) = (i / side, i % side);
827 f64::from(
828 (i32::from(self.source[(y + row) * self.width + x + col])
829 - i32::from(prediction[i]))
830 .abs(),
831 )
832 })
833 .sum();
834 (sad + lambda * mode_bits[usize::from(mode)], mode)
835 })
836 .collect()
837 }
838
839 /// Codes one block under every mode the search offers (or, when
840 /// [`Search::top_k`] prunes it, the cheapest `top_k` of them by a SAD
841 /// pre-pass plus DC) and commits the one whose squared error and
842 /// estimated rate come out cheapest.
843 ///
844 /// The prediction is built once per mode regardless -- the full RD trial
845 /// needs it too -- so ranking modes by SAD on that same prediction before
846 /// running the expensive part (forward transform, quantize, reconstruct,
847 /// `coeff_bits`) on only the survivors costs nothing extra to predict,
848 /// only to sum.
849 fn search_block(
850 &mut self,
851 at: At,
852 search: &Search,
853 mode_bits: &[f64; 13],
854 ) -> (Vec<Coeff>, u8, f64) {
855 let At {
856 x, y, side, reach, ..
857 } = at;
858 let (above, left, corner) = self.edges(x, y, side, reach);
859 let mut scored: Vec<(f64, u8, Vec<u8>)> = search
860 .modes
861 .iter()
862 .map(|&mode| {
863 let mut prediction = vec![0u8; side * side];
864 crate::intra::predict(
865 mode,
866 above.as_deref(),
867 left.as_deref(),
868 corner,
869 side,
870 &mut prediction,
871 );
872 let sad: f64 = (0..side * side)
873 .map(|i| {
874 let (row, col) = (i / side, i % side);
875 f64::from(
876 (i32::from(self.source[(y + row) * self.width + x + col])
877 - i32::from(prediction[i]))
878 .abs(),
879 )
880 })
881 .sum();
882 (
883 sad + search.lambda * mode_bits[usize::from(mode)],
884 mode,
885 prediction,
886 )
887 })
888 .collect();
889 if let Some(k) = search.top_k {
890 if k < scored.len() {
891 let dc_pos = scored.iter().position(|&(_, mode, _)| mode == DC_PRED);
892 let dc_entry = dc_pos.map(|i| scored.remove(i));
893 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
894 scored.truncate(if dc_entry.is_some() {
895 k.saturating_sub(1)
896 } else {
897 k
898 });
899 if let Some(dc_entry) = dc_entry {
900 scored.push(dc_entry);
901 }
902 }
903 }
904 let mut best: Option<(f64, u8, Trial)> = None;
905 for (_, mode, prediction) in scored {
906 let trial = self.code_from_prediction(
907 x,
908 y,
909 side,
910 &prediction,
911 false,
912 search.base_q_idx,
913 search.deadzone,
914 at.set,
915 );
916 let cost = trial.sse + search.lambda * (trial.bits + mode_bits[usize::from(mode)]);
917 if best
918 .as_ref()
919 .is_none_or(|(best_cost, _, _)| cost < *best_cost)
920 {
921 best = Some((cost, mode, trial));
922 }
923 }
924 let (cost, mode, trial) = best.expect("the search offers at least one mode");
925 self.commit(x, y, side, &trial);
926 (coeffs(&trial.levels, side), mode, cost)
927 }
928}
929
930/// Where one block sits in its plane, and how far past its own edges its
931/// prediction may read.
932#[derive(Clone, Copy)]
933struct At {
934 x: usize,
935 y: usize,
936 side: usize,
937 reach: Reach,
938 /// Which of the tile writer's coefficient tables this block's levels are
939 /// coded with, and so which the search prices them through.
940 set: TxbSet,
941}
942
943/// Which of the samples past a block's own edges the decoder has decoded by
944/// the time it predicts the block, and so which a directional mode may read.
945///
946/// The decoder derives these from its `BlockDecoded` flags, which are cleared
947/// per superblock (`clear_block_decoded_flags`, spec 7.4). Rather than carry
948/// that map, this reads the answer the same way libaom and rav1e do: for a
949/// block whose transform covers it whole, whether the samples above its right
950/// (or below its left) are decoded depends only on where the block sits inside
951/// its 64x64 superblock, which is a pinned table per block size.
952#[derive(Clone, Copy)]
953pub(crate) struct Reach {
954 pub(crate) above_right: bool,
955 pub(crate) below_left: bool,
956}
957
958/// `has_tr_16x16` / `has_tr_32x32` (`recon_intra.rs` in rav1e, `has_tr_*` in
959/// libaom): for a block that is neither in the superblock's top row nor its
960/// rightmost column, whether the block above and to its right is coded before
961/// it. Indexed by the block's position in the superblock, in blocks of its own
962/// size, as `row * (128 / side) + col` (`Reach::table_stride`) -- libaom's
963/// 128, not this crate's 64 superblock -- bit by bit from the low end.
964const HAS_TOP_RIGHT: [&[u8]; 3] = [
965 &[255, 85, 119, 85, 127, 85, 119, 85],
966 &[95, 87],
967 // has_tr_8x8 (libaom av1/common/reconintra.c) -- table_stride(8) == 16
968 // (128 / 8), so this row is 16 wide by 16 rows, 32 bytes.
969 &[
970 255, 255, 85, 85, 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85, 255, 127, 85, 85,
971 119, 119, 85, 85, 127, 127, 85, 85, 119, 119, 85, 85,
972 ],
973];
974
975/// `has_bl_16x16` / `has_bl_32x32`: the same, for the block below and to the
976/// left.
977const HAS_BOTTOM_LEFT: [&[u8]; 3] = [
978 &[84, 16, 84, 0, 84, 16, 84, 0],
979 &[4, 4],
980 // has_bl_8x8 (libaom av1/common/reconintra.c)
981 &[
982 84, 85, 16, 17, 84, 85, 0, 1, 84, 85, 16, 17, 84, 85, 0, 0, 84, 85, 16, 17, 84, 85, 0, 1,
983 84, 85, 16, 17, 84, 85, 0, 0,
984 ],
985];
986
987impl Reach {
988 /// What a block of `side` samples at `(x, y)` may read past its own edges,
989 /// in a frame of `width` by `height`.
990 pub(crate) fn of(side: usize, x: usize, y: usize, width: usize, height: usize) -> Self {
991 Self {
992 above_right: y > 0 && x + side < width && Self::top_right(side, x, y),
993 below_left: x > 0 && y + side < height && Self::bottom_left(side, x, y),
994 }
995 }
996
997 /// Neither, which is all a mode that reads no further than its own edges
998 /// needs.
999 pub(crate) fn none() -> Self {
1000 Self {
1001 above_right: false,
1002 below_left: false,
1003 }
1004 }
1005
1006 /// `has_top_right` for a block whose transform covers it whole: the top
1007 /// row of a superblock reads into the superblock above, which is decoded;
1008 /// the rightmost column would read into the superblock to the right, which
1009 /// is not; and everything between is the table's to answer.
1010 fn top_right(side: usize, x: usize, y: usize) -> bool {
1011 let (row, col, per_side) = Self::position(side, x, y);
1012 if row == 0 {
1013 return true;
1014 }
1015 if col + 1 == per_side {
1016 return false;
1017 }
1018 Self::bit(
1019 HAS_TOP_RIGHT[Self::table(side)],
1020 row * Self::table_stride(side) + col,
1021 )
1022 }
1023
1024 /// `has_bottom_left` for such a block: the leftmost column of a superblock
1025 /// reads into the superblock to its left, which is decoded only as far
1026 /// down as its own bottom; the bottom row would read into the superblock
1027 /// below, which is not decoded at all; and the table answers the rest.
1028 fn bottom_left(side: usize, x: usize, y: usize) -> bool {
1029 let (row, col, per_side) = Self::position(side, x, y);
1030 if col == 0 {
1031 return row * side + side < SUPERBLOCK;
1032 }
1033 if row + 1 == per_side {
1034 return false;
1035 }
1036 Self::bit(
1037 HAS_BOTTOM_LEFT[Self::table(side)],
1038 row * Self::table_stride(side) + col,
1039 )
1040 }
1041
1042 /// Where a block sits inside its superblock, in blocks of its own size,
1043 /// and how many of them a superblock is across.
1044 fn position(side: usize, x: usize, y: usize) -> (usize, usize, usize) {
1045 (
1046 (y % SUPERBLOCK) / side,
1047 (x % SUPERBLOCK) / side,
1048 SUPERBLOCK / side,
1049 )
1050 }
1051
1052 /// The row stride `HAS_TOP_RIGHT`/`HAS_BOTTOM_LEFT` index by: libaom pins
1053 /// these tables to its compile-time maximum superblock (128, spec
1054 /// `MAX_MIB_SIZE_LOG2` = 5 in 4-pixel units), not to whichever superblock
1055 /// size an encode actually uses, so a block's row in the bit index steps
1056 /// by 128 / `side` even though this crate only ever codes a 64
1057 /// superblock -- using `per_side` (`SUPERBLOCK` / `side`, 64-relative)
1058 /// here instead indexes the wrong bit for every block size but the one
1059 /// where 64 and 128 give the same stride.
1060 fn table_stride(side: usize) -> usize {
1061 128 / side
1062 }
1063
1064 /// Which of the three block sizes the encoder codes a table row is for.
1065 fn table(side: usize) -> usize {
1066 if side == BLOCK {
1067 1
1068 } else if side == 8 {
1069 2
1070 } else {
1071 0
1072 }
1073 }
1074
1075 /// One bit of a table, counting from the low end of its first byte.
1076 fn bit(table: &[u8], index: usize) -> bool {
1077 (table[index / 8] >> (index % 8)) & 1 != 0
1078 }
1079}
1080
1081/// What one symbol costs against a CDF, in bits.
1082pub(crate) fn symbol_bits(cdf: &[u16], symbol: usize) -> f64 {
1083 let low = if symbol == 0 { 0 } else { cdf[symbol - 1] };
1084 let probability = f64::from(cdf[symbol] - low) / 32768.0;
1085 -probability.log2()
1086}
1087
1088/// What the tile writer spends to say a block is coded in each of the thirteen
1089/// modes, given the modes of the blocks above it and to its left: the luma mode
1090/// symbol against the CDF those two neighbours pick, the angle delta a
1091/// directional mode carries, and the chroma mode symbol, whose CDF the luma
1092/// mode itself indexes.
1093///
1094/// Without this the search is blind to what a mode costs to name, which is not
1095/// a rounding error: a directional mode on a picture that does not run that way
1096/// is a rate loss the squared error never sees.
1097/// Codes one square of the picture as a single block: searches the luma mode,
1098/// codes both chroma planes DC, and hands back the block and what it cost --
1099/// squared error plus lambda times the bits its symbols spend.
1100fn code_square(
1101 luma: &mut Plane,
1102 chroma: &mut [Plane; 2],
1103 (x, y): (usize, usize),
1104 side: usize,
1105 search: &Search,
1106 mode_bits: &[f64; 13],
1107) -> (BlockCoeffs, f64) {
1108 let (luma_set, chroma_set) = if side == BLOCK {
1109 (TxbSet::Luma32, TxbSet::Chroma16)
1110 } else if side == 8 {
1111 // An 8x8 leaf under a straddling 16x16 (lane-av1-rect). r5 correction:
1112 // `TxbSet::Chroma4`'s doc now has the checked spec fact -- chroma is
1113 // `is_chroma_reference` at every BLOCK_8X8, so it is coded per leaf at
1114 // 4x4, not once at the parent's 8x8. No caller passes `side == 8` yet
1115 // (this branch is still unreached), so leaving `Chroma8` here would
1116 // silently wire the wrong table the moment one does; `Chroma4` is
1117 // what a real caller needs.
1118 (TxbSet::Luma8, TxbSet::Chroma4)
1119 } else {
1120 (TxbSet::Luma16, TxbSet::Chroma8)
1121 };
1122 let (luma_coeffs, mode, mut cost) = luma.search_block(
1123 At {
1124 x,
1125 y,
1126 side,
1127 reach: Reach::of(side, x, y, luma.true_width, luma.true_height),
1128 set: luma_set,
1129 },
1130 search,
1131 mode_bits,
1132 );
1133 // Chroma is predicted DC because that is the mode the tile writer codes
1134 // for it; what it costs still counts towards the partition decision.
1135 let mut planes = [Vec::new(), Vec::new()];
1136 for (plane, coeffs) in chroma.iter_mut().zip(&mut planes) {
1137 let (levels, sse, bits) = plane.code_block(
1138 At {
1139 x: x / 2,
1140 y: y / 2,
1141 side: side / 2,
1142 reach: Reach::none(),
1143 set: chroma_set,
1144 },
1145 DC_PRED,
1146 search.base_q_idx,
1147 search.deadzone,
1148 );
1149 *coeffs = levels;
1150 cost += sse + search.lambda * bits;
1151 }
1152 let [u, v] = planes;
1153 (
1154 BlockCoeffs {
1155 u,
1156 v,
1157 luma: luma_coeffs,
1158 mode,
1159 ..BlockCoeffs::default()
1160 },
1161 cost,
1162 )
1163}
1164
1165/// Codes one leaf of a straddling quadrant as whichever costs least of intra
1166/// ([`code_square`], unchanged) or `NEARESTMV` against `reference` at
1167/// `stack.nearest_mv` -- the same NEARESTMV candidate [`search_inter_block`]
1168/// prices for a whole 32x32 block, just at this leaf's own `side` (16, for a
1169/// 16x16 leaf under a straddling 32x32 quadrant, or 8, for an 8x8 leaf under
1170/// a straddling 16x16 -- lane-av1inter8) and through [`TxbSet::Luma16Inter`]
1171/// or [`TxbSet::Luma8Inter`]. `NEWMV` (a motion search of its own) is not
1172/// attempted here: these leaves only ever fill the sliver of real content a
1173/// true edge lands in the middle of a larger block, not a leaf worth a full
1174/// search, so `NEARESTMV`-or-intra is this function's deliberate first cut
1175/// (see `write_inter_frame_leaf`'s doc comment).
1176#[allow(clippy::too_many_arguments)]
1177fn code_square_inter(
1178 luma: &mut Plane,
1179 chroma: &mut [Plane; 2],
1180 (x, y): (usize, usize),
1181 side: usize,
1182 search: &Search,
1183 mode_bits: &[f64; 13],
1184 reference: &Picture,
1185 stack: &MvStack,
1186) -> BlockCoeffs {
1187 let (intra_block, intra_cost) = code_square(luma, chroma, (x, y), side, search, mode_bits);
1188 let luma_set = if side == 8 {
1189 TxbSet::Luma8Inter
1190 } else {
1191 TxbSet::Luma16Inter
1192 };
1193 let chroma_set = if side == 8 {
1194 TxbSet::Chroma4
1195 } else {
1196 TxbSet::Chroma8
1197 };
1198
1199 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
1200 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
1201 let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0)
1202 + symbol_bits(&cdf::SINGLE_REF[0][2], 0)
1203 + symbol_bits(&cdf::SINGLE_REF[0][3], 0);
1204 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
1205 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
1206 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
1207
1208 let mv = stack.nearest_mv;
1209 let ref_luma = (
1210 &reference.y,
1211 reference.width,
1212 luma.true_width,
1213 luma.true_height,
1214 );
1215 let ref_u = (
1216 &reference.u,
1217 reference.width / 2,
1218 chroma[0].true_width,
1219 chroma[0].true_height,
1220 );
1221 let ref_v = (
1222 &reference.v,
1223 reference.width / 2,
1224 chroma[1].true_width,
1225 chroma[1].true_height,
1226 );
1227 let luma_trial = mc_trial(
1228 luma,
1229 x,
1230 y,
1231 side,
1232 mv,
1233 true,
1234 ref_luma.0,
1235 ref_luma.1,
1236 ref_luma.2,
1237 ref_luma.3,
1238 false,
1239 search.base_q_idx,
1240 search.deadzone,
1241 luma_set,
1242 );
1243 let u = mc_trial(
1244 &chroma[0],
1245 x / 2,
1246 y / 2,
1247 side / 2,
1248 mv,
1249 false,
1250 ref_u.0,
1251 ref_u.1,
1252 ref_u.2,
1253 ref_u.3,
1254 false,
1255 search.base_q_idx,
1256 search.deadzone,
1257 chroma_set,
1258 );
1259 let v = mc_trial(
1260 &chroma[1],
1261 x / 2,
1262 y / 2,
1263 side / 2,
1264 mv,
1265 false,
1266 ref_v.0,
1267 ref_v.1,
1268 ref_v.2,
1269 ref_v.3,
1270 false,
1271 search.base_q_idx,
1272 search.deadzone,
1273 chroma_set,
1274 );
1275 let skip = luma_trial.levels.iter().all(|&l| l == 0)
1276 && u.levels.iter().all(|&l| l == 0)
1277 && v.levels.iter().all(|&l| l == 0);
1278 let inter_cost = luma_trial.sse
1279 + u.sse
1280 + v.sse
1281 + search.lambda
1282 * (skip_bits(skip)
1283 + intra_inter_bits(true)
1284 + single_ref_bits
1285 + mode_bits_inter
1286 + if skip {
1287 0.0
1288 } else {
1289 luma_trial.bits + u.bits + v.bits
1290 });
1291
1292 // NEARESTMV for 16x16 leaves, gated on real cost. r1/r2 found the gate's
1293 // desync in `mvstack.rs`'s `find_mv_stack`: it lacked spec 7.10.2.4's
1294 // extended row/col scan, invisible at 8-mi-only geometry (the immediate
1295 // scan's own coverage already reached as far) but a real gap at 4-mi
1296 // leaf geometry. r3 ported the extended scan and, while proving it a
1297 // no-op at 8-mi (`extended_row_scan_is_a_no_op_at_8mi_geometry_*`,
1298 // `mvstack.rs`), found and fixed a second bug the extended scan's
1299 // coverage bookkeeping (`processed_rows`/`processed_cols`) exposed: an
1300 // intra neighbour is a coded cell too (libaom's `scan_row_mbmi`/
1301 // `scan_col_mbmi` advance coverage from any candidate's `bsize`,
1302 // regardless of whether it also casts a ref-frame-matching vote) --
1303 // `MiGrid` now records intra cells (`tile.rs`/`encode.rs`'s `else`
1304 // branches), which is what made 8-mi geometry a true no-op instead of
1305 // one that only held when every neighbour happened to be inter.
1306 if inter_cost < intra_cost {
1307 luma.commit(x, y, side, &luma_trial);
1308 chroma[0].commit(x / 2, y / 2, side / 2, &u);
1309 chroma[1].commit(x / 2, y / 2, side / 2, &v);
1310 BlockCoeffs {
1311 luma: coeffs(&luma_trial.levels, side),
1312 u: coeffs(&u.levels, side / 2),
1313 v: coeffs(&v.levels, side / 2),
1314 mode: DC_PRED as u8,
1315 skip,
1316 eight: None,
1317 inter: Some(InterInfo {
1318 mode: InterMode::NearestMv,
1319 mv,
1320 }),
1321 }
1322 } else {
1323 intra_block
1324 }
1325}
1326
1327/// The reconstructed samples one 32x32 square covers in all three planes, so
1328/// that a partition trial can be undone.
1329fn snapshot(luma: &Plane, chroma: &[Plane; 2], (x, y): (usize, usize)) -> [Vec<u8>; 3] {
1330 [
1331 luma.snapshot(x, y, BLOCK),
1332 chroma[0].snapshot(x / 2, y / 2, BLOCK / 2),
1333 chroma[1].snapshot(x / 2, y / 2, BLOCK / 2),
1334 ]
1335}
1336
1337/// Puts such a snapshot back.
1338fn restore(
1339 luma: &mut Plane,
1340 chroma: &mut [Plane; 2],
1341 (x, y): (usize, usize),
1342 saved: &[Vec<u8>; 3],
1343) {
1344 luma.restore(x, y, BLOCK, &saved[0]);
1345 chroma[0].restore(x / 2, y / 2, BLOCK / 2, &saved[1]);
1346 chroma[1].restore(x / 2, y / 2, BLOCK / 2, &saved[2]);
1347}
1348
1349/// Keeps the DC candidate plus the cheapest `top_k` (or fewer, once DC is set
1350/// aside) of `scored` (as [`Plane::intra_scores`] built it), in `modes`' own
1351/// order -- the same DC-always-kept, cheapest-by-SAD rule [`Plane::search_block`]
1352/// applies, so [`search_inter_block`]'s intra-candidate loop prunes by one
1353/// rule shared with the key-frame path, not a second one that could diverge.
1354fn prune_by_sad(modes: &[u8], mut scored: Vec<(f64, u8)>, top_k: usize) -> Vec<u8> {
1355 let dc_pos = scored.iter().position(|&(_, mode)| mode == DC_PRED);
1356 let dc_entry = dc_pos.map(|i| scored.remove(i));
1357 scored.sort_by(|a, b| a.0.partial_cmp(&b.0).expect("scores are finite"));
1358 scored.truncate(if dc_entry.is_some() {
1359 top_k.saturating_sub(1)
1360 } else {
1361 top_k
1362 });
1363 if let Some(dc_entry) = dc_entry {
1364 scored.push(dc_entry);
1365 }
1366 let keep: Vec<u8> = scored.into_iter().map(|(_, mode)| mode).collect();
1367 modes.iter().copied().filter(|m| keep.contains(m)).collect()
1368}
1369
1370fn mode_bits(above_mode: u8, left_mode: u8) -> [f64; 13] {
1371 let luma = &cdf::KF_Y_MODE[INTRA_MODE_CTX[usize::from(above_mode)]]
1372 [INTRA_MODE_CTX[usize::from(left_mode)]];
1373 std::array::from_fn(|mode| {
1374 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
1375 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
1376 } else {
1377 0.0
1378 };
1379 symbol_bits(luma, mode) + angle + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
1380 })
1381}
1382
1383/// What the luma mode search picks between, and under what terms.
1384struct Search<'a> {
1385 base_q_idx: u8,
1386 deadzone: f64,
1387 lambda: f64,
1388 modes: &'a [u8],
1389 /// How many of `modes` the full RD trial (forward transform, quantize,
1390 /// reconstruct, `coeff_bits`) actually runs on, ranked by a cheap SAD
1391 /// pre-pass on the prediction residual alone plus DC (always kept, since
1392 /// libaom's own intra pruning -- `av1/encoder/speed_features.c`'s
1393 /// `intra_pruning_with_hog` -- never prunes it away). `None` runs every
1394 /// mode through full RD, unchanged from before this lever.
1395 top_k: Option<usize>,
1396}
1397
1398/// [`Search::top_k`]'s value: `None` keeps every mode's search unchanged
1399/// (the default, until a lever's quality gate justifies pruning by default);
1400/// `EC_AV1_PRUNE_K` sweeps it in a test build without touching callers.
1401fn prune_top_k() -> Option<usize> {
1402 #[cfg(test)]
1403 {
1404 if let Some(k) = TEST_TOP_K_OVERRIDE.with(|cell| cell.get()) {
1405 return k;
1406 }
1407 }
1408 let swept = std::env::var("EC_AV1_PRUNE_K")
1409 .ok()
1410 .and_then(|v| v.parse::<usize>().ok());
1411 match swept {
1412 Some(k) if cfg!(test) => Some(k),
1413 _ => PRUNE_TOP_K,
1414 }
1415}
1416
1417/// A per-thread override [`prune_top_k`] checks first, so one test can sweep
1418/// `top_k` in-process without mutating the environment (forbidden here --
1419/// `#![forbid(unsafe_code)]` -- and racy across parallel tests besides).
1420#[cfg(test)]
1421thread_local! {
1422 static TEST_TOP_K_OVERRIDE: std::cell::Cell<Option<Option<usize>>> =
1423 const { std::cell::Cell::new(None) };
1424}
1425
1426#[cfg(test)]
1427fn set_test_top_k_override(value: Option<usize>) {
1428 TEST_TOP_K_OVERRIDE.with(|cell| cell.set(Some(value)));
1429}
1430
1431/// The default: unpruned, thirteen full trials per block, same as before this
1432/// lever. Set from the sweep in the lane report if the quality gate clears it.
1433const PRUNE_TOP_K: Option<usize> = None;
1434
1435/// [`Search::top_k`] for [`search_inter_block`]'s intra-candidate loop --
1436/// kept apart from [`prune_top_k`]/[`PRUNE_TOP_K`] because the two paths'
1437/// quality gates were measured separately and may land on different
1438/// defaults; `EC_AV1_PRUNE_K_INTER` sweeps it without touching
1439/// [`EC_AV1_PRUNE_K`] or the key-frame path.
1440fn prune_top_k_inter() -> Option<usize> {
1441 #[cfg(test)]
1442 {
1443 if let Some(k) = TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.get()) {
1444 return k;
1445 }
1446 }
1447 let swept = std::env::var("EC_AV1_PRUNE_K_INTER")
1448 .ok()
1449 .and_then(|v| v.parse::<usize>().ok());
1450 match swept {
1451 Some(k) if cfg!(test) => Some(k),
1452 _ => INTER_PRUNE_TOP_K,
1453 }
1454}
1455
1456/// A per-thread override [`prune_top_k_inter`] checks first, same reason as
1457/// [`TEST_TOP_K_OVERRIDE`].
1458#[cfg(test)]
1459thread_local! {
1460 static TEST_TOP_K_OVERRIDE_INTER: std::cell::Cell<Option<Option<usize>>> =
1461 const { std::cell::Cell::new(None) };
1462}
1463
1464#[cfg(test)]
1465fn set_test_top_k_override_inter(value: Option<usize>) {
1466 TEST_TOP_K_OVERRIDE_INTER.with(|cell| cell.set(Some(value)));
1467}
1468
1469/// The inter path's default `top_k`: `Some(3)`, from `prune_k_quality_sweep_inter`
1470/// (three real clips, q 60 and 150) -- every `K` in {3, 4, 6} cleared the
1471/// same rule the key-frame lever uses (every PSNR delta <0.05dB, bytes
1472/// within +1%; worst seen was -0.011dB / +0.147% bytes), so the cheapest,
1473/// `K=3`, ships as default. Unlike the key-frame path (still `None`), an
1474/// inter block's intra candidates rarely win against NEWMV/NEARESTMV, so
1475/// pruning them costs less quality here.
1476const INTER_PRUNE_TOP_K: Option<usize> = Some(3);
1477
1478/// Per-thread nanosecond counters `stage_timing_breakdown_inter` (and
1479/// [`crate::mc::predict`], through [`stage_add`]) accumulate into, so an
1480/// inter frame's cost can be attributed to a bucket without changing what
1481/// the search actually does. Index: 0 = whole-call time inside
1482/// [`motion::search`] (includes bucket 1's time, run from inside it), 1 =
1483/// [`crate::mc::predict`] (every call, from the motion search's own
1484/// candidates and from a committed inter block's final prediction alike),
1485/// 2 = `forward_and_quantize` + `dequant_and_inverse`, 3 = `coeff_bits`.
1486#[cfg(test)]
1487thread_local! {
1488 static STAGE_NS: [std::cell::Cell<u64>; 4] = [
1489 std::cell::Cell::new(0),
1490 std::cell::Cell::new(0),
1491 std::cell::Cell::new(0),
1492 std::cell::Cell::new(0),
1493 ];
1494}
1495
1496#[cfg(test)]
1497pub(crate) fn stage_add(bucket: usize, dur: std::time::Duration) {
1498 STAGE_NS.with(|c| c[bucket].set(c[bucket].get() + dur.as_nanos() as u64));
1499}
1500
1501#[cfg(test)]
1502fn stage_reset() {
1503 STAGE_NS.with(|c| c.iter().for_each(|cell| cell.set(0)));
1504}
1505
1506#[cfg(test)]
1507fn stage_read() -> [std::time::Duration; 4] {
1508 STAGE_NS.with(|c| {
1509 c.each_ref()
1510 .map(|cell| std::time::Duration::from_nanos(cell.get()))
1511 })
1512}
1513
1514/// One mode's coding of one block, before it is committed.
1515#[derive(Clone)]
1516struct Trial {
1517 levels: Vec<i32>,
1518 reconstruction: Vec<u8>,
1519 sse: f64,
1520 bits: f64,
1521}
1522
1523/// The non-zero levels of a block, as the tile writer takes them.
1524fn coeffs(levels: &[i32], side: usize) -> Vec<Coeff> {
1525 levels
1526 .iter()
1527 .enumerate()
1528 .filter(|&(_, &level)| level != 0)
1529 .map(|(i, &level)| Coeff {
1530 row: (i / side) as u8,
1531 col: (i % side) as u8,
1532 level,
1533 })
1534 .collect()
1535}
1536
1537/// Encodes one picture as a key frame.
1538///
1539/// `base_q_idx` is the frame's quantizer index (0..=255); the tile writer
1540/// picks its coefficient CDFs from one of four q contexts by that index.
1541/// `deadzone` is the quantizer's rounding offset: 0.5 rounds to nearest, and
1542/// smaller values trade fidelity for rate.
1543///
1544/// The picture may be any even width and height: the encoder pads it by edge
1545/// replication to a whole number of 32x32 blocks internally, and the frame it
1546/// writes crops back to the picture's own size (`render_width`/
1547/// `render_height`), so [`Encoded::reconstruction`] is always the picture's
1548/// own size, never the padded one.
1549///
1550/// # Errors
1551/// Returns an error when the picture's width or height is zero or odd, or
1552/// when its planes are not 4:2:0 of that size.
1553pub fn encode_key_frame(picture: &Picture, base_q_idx: u8, deadzone: f64) -> Result<Encoded> {
1554 encode_key_frame_with_modes(picture, base_q_idx, deadzone, &KEY_FRAME_MODES)
1555}
1556
1557/// Encodes one picture as a key frame, choosing each block's luma mode from
1558/// `modes` alone.
1559///
1560/// This is what an ablation measures against: `&[DC_PRED]` is the encoder
1561/// before the mode search, [`crate::intra::NON_DIRECTIONAL`] is it before the
1562/// directional modes, and [`KEY_FRAME_MODES`] is what [`encode_key_frame`]
1563/// uses.
1564///
1565/// # Errors
1566/// The same as [`encode_key_frame`], and additionally when `modes` is empty or
1567/// names a mode [`crate::intra::predict`] does not predict.
1568pub fn encode_key_frame_with_modes(
1569 picture: &Picture,
1570 base_q_idx: u8,
1571 deadzone: f64,
1572 modes: &[u8],
1573) -> Result<Encoded> {
1574 picture.check_even()?;
1575 let padded = picture.padded_to(BLOCK);
1576 let encoded = encode_key_frame_inner(
1577 &padded,
1578 base_q_idx,
1579 deadzone,
1580 modes,
1581 split_blocks(),
1582 (picture.width, picture.height),
1583 unspecified_color_config(),
1584 )?;
1585 Ok(crop_encoded(&encoded, picture.width, picture.height))
1586}
1587
1588/// [`encode_key_frame_with_modes`] with the partition decision forced, which is
1589/// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
1590/// already padded to a whole number of 32x32 blocks; `render` is the real
1591/// (pre-pad) size the frame header tells a decoder to crop back to.
1592pub(crate) fn encode_key_frame_inner(
1593 picture: &Picture,
1594 base_q_idx: u8,
1595 deadzone: f64,
1596 modes: &[u8],
1597 split_blocks: bool,
1598 render: (usize, usize),
1599 color_config: ColorConfig,
1600) -> Result<Encoded> {
1601 picture.check()?;
1602 if modes.is_empty() {
1603 return Err(Error::unsupported(
1604 "AV1 encode",
1605 "a mode search needs at least one mode to choose from",
1606 ));
1607 }
1608 if let Some(bad) = modes.iter().find(|m| !KEY_FRAME_MODES.contains(m)) {
1609 return Err(Error::unsupported(
1610 "AV1 encode",
1611 format!("intra mode {bad} is not one the encoder predicts"),
1612 ));
1613 }
1614 // The header carries the frame's true (unpadded) size as `frame_width`/
1615 // `frame_height` -- what a decoder actually crops to -- with `mi_cols`/
1616 // `mi_rows` derived from that same true size (spec `compute_image_size`).
1617 // `render_width`/`render_height` come out equal to it too, so
1618 // `render_and_frame_size_different` is false and no render_size bits are
1619 // written, mirroring libaom/rav1e: the padded `picture` below is only the
1620 // internal coding surface, never what the header names.
1621 let (seq, mut header) = key_frame_headers_colour(render.0, render.1, base_q_idx, color_config)?;
1622 header.render_width = render.0 as u32;
1623 header.render_height = render.1 as u32;
1624
1625 // Prediction reads no further than this, in each plane's own units --
1626 // see `Plane::true_width`/`true_height`.
1627 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
1628 let mut luma = Plane {
1629 source: &picture.y,
1630 reconstruction: vec![128; picture.y.len()],
1631 width: picture.width,
1632 height: picture.height,
1633 true_width,
1634 true_height,
1635 };
1636 let mut chroma = [
1637 Plane {
1638 source: &picture.u,
1639 reconstruction: vec![128; picture.u.len()],
1640 width: picture.width / 2,
1641 height: picture.height / 2,
1642 true_width: true_width / 2,
1643 true_height: true_height / 2,
1644 },
1645 Plane {
1646 source: &picture.v,
1647 reconstruction: vec![128; picture.v.len()],
1648 width: picture.width / 2,
1649 height: picture.height / 2,
1650 true_width: true_width / 2,
1651 true_height: true_height / 2,
1652 },
1653 ];
1654
1655 // The search trades a bit for the squared error it saves, in the units the
1656 // reconstruction is measured in: one step of the quantizer, squared.
1657 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
1658 let search = Search {
1659 base_q_idx,
1660 deadzone,
1661 lambda: lambda_scale() * step * step,
1662 modes,
1663 top_k: prune_top_k(),
1664 };
1665
1666 // The block grid this frame is coded over: [`crate::tile::block_grid`]'s
1667 // ceiling of the header's own (true-size-derived) `mi_cols`/`mi_rows`,
1668 // which may be fewer columns/rows than the padded picture has room for
1669 // -- a block whose origin sits past the true bound is not coded at all,
1670 // matching what a decoder derives from `frame_width`/`frame_height` and
1671 // so never visits either.
1672 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
1673 let (cols, rows) = (cols as usize, rows as usize);
1674 // The luma mode of the block above and of the block to the left, which is
1675 // what picks the CDF the next block's mode is coded against -- the same
1676 // bookkeeping the tile writer keeps, so that the search is costing the
1677 // symbol the writer will actually write.
1678 // The bookkeeping is kept on the 16x16 grid the tile writer keeps it on,
1679 // because a 32x32 block may be split into four 16x16 ones.
1680 let mut above_mode = vec![DC_PRED; cols * 2];
1681 let mut left_mode = vec![DC_PRED; rows * 2];
1682 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
1683 let mut superblocks = Vec::with_capacity(sb_cols * sb_rows);
1684 let mut modes = Vec::with_capacity(cols * rows);
1685 for sb_row in 0..sb_rows {
1686 for sb_col in 0..sb_cols {
1687 // The quadrants of a superblock are coded in the order the decoder
1688 // walks them, which for a 64x64 split into 32x32 blocks is raster
1689 // order among the quadrants that are inside the frame.
1690 let mut blocks = Vec::with_capacity(4);
1691 for quadrant in 0..4 {
1692 let (col, row) = (sb_col * 2 + quadrant % 2, sb_row * 2 + quadrant / 2);
1693 if col >= cols || row >= rows {
1694 continue;
1695 }
1696 let (x, y) = (col * BLOCK, row * BLOCK);
1697 let (c0, r0) = (col * 2, row * 2);
1698 let base = snapshot(&luma, &chroma, (x, y));
1699
1700 // spec `decode_partition`'s hasRows/hasCols recomputed at this
1701 // 32x32 block's own half (see `crate::tile::has_half`): the
1702 // true frame edge can fall inside a quadrant a superblock-level
1703 // check already let through. A quadrant that fails either may
1704 // not be left whole; a 16x16 sub-block that fails either (once
1705 // split) is a leaf this writer has no rectangular transform
1706 // for, so the search must not pick a split that would need one.
1707 let (has_cols32, has_rows32) = (
1708 crate::tile::has_half(
1709 col as u32 * crate::tile::BLOCK_MI,
1710 crate::tile::BLOCK_MI,
1711 header.mi_cols,
1712 ),
1713 crate::tile::has_half(
1714 row as u32 * crate::tile::BLOCK_MI,
1715 crate::tile::BLOCK_MI,
1716 header.mi_rows,
1717 ),
1718 );
1719 let whole_legal = has_cols32 && has_rows32;
1720 // A 16x16 sub-block's own hasCols/hasRows (spec
1721 // `decode_partition`, recomputed at this leaf's own half): one
1722 // axis false is a straddling leaf this writer codes as two
1723 // 8x8 leaves (`crate::tile::write_leaf8`, lane-av1-rect r7);
1724 // both axes false needs a rectangular transform this writer
1725 // has no size for at all, whether whole or split.
1726 let sub_half = |sr: usize, sc: usize| {
1727 (
1728 crate::tile::has_half(
1729 sc as u32 * crate::tile::SUB_MI,
1730 crate::tile::SUB_MI,
1731 header.mi_cols,
1732 ),
1733 crate::tile::has_half(
1734 sr as u32 * crate::tile::SUB_MI,
1735 crate::tile::SUB_MI,
1736 header.mi_rows,
1737 ),
1738 )
1739 };
1740 let both_axes_cut = (0..4)
1741 .map(|i| (r0 + i / 2, c0 + i % 2))
1742 .filter(|&(sr, sc)| {
1743 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
1744 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
1745 })
1746 .any(|(sr, sc)| {
1747 let (has_cols16, has_rows16) = sub_half(sr, sc);
1748 !has_cols16 && !has_rows16
1749 });
1750 if !whole_legal && both_axes_cut {
1751 return Err(Error::unsupported(
1752 "AV1 encode",
1753 format!(
1754 "the 32x32 block at ({col},{row}) straddles the true frame edge \
1755 in a way that needs a rectangular (HORZ/VERT) transform this \
1756 encoder does not code yet"
1757 ),
1758 ));
1759 }
1760
1761 // What the whole 32x32 costs, including the partition symbol
1762 // that says it is not split.
1763 let (whole, mut cost_whole) = code_square(
1764 &mut luma,
1765 &mut chroma,
1766 (x, y),
1767 BLOCK,
1768 &search,
1769 &mode_bits(above_mode[c0], left_mode[r0]),
1770 );
1771 cost_whole += search.lambda * partition_bits(BLOCK, false);
1772 let after_whole = snapshot(&luma, &chroma, (x, y));
1773
1774 // What four 16x16 blocks cost instead, each searched against
1775 // the reconstruction the ones before it left.
1776 restore(&mut luma, &mut chroma, (x, y), &base);
1777 let mut split = Vec::with_capacity(4);
1778 let mut cost_split = search.lambda
1779 * (partition_bits(BLOCK, true) + 4.0 * partition_bits(SUB, false));
1780 let mut split_modes = Vec::with_capacity(4);
1781 for sub in 0..4 {
1782 let (sc, sr) = (c0 + sub % 2, r0 + sub / 2);
1783 // Same filter as the writer's `sub_positions` (spec
1784 // `decode_partition`'s `r >= MiRows || c >= MiCols` early
1785 // return): a sub-block whose own origin sits past the
1786 // true frame is never coded, so it must not be searched
1787 // or pushed onto `split` either, or the writer's block
1788 // count will not match what it is prepared to name.
1789 if (sr as u32) * crate::tile::SUB_MI >= header.mi_rows
1790 || (sc as u32) * crate::tile::SUB_MI >= header.mi_cols
1791 {
1792 continue;
1793 }
1794 let (has_cols16, has_rows16) = sub_half(sr, sc);
1795 if has_cols16 && has_rows16 {
1796 let (block, cost) = code_square(
1797 &mut luma,
1798 &mut chroma,
1799 (x + (sub % 2) * SUB, y + (sub / 2) * SUB),
1800 SUB,
1801 &search,
1802 &mode_bits(above_mode[sc], left_mode[sr]),
1803 );
1804 cost_split += cost;
1805 split_modes.push(block.mode);
1806 above_mode[sc] = block.mode;
1807 left_mode[sr] = block.mode;
1808 split.push(block);
1809 } else {
1810 // A straddling 16x16: two (or, at a true corner, one)
1811 // 8x8 leaves, in the raster order `write_leaf8`'s
1812 // caller expects. Both leaves cost against the SAME
1813 // enclosing-slot mode context (see
1814 // `crate::tile::write_leaf8`'s doc), and neither
1815 // updates `above_mode`/`left_mode` at this SUB slot --
1816 // the writer never does either, so the search must
1817 // not diverge from what it will actually read next.
1818 let leaf_mode_bits = mode_bits(above_mode[sc], left_mode[sr]);
1819 let (x_sub, y_sub) = (x + (sub % 2) * SUB, y + (sub / 2) * SUB);
1820 let mut leaves = Vec::with_capacity(2);
1821 for i in 0..4 {
1822 let leaf_x = x_sub + (i % 2) * 8;
1823 let leaf_y = y_sub + (i / 2) * 8;
1824 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
1825 continue;
1826 }
1827 let (leaf, cost) = code_square(
1828 &mut luma,
1829 &mut chroma,
1830 (leaf_x, leaf_y),
1831 8,
1832 &search,
1833 &leaf_mode_bits,
1834 );
1835 cost_split += cost;
1836 split_modes.push(leaf.mode);
1837 leaves.push(leaf);
1838 }
1839 split.push(BlockCoeffs {
1840 eight: Some(leaves),
1841 ..BlockCoeffs::default()
1842 });
1843 }
1844 }
1845
1846 // A split whose subs are all whole 16x16 is a real quality
1847 // alternative to `whole`, exactly as before. Through r14, a
1848 // split carrying an 8x8-leaf sub was only ever forced
1849 // (`!whole_legal`), never chosen on cost, because the leaf
1850 // path was not yet proven against a real decoder; r15 proved
1851 // it against ffmpeg, and lane-av1dec r5 taught crate::decode
1852 // the read path (`decode_leaf8`), so leaf8 can now win on
1853 // cost anywhere, same as any other split.
1854 if !whole_legal || (split_blocks && cost_split < cost_whole) {
1855 modes.extend_from_slice(&split_modes);
1856 blocks.push(Quadrant::Split(split));
1857 } else {
1858 restore(&mut luma, &mut chroma, (x, y), &after_whole);
1859 for cell in 0..2 {
1860 above_mode[c0 + cell] = whole.mode;
1861 left_mode[r0 + cell] = whole.mode;
1862 }
1863 modes.push(whole.mode);
1864 blocks.push(Quadrant::Whole(whole));
1865 }
1866 }
1867 superblocks.push(Superblock::Split(blocks));
1868 }
1869 }
1870
1871 let tile = sb_coeff_key_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &superblocks)?;
1872 let mut stream = temporal_delimiter();
1873 stream.extend_from_slice(&sequence_header_obu(&seq)?);
1874 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
1875
1876 let [u, v] = chroma;
1877 Ok(Encoded {
1878 stream,
1879 modes,
1880 inter_block_share: 0.0,
1881 reconstruction: Picture {
1882 width: luma.width,
1883 height: luma.height,
1884 y: luma.reconstruction,
1885 u: u.reconstruction,
1886 v: v.reconstruction,
1887 },
1888 tile,
1889 mi_cols: header.mi_cols,
1890 mi_rows: header.mi_rows,
1891 base_q_idx,
1892 })
1893}
1894
1895/// `Y_MODE`'s size group (spec `Size_Group`) for a 32x32 block: the only
1896/// group an inter frame's intra branch codes (spec `inter_frame_mode_info`),
1897/// since every block this crate's inter tile writer codes is 32x32.
1898const SIZE_GROUP_32: usize = 3;
1899
1900/// `Ref_Frame_List`'s `LAST_FRAME` (spec 3): the only reference
1901/// [`sb_coeff_inter_frame_tile`] ever names, and so the only one the MV
1902/// stack this encoder builds is ever asked to predict against.
1903const LAST_FRAME: i8 = 1;
1904
1905/// What an inter frame's intra branch spends to name each of the thirteen
1906/// modes: `Y_MODE` by size group rather than `KF_Y_MODE` by neighbour
1907/// context, since an inter frame's intra blocks do not read their
1908/// neighbours' modes (spec `inter_frame_mode_info`, `sb_coeff_inter_frame_tile`'s
1909/// own doc comment). Unlike [`mode_bits`] this needs no per-block neighbour
1910/// state, so it is built once per frame.
1911fn inter_mode_bits() -> [f64; 13] {
1912 std::array::from_fn(|mode| {
1913 let angle = if (usize::from(V_PRED)..=usize::from(D67_PRED)).contains(&mode) {
1914 symbol_bits(&cdf::ANGLE_DELTA[mode - usize::from(V_PRED)], 3)
1915 } else {
1916 0.0
1917 };
1918 symbol_bits(&cdf::Y_MODE[SIZE_GROUP_32], mode)
1919 + angle
1920 + symbol_bits(&cdf::UV_MODE_CFL[mode], usize::from(DC_PRED))
1921 })
1922}
1923
1924/// A 1/8-pel motion vector component, converted to the 1/16-pel offset
1925/// [`mc::predict`] takes, in the units of the plane it predicts into.
1926///
1927/// A luma sample of displacement is `mv/8`; in the 1/16-pel domain that is
1928/// `mv*2`. A 4:2:0 chroma sample is half a luma sample wide, so the same
1929/// physical displacement is `mv/16` chroma samples — `mv*1` in the 1/16-pel
1930/// domain. `luma` picks which.
1931fn mv_to_q4(pos: usize, mv_component: i32, luma: bool) -> i32 {
1932 (pos as i32) * 16 + mv_component * if luma { 2 } else { 1 }
1933}
1934
1935/// `CLASS0_SIZE << (class + 2)`, mirroring `tile::mv_class_base` (private to
1936/// that module): the magnitude an `MV_CLASS_n` component's own bits start
1937/// counting from.
1938fn mv_class_base(class: usize) -> i32 {
1939 if class == 0 { 0 } else { 2i32 << (class + 2) }
1940}
1941
1942/// The class a pre-offset magnitude `z` (`|diff| - 1`) falls in, mirroring
1943/// `tile::mv_class_of`.
1944fn mv_class_of(z: i32) -> usize {
1945 let mut class = 0;
1946 while class < 10 && mv_class_base(class + 1) <= z {
1947 class += 1;
1948 }
1949 class
1950}
1951
1952/// What [`crate::tile::write_mv_component`] (private to that module) would
1953/// spend coding one non-zero motion vector component, against the same
1954/// static default CDFs the writer starts a frame from — the same
1955/// static-table approximation [`mode_bits`] costs the luma mode symbol
1956/// through, not the tile writer's own adapting state, which this encoder has
1957/// no way to read without duplicating it block for block.
1958///
1959/// Returns `None` when `diff` needs the eighth-pel precision this crate's
1960/// frames never carry (`allow_high_precision_mv` is always off), which is
1961/// what [`round_to_valid_mv`] exists to avoid ever happening.
1962fn mv_component_bits(diff: i32) -> Option<f64> {
1963 let mag = diff.unsigned_abs() as i32;
1964 let z = mag - 1;
1965 if z & 1 == 0 {
1966 return None;
1967 }
1968 let mut bits = symbol_bits(&cdf::MV_SIGN, usize::from(diff < 0));
1969 let class = mv_class_of(z);
1970 bits += symbol_bits(&cdf::MV_CLASS, class);
1971 let local = z - mv_class_base(class);
1972 if class == 0 {
1973 let bit = (local >> 3) & 1;
1974 let fr = (local >> 1) & 3;
1975 bits += symbol_bits(&cdf::MV_CLASS0_BIT, bit as usize);
1976 bits += symbol_bits(&cdf::MV_CLASS0_FR[bit as usize], fr as usize);
1977 } else {
1978 let d = local >> 3;
1979 let fr = (local >> 1) & 3;
1980 for i in 0..class {
1981 bits += symbol_bits(&cdf::MV_BIT[i], ((d >> i) & 1) as usize);
1982 }
1983 bits += symbol_bits(&cdf::MV_FR, fr as usize);
1984 }
1985 Some(bits)
1986}
1987
1988/// What [`crate::tile::write_mv`] (private to that module) would spend
1989/// coding `mv` as a residual against `pred`: the joint symbol naming which
1990/// components differ, then each differing component. `None` under the same
1991/// condition [`mv_component_bits`] returns `None`.
1992fn mv_residual_bits(mv: (i32, i32), pred: (i32, i32)) -> Option<f64> {
1993 let diff = (mv.0 - pred.0, mv.1 - pred.1);
1994 let joint = match (diff.0 != 0, diff.1 != 0) {
1995 (false, false) => 0,
1996 (false, true) => 1,
1997 (true, false) => 2,
1998 (true, true) => 3,
1999 };
2000 let mut bits = symbol_bits(&cdf::MV_JOINT, joint);
2001 for d in [diff.0, diff.1] {
2002 if d != 0 {
2003 bits += mv_component_bits(d)?;
2004 }
2005 }
2006 Some(bits)
2007}
2008
2009/// Rounds `mv` so that its residual against `pred` is one
2010/// [`crate::tile::write_mv_component`] can actually code: each component's
2011/// difference is either zero or has an even magnitude (the eighth-pel bit
2012/// `allow_high_precision_mv` off always infers as one forces the coded
2013/// magnitude odd one step further in, which comes out even here since this
2014/// crate's motion search works in whole units of that same step). Rounding
2015/// down keeps every coded MV — and so every `nearest_mv` a later block's
2016/// stack votes with — built from an even displacement from `(0, 0)`, so the
2017/// invariant holds without this function seeing the whole stack.
2018fn round_to_valid_mv(mv: (i32, i32), pred: (i32, i32)) -> (i32, i32) {
2019 let round = |m: i32, p: i32| {
2020 let diff = m - p;
2021 let mag = diff.unsigned_abs() as i32;
2022 let even = mag - mag % 2;
2023 if even == 0 {
2024 p
2025 } else {
2026 p + even * diff.signum()
2027 }
2028 };
2029 (round(mv.0, pred.0), round(mv.1, pred.1))
2030}
2031
2032/// Predicts one `side`-square block by motion compensation from `reference`
2033/// at `mv` (1/8-pel), then codes it through [`Plane::code_from_prediction`].
2034#[allow(clippy::too_many_arguments)]
2035fn mc_trial(
2036 plane: &Plane,
2037 x: usize,
2038 y: usize,
2039 side: usize,
2040 mv: (i32, i32),
2041 luma: bool,
2042 reference: &[u8],
2043 stride: usize,
2044 ref_width: usize,
2045 ref_height: usize,
2046 skip: bool,
2047 base_q_idx: u8,
2048 deadzone: f64,
2049 set: TxbSet,
2050) -> Trial {
2051 let x_q4 = mv_to_q4(x, mv.1, luma);
2052 let y_q4 = mv_to_q4(y, mv.0, luma);
2053 let mut prediction = vec![0u8; side * side];
2054 mc::predict(
2055 reference,
2056 stride,
2057 ref_width,
2058 ref_height,
2059 x_q4,
2060 y_q4,
2061 side,
2062 side,
2063 &mut prediction,
2064 );
2065 plane.code_from_prediction(x, y, side, &prediction, skip, base_q_idx, deadzone, set)
2066}
2067
2068/// Codes one 32x32 block of an inter frame as whichever costs least of: each
2069/// intra mode [`Search::modes`] offers (predicted exactly as a key frame's
2070/// block is), `NEARESTMV`, and `NEWMV` searched from `reference` by
2071/// [`motion::search`] and seeded by `stack.pred_mv` — both inter candidates
2072/// coding a real residual (`skip: false`) whenever one prices out cheaper
2073/// than the all-skip candidate, now that `sb_coeff_inter_frame_tile`'s
2074/// missing inter `tx_type` symbol (the desync this function's candidates
2075/// used to route around; see `crate::cdf_state::TxbSet::Luma32Inter`) is
2076/// fixed.
2077///
2078/// The symbol costs this ranks candidates by use fixed contexts (0) for
2079/// `skip`, `intra_inter` and `single_ref` — the tile writer's actual
2080/// contexts for those come from its own neighbour bookkeeping
2081/// (`tile::Neighbours`), which is private to that module and not worth
2082/// duplicating for three one-or-two-bit symbols; `new_mv`/`ref_mv`/`zero_mv`/
2083/// `drl_mode` contexts come straight from `stack`, which is exact, because
2084/// [`find_mv_stack`] is public and this function is handed the same `MvStack`
2085/// the tile writer derives from the same grid state.
2086#[allow(clippy::too_many_arguments)]
2087fn search_inter_block(
2088 luma: &mut Plane,
2089 chroma: &mut [Plane; 2],
2090 (x, y): (usize, usize),
2091 search: &Search,
2092 mode_bits: &[f64; 13],
2093 reference: &Picture,
2094 stack: &MvStack,
2095) -> BlockCoeffs {
2096 let (luma_set, chroma_set) = (TxbSet::Luma32, TxbSet::Chroma16);
2097 let reach = Reach::of(BLOCK, x, y, luma.true_width, luma.true_height);
2098
2099 // skip / intra_inter symbol costs at a fixed context -- see this
2100 // function's doc comment.
2101 let skip_bits = |skip: bool| symbol_bits(&cdf::SKIP[0], usize::from(skip));
2102 let intra_inter_bits = |inter: bool| symbol_bits(&cdf::INTRA_INTER[0], usize::from(inter));
2103 let single_ref_bits = symbol_bits(&cdf::SINGLE_REF[0][0], 0)
2104 + symbol_bits(&cdf::SINGLE_REF[0][2], 0)
2105 + symbol_bits(&cdf::SINGLE_REF[0][3], 0);
2106
2107 struct Candidate {
2108 cost: f64,
2109 luma: Trial,
2110 u: Trial,
2111 v: Trial,
2112 mode: u8,
2113 skip: bool,
2114 inter: Option<InterInfo>,
2115 }
2116 let mut best: Option<Candidate> = None;
2117 let mut consider = |candidate: Candidate| {
2118 if best.as_ref().is_none_or(|b| candidate.cost < b.cost) {
2119 best = Some(candidate);
2120 }
2121 };
2122
2123 // The chroma trial an intra candidate prices does not depend on `mode`
2124 // at all -- both planes always code `DC_PRED` here (a coding choice this
2125 // search inherited, not this loop's to second-guess) at the same `reach:
2126 // Reach::none()` -- so it is the same call with the same inputs on every
2127 // one of the thirteen iterations below; run it once and reuse the result
2128 // rather than repeat an already-priced transform/quantize/entropy call
2129 // twelve times for nothing (bit-identical: the value each iteration
2130 // reads back is exactly what it used to recompute).
2131 let u_trial = chroma[0].trial(
2132 At {
2133 x: x / 2,
2134 y: y / 2,
2135 side: BLOCK / 2,
2136 reach: Reach::none(),
2137 set: chroma_set,
2138 },
2139 DC_PRED,
2140 search.base_q_idx,
2141 search.deadzone,
2142 );
2143 let v_trial = chroma[1].trial(
2144 At {
2145 x: x / 2,
2146 y: y / 2,
2147 side: BLOCK / 2,
2148 reach: Reach::none(),
2149 set: chroma_set,
2150 },
2151 DC_PRED,
2152 search.base_q_idx,
2153 search.deadzone,
2154 );
2155
2156 let intra_modes: Vec<u8> = match search.top_k {
2157 Some(k) if k < search.modes.len() => {
2158 let scored = luma.intra_scores(
2159 At {
2160 x,
2161 y,
2162 side: BLOCK,
2163 reach,
2164 set: luma_set,
2165 },
2166 search.modes,
2167 mode_bits,
2168 search.lambda,
2169 );
2170 prune_by_sad(search.modes, scored, k)
2171 }
2172 _ => search.modes.to_vec(),
2173 };
2174 for &mode in &intra_modes {
2175 let luma_trial = luma.trial(
2176 At {
2177 x,
2178 y,
2179 side: BLOCK,
2180 reach,
2181 set: luma_set,
2182 },
2183 mode,
2184 search.base_q_idx,
2185 search.deadzone,
2186 );
2187 let u = u_trial.clone();
2188 let v = v_trial.clone();
2189 let cost = luma_trial.sse
2190 + u.sse
2191 + v.sse
2192 + search.lambda
2193 * (luma_trial.bits
2194 + u.bits
2195 + v.bits
2196 + mode_bits[usize::from(mode)]
2197 + skip_bits(false)
2198 + intra_inter_bits(false));
2199 consider(Candidate {
2200 cost,
2201 luma: luma_trial,
2202 u,
2203 v,
2204 mode,
2205 skip: false,
2206 inter: None,
2207 });
2208 }
2209
2210 // The reference frame buffer a spec decoder holds is exactly the true
2211 // (unpadded) coded extent -- a superblock whose partition stops early at
2212 // `has_cols`/`has_rows` never codes syntax for the padding columns/rows
2213 // beyond it, so those samples are never part of the decoded picture.
2214 // Motion compensation clamps reads to that true extent (spec 7.11.3.4's
2215 // reference sample position clamp), not to this crate's own
2216 // padded-to-`SUPERBLOCK` coding surface -- passing the padded width/height
2217 // here would let a fractional-pel read past the true edge pick up this
2218 // encoder's own uncoded padding instead of the true edge's replicated
2219 // value a decoder computes.
2220 let ref_luma = (
2221 &reference.y,
2222 reference.width,
2223 luma.true_width,
2224 luma.true_height,
2225 );
2226 let ref_u = (
2227 &reference.u,
2228 reference.width / 2,
2229 chroma[0].true_width,
2230 chroma[0].true_height,
2231 );
2232 let ref_v = (
2233 &reference.v,
2234 reference.width / 2,
2235 chroma[1].true_width,
2236 chroma[1].true_height,
2237 );
2238 let mode_bits_inter = symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 1) // not NEWMV
2239 + symbol_bits(&cdf::ZERO_MV[stack.zero_mv_ctx], 1) // not zero
2240 + symbol_bits(&cdf::REF_MV[stack.ref_mv_ctx], 0); // NEARESTMV
2241
2242 // The NEARESTMV candidate: `skip` is decided below from whether its
2243 // trial actually found a nonzero level, once its residual is priced
2244 // against the same CDFs the tile writer codes it with.
2245 {
2246 let mv = stack.nearest_mv;
2247 let luma_trial = mc_trial(
2248 luma,
2249 x,
2250 y,
2251 BLOCK,
2252 mv,
2253 true,
2254 ref_luma.0,
2255 ref_luma.1,
2256 ref_luma.2,
2257 ref_luma.3,
2258 false,
2259 search.base_q_idx,
2260 search.deadzone,
2261 luma_set,
2262 );
2263 let u = mc_trial(
2264 &chroma[0],
2265 x / 2,
2266 y / 2,
2267 BLOCK / 2,
2268 mv,
2269 false,
2270 ref_u.0,
2271 ref_u.1,
2272 ref_u.2,
2273 ref_u.3,
2274 false,
2275 search.base_q_idx,
2276 search.deadzone,
2277 chroma_set,
2278 );
2279 let v = mc_trial(
2280 &chroma[1],
2281 x / 2,
2282 y / 2,
2283 BLOCK / 2,
2284 mv,
2285 false,
2286 ref_v.0,
2287 ref_v.1,
2288 ref_v.2,
2289 ref_v.3,
2290 false,
2291 search.base_q_idx,
2292 search.deadzone,
2293 chroma_set,
2294 );
2295 let skip = luma_trial.levels.iter().all(|&l| l == 0)
2296 && u.levels.iter().all(|&l| l == 0)
2297 && v.levels.iter().all(|&l| l == 0);
2298 let cost = luma_trial.sse
2299 + u.sse
2300 + v.sse
2301 + search.lambda
2302 * (skip_bits(skip)
2303 + intra_inter_bits(true)
2304 + single_ref_bits
2305 + mode_bits_inter
2306 + if skip {
2307 0.0
2308 } else {
2309 luma_trial.bits + u.bits + v.bits
2310 });
2311 consider(Candidate {
2312 cost,
2313 luma: luma_trial,
2314 u,
2315 v,
2316 mode: DC_PRED,
2317 skip,
2318 inter: Some(InterInfo {
2319 mode: InterMode::NearestMv,
2320 mv,
2321 }),
2322 });
2323 }
2324
2325 let source_block = luma.source_block(x, y, BLOCK);
2326 #[cfg(test)]
2327 let t = std::time::Instant::now();
2328 let found = motion::search(
2329 ref_luma.0,
2330 ref_luma.1,
2331 ref_luma.2,
2332 ref_luma.3,
2333 &source_block,
2334 x,
2335 y,
2336 BLOCK,
2337 BLOCK,
2338 stack.pred_mv,
2339 search.lambda,
2340 );
2341 #[cfg(test)]
2342 stage_add(0, t.elapsed());
2343 let mv = round_to_valid_mv(found.mv, stack.pred_mv);
2344 if let Some(mv_bits) = mv_residual_bits(mv, stack.pred_mv) {
2345 let luma_trial = mc_trial(
2346 luma,
2347 x,
2348 y,
2349 BLOCK,
2350 mv,
2351 true,
2352 ref_luma.0,
2353 ref_luma.1,
2354 ref_luma.2,
2355 ref_luma.3,
2356 false,
2357 search.base_q_idx,
2358 search.deadzone,
2359 luma_set,
2360 );
2361 let u = mc_trial(
2362 &chroma[0],
2363 x / 2,
2364 y / 2,
2365 BLOCK / 2,
2366 mv,
2367 false,
2368 ref_u.0,
2369 ref_u.1,
2370 ref_u.2,
2371 ref_u.3,
2372 false,
2373 search.base_q_idx,
2374 search.deadzone,
2375 chroma_set,
2376 );
2377 let v = mc_trial(
2378 &chroma[1],
2379 x / 2,
2380 y / 2,
2381 BLOCK / 2,
2382 mv,
2383 false,
2384 ref_v.0,
2385 ref_v.1,
2386 ref_v.2,
2387 ref_v.3,
2388 false,
2389 search.base_q_idx,
2390 search.deadzone,
2391 chroma_set,
2392 );
2393 let drl_bits = if stack.entries.len() > 1 {
2394 symbol_bits(&cdf::DRL_MODE[stack.drl_ctx[0]], 0)
2395 } else {
2396 0.0
2397 };
2398 let skip = luma_trial.levels.iter().all(|&l| l == 0)
2399 && u.levels.iter().all(|&l| l == 0)
2400 && v.levels.iter().all(|&l| l == 0);
2401 let cost = luma_trial.sse
2402 + u.sse
2403 + v.sse
2404 + search.lambda
2405 * (skip_bits(skip)
2406 + intra_inter_bits(true)
2407 + single_ref_bits
2408 + symbol_bits(&cdf::NEW_MV[stack.new_mv_ctx], 0)
2409 + drl_bits
2410 + mv_bits
2411 + if skip {
2412 0.0
2413 } else {
2414 luma_trial.bits + u.bits + v.bits
2415 });
2416 consider(Candidate {
2417 cost,
2418 luma: luma_trial,
2419 u,
2420 v,
2421 mode: DC_PRED,
2422 skip,
2423 inter: Some(InterInfo {
2424 mode: InterMode::NewMv,
2425 mv,
2426 }),
2427 });
2428 }
2429
2430 let best = best.expect("the search offers at least the intra modes");
2431 luma.commit(x, y, BLOCK, &best.luma);
2432 chroma[0].commit(x / 2, y / 2, BLOCK / 2, &best.u);
2433 chroma[1].commit(x / 2, y / 2, BLOCK / 2, &best.v);
2434 BlockCoeffs {
2435 luma: coeffs(&best.luma.levels, BLOCK),
2436 u: coeffs(&best.u.levels, BLOCK / 2),
2437 v: coeffs(&best.v.levels, BLOCK / 2),
2438 mode: best.mode,
2439 skip: best.skip,
2440 inter: best.inter,
2441 eight: None,
2442 }
2443}
2444
2445/// Encodes one picture as an inter frame predicting from `reference`'s
2446/// reconstruction, which the caller decoded (or, for the frame right after
2447/// the key frame, is the key frame's own reconstruction).
2448pub(crate) fn encode_inter_frame(
2449 picture: &Picture,
2450 reference: &Picture,
2451 base_q_idx: u8,
2452 deadzone: f64,
2453 order_hint: u32,
2454 render: (usize, usize),
2455) -> Result<Encoded> {
2456 picture.check()?;
2457 if !picture.width.is_multiple_of(SUPERBLOCK) || !picture.height.is_multiple_of(SUPERBLOCK) {
2458 return Err(Error::unsupported(
2459 "AV1 encode",
2460 "an inter frame is coded only for a picture that is a whole number \
2461 of 64x64 superblocks -- the inter tile writer never splits a \
2462 superblock's partition below that",
2463 ));
2464 }
2465 if reference.width != picture.width || reference.height != picture.height {
2466 return Err(Error::unsupported(
2467 "AV1 encode",
2468 "the reference picture must be the same size as the one being coded",
2469 ));
2470 }
2471
2472 // The single slot this crate's inter frames ever predict from or
2473 // refresh (`inter_frame_headers`'s contract): every frame both reads and
2474 // overwrites slot 0, so the frame just coded is always what the next one
2475 // predicts against.
2476 const LAST_SLOT: u8 = 0;
2477 // `render`, not `picture.width`/`picture.height`: `picture` here is
2478 // already padded to a whole number of superblocks (`encode_sequence`'s
2479 // `padded_to(SUPERBLOCK)`), and the header's `mi_cols`/`mi_rows` (and so
2480 // every true-edge clamp downstream) must come from the frame's real,
2481 // unpadded size, same as `key_frame_headers_colour` takes `render` and
2482 // not the padded picture in `encode_key_frame_inner`.
2483 let (seq, mut header) =
2484 inter_frame_headers(render.0, render.1, base_q_idx, order_hint, LAST_SLOT)?;
2485 header.render_width = render.0 as u32;
2486 header.render_height = render.1 as u32;
2487
2488 let (true_width, true_height) = (header.mi_cols as usize * 4, header.mi_rows as usize * 4);
2489 let mut luma = Plane {
2490 source: &picture.y,
2491 reconstruction: vec![128; picture.y.len()],
2492 width: picture.width,
2493 height: picture.height,
2494 true_width,
2495 true_height,
2496 };
2497 let mut chroma = [
2498 Plane {
2499 source: &picture.u,
2500 reconstruction: vec![128; picture.u.len()],
2501 width: picture.width / 2,
2502 height: picture.height / 2,
2503 true_width: true_width / 2,
2504 true_height: true_height / 2,
2505 },
2506 Plane {
2507 source: &picture.v,
2508 reconstruction: vec![128; picture.v.len()],
2509 width: picture.width / 2,
2510 height: picture.height / 2,
2511 true_width: true_width / 2,
2512 true_height: true_height / 2,
2513 },
2514 ];
2515
2516 let step = f64::from(ac_q(8, i32::from(base_q_idx))) / 8.0;
2517 let search = Search {
2518 base_q_idx,
2519 deadzone,
2520 lambda: lambda_scale() * step * step,
2521 modes: &KEY_FRAME_MODES,
2522 top_k: prune_top_k_inter(),
2523 };
2524 let mode_bits_table = inter_mode_bits();
2525
2526 // The true grid ([`crate::tile::block_grid`]'s ceiling), not the padded
2527 // coding surface's: `blocks` carries one entry per 32x32 block the tile
2528 // writer will actually visit, same count it checks `blocks.len()`
2529 // against, which is fewer than the padded surface's own block count
2530 // whenever the true size is not a 64x64 multiple.
2531 let (cols, rows) = crate::tile::block_grid(header.mi_cols, header.mi_rows);
2532 let (cols, rows) = (cols as usize, rows as usize);
2533 let (sb_cols, sb_rows) = (cols.div_ceil(2), rows.div_ceil(2));
2534 let (mi_cols, mi_rows) = (header.mi_cols as usize, header.mi_rows as usize);
2535 let mut grid = MiGrid::new(mi_cols, mi_rows);
2536 let mut blocks = vec![Quadrant::Whole(BlockCoeffs::default()); cols * rows];
2537
2538 for sb_r in 0..sb_rows {
2539 for sb_c in 0..sb_cols {
2540 for quadrant in 0..4 {
2541 let (r32, c32) = (sb_r * 2 + quadrant / 2, sb_c * 2 + quadrant % 2);
2542 // Same filter as the tile writer's: a quadrant whose own mi
2543 // origin is not inside the true frame is never coded.
2544 if r32 >= rows || c32 >= cols {
2545 continue;
2546 }
2547 // spec `decode_partition`'s hasRows/hasCols recomputed at this
2548 // 32x32 block's own half (`crate::tile::has_half`), same as
2549 // the key frame search: the true frame edge can fall inside a
2550 // quadrant a superblock-level check already let through, and
2551 // such a quadrant cannot be left whole -- it must split into
2552 // the 16x16 leaves that are actually inside the true frame
2553 // (`crate::tile::sb_coeff_inter_frame_tile`'s `Quadrant::Split`
2554 // arm).
2555 let (has_cols32, has_rows32) = (
2556 crate::tile::has_half(
2557 c32 as u32 * crate::tile::BLOCK_MI,
2558 crate::tile::BLOCK_MI,
2559 header.mi_cols,
2560 ),
2561 crate::tile::has_half(
2562 r32 as u32 * crate::tile::BLOCK_MI,
2563 crate::tile::BLOCK_MI,
2564 header.mi_rows,
2565 ),
2566 );
2567 if has_cols32 && has_rows32 {
2568 let (x, y) = (c32 * BLOCK, r32 * BLOCK);
2569 let (mi_row, mi_col) = (r32 * 8, c32 * 8);
2570 let stack =
2571 find_mv_stack(&grid, mi_row, mi_col, 8, 8, LAST_FRAME, mi_cols, mi_rows);
2572
2573 let block = search_inter_block(
2574 &mut luma,
2575 &mut chroma,
2576 (x, y),
2577 &search,
2578 &mode_bits_table,
2579 reference,
2580 &stack,
2581 );
2582
2583 for dr in 0..8 {
2584 for dc in 0..8 {
2585 grid.set(
2586 mi_row + dr,
2587 mi_col + dc,
2588 match block.inter {
2589 Some(info) => MiInfo {
2590 is_inter: true,
2591 ref_frame: LAST_FRAME,
2592 mv: info.mv,
2593 is_new_mv: matches!(info.mode, InterMode::NewMv),
2594 size: 8,
2595 },
2596 // Intra: no vote, but still a coded cell
2597 // -- mvstack's extended-scan coverage
2598 // (`processed_rows`/`processed_cols`)
2599 // must see it (module doc).
2600 None => MiInfo {
2601 is_inter: false,
2602 ref_frame: -1,
2603 mv: (0, 0),
2604 is_new_mv: false,
2605 size: 8,
2606 },
2607 },
2608 );
2609 }
2610 }
2611 blocks[r32 * cols + c32] = Quadrant::Whole(block);
2612 } else {
2613 // The sub-positions actually inside the true frame, same
2614 // filter as `sb_coeff_inter_frame_tile`'s `sub_positions`.
2615 let sub_positions: Vec<(usize, usize)> = (0..4)
2616 .map(|i| (r32 * 2 + i / 2, c32 * 2 + i % 2))
2617 .filter(|&(sr, sc)| {
2618 (sr as u32) * crate::tile::SUB_MI < header.mi_rows
2619 && (sc as u32) * crate::tile::SUB_MI < header.mi_cols
2620 })
2621 .collect();
2622 // Each leaf searches intra against its own `NEARESTMV`
2623 // candidate (`code_square_inter`), same real-inter choice
2624 // `search_inter_block` makes for a whole 32x32 block, at
2625 // this leaf's own 4x4-mi mv-stack window -- unless the
2626 // leaf's own half itself straddles the true edge, which
2627 // it codes as two (or one, at a true corner) 8x8 leaves
2628 // (`crate::tile::write_leaf8`'s inter counterpart),
2629 // mirroring the key frame search's straddling-16x16
2630 // handling above (lane-av1inter8).
2631 let mut leaves = Vec::with_capacity(sub_positions.len());
2632 for (sr, sc) in sub_positions {
2633 let (has_cols16, has_rows16) = (
2634 crate::tile::has_half(
2635 sc as u32 * crate::tile::SUB_MI,
2636 crate::tile::SUB_MI,
2637 header.mi_cols,
2638 ),
2639 crate::tile::has_half(
2640 sr as u32 * crate::tile::SUB_MI,
2641 crate::tile::SUB_MI,
2642 header.mi_rows,
2643 ),
2644 );
2645 if !has_cols16 && !has_rows16 {
2646 return Err(Error::unsupported(
2647 "AV1 encode",
2648 format!(
2649 "the 16x16 block at ({sc},{sr}) straddles the true \
2650 frame edge in a way that needs a rectangular \
2651 (HORZ/VERT) transform this encoder does not code yet"
2652 ),
2653 ));
2654 }
2655 if has_cols16 && has_rows16 {
2656 let (x, y) = (sc * SUB, sr * SUB);
2657 let (mi_row, mi_col) = (sr * 4, sc * 4);
2658 let stack = find_mv_stack(
2659 &grid, mi_row, mi_col, 4, 4, LAST_FRAME, mi_cols, mi_rows,
2660 );
2661 let block = code_square_inter(
2662 &mut luma,
2663 &mut chroma,
2664 (x, y),
2665 SUB,
2666 &search,
2667 &mode_bits_table,
2668 reference,
2669 &stack,
2670 );
2671 for dr in 0..4 {
2672 for dc in 0..4 {
2673 grid.set(
2674 mi_row + dr,
2675 mi_col + dc,
2676 match block.inter {
2677 Some(info) => MiInfo {
2678 is_inter: true,
2679 ref_frame: LAST_FRAME,
2680 mv: info.mv,
2681 is_new_mv: matches!(info.mode, InterMode::NewMv),
2682 size: 4,
2683 },
2684 None => MiInfo {
2685 is_inter: false,
2686 ref_frame: -1,
2687 mv: (0, 0),
2688 is_new_mv: false,
2689 size: 4,
2690 },
2691 },
2692 );
2693 }
2694 }
2695 leaves.push(block);
2696 } else {
2697 let (x_sub, y_sub) = (sc * SUB, sr * SUB);
2698 let (mi_row0, mi_col0) = (sr * 4, sc * 4);
2699 let mut eight = Vec::with_capacity(2);
2700 for i in 0..4 {
2701 let leaf_x = x_sub + (i % 2) * 8;
2702 let leaf_y = y_sub + (i / 2) * 8;
2703 if leaf_x >= luma.true_width || leaf_y >= luma.true_height {
2704 continue;
2705 }
2706 let (mi_row, mi_col) =
2707 (mi_row0 + (i / 2) * 2, mi_col0 + (i % 2) * 2);
2708 let stack = find_mv_stack(
2709 &grid, mi_row, mi_col, 2, 2, LAST_FRAME, mi_cols, mi_rows,
2710 );
2711 let leaf = code_square_inter(
2712 &mut luma,
2713 &mut chroma,
2714 (leaf_x, leaf_y),
2715 8,
2716 &search,
2717 &mode_bits_table,
2718 reference,
2719 &stack,
2720 );
2721 for dr in 0..2 {
2722 for dc in 0..2 {
2723 grid.set(
2724 mi_row + dr,
2725 mi_col + dc,
2726 match leaf.inter {
2727 Some(info) => MiInfo {
2728 is_inter: true,
2729 ref_frame: LAST_FRAME,
2730 mv: info.mv,
2731 is_new_mv: matches!(
2732 info.mode,
2733 InterMode::NewMv
2734 ),
2735 size: 2,
2736 },
2737 None => MiInfo {
2738 is_inter: false,
2739 ref_frame: -1,
2740 mv: (0, 0),
2741 is_new_mv: false,
2742 size: 2,
2743 },
2744 },
2745 );
2746 }
2747 }
2748 eight.push(leaf);
2749 }
2750 leaves.push(BlockCoeffs {
2751 eight: Some(eight),
2752 ..BlockCoeffs::default()
2753 });
2754 }
2755 }
2756 blocks[r32 * cols + c32] = Quadrant::Split(leaves);
2757 }
2758 }
2759 }
2760 }
2761
2762 let modes = blocks
2763 .iter()
2764 .flat_map(Quadrant::blocks)
2765 .map(|b| b.mode)
2766 .collect::<Vec<_>>();
2767 let inter_block_share = blocks
2768 .iter()
2769 .flat_map(Quadrant::blocks)
2770 .filter(|b| b.inter.is_some())
2771 .count() as f64
2772 / modes.len() as f64;
2773 let tile = sb_coeff_inter_frame_tile(header.mi_cols, header.mi_rows, base_q_idx, &blocks)?;
2774 let mut stream = temporal_delimiter();
2775 stream.extend_from_slice(&frame_obu(&seq, &header, &tile)?);
2776
2777 let [u, v] = chroma;
2778 Ok(Encoded {
2779 stream,
2780 modes,
2781 inter_block_share,
2782 reconstruction: Picture {
2783 width: luma.width,
2784 height: luma.height,
2785 y: luma.reconstruction,
2786 u: u.reconstruction,
2787 v: v.reconstruction,
2788 },
2789 tile,
2790 mi_cols: header.mi_cols,
2791 mi_rows: header.mi_rows,
2792 base_q_idx,
2793 })
2794}
2795
2796/// What [`encode_sequence`] produced: the concatenated AV1 stream -- a key
2797/// frame's temporal unit followed by one inter frame's temporal unit per
2798/// remaining picture, all sharing the key frame's sequence header -- and
2799/// each frame's own [`Encoded`], in coding order.
2800#[derive(Clone, Debug)]
2801pub struct EncodedSequence {
2802 /// The whole stream: `frames[0].stream` (a temporal delimiter, the
2803 /// sequence header and the key frame) followed by each later frame's
2804 /// `stream` (a temporal delimiter and that frame's OBU alone; it reuses
2805 /// the sequence header the key frame carried).
2806 pub stream: Vec<u8>,
2807 /// One entry per picture, in coding order.
2808 pub frames: Vec<Encoded>,
2809}
2810
2811/// Encodes a sequence of pictures as a key frame followed by one inter frame
2812/// per remaining picture, each predicting from the previous frame's own
2813/// decoded reconstruction — never from the source, which is what a decoder
2814/// cannot see. Every picture must be the same even size (any even width and
2815/// height — each is padded to a whole number of 64x64 superblocks
2816/// internally, which is what lets an inter frame's reference always match
2817/// the frame being coded against it), and `pictures` must be non-empty.
2818///
2819/// # Errors
2820/// Returns an error when `pictures` is empty, when any picture besides the
2821/// first is not the same size as the first, or under the same conditions
2822/// [`encode_key_frame`] and the inter frame path do.
2823pub fn encode_sequence(
2824 pictures: &[Picture],
2825 base_q_idx: u8,
2826 deadzone: f64,
2827) -> Result<EncodedSequence> {
2828 let Some((first, rest)) = pictures.split_first() else {
2829 return Err(Error::unsupported(
2830 "AV1 encode",
2831 "a sequence needs at least one picture",
2832 ));
2833 };
2834 first.check_even()?;
2835 let render = (first.width, first.height);
2836 // The key frame and every inter frame after it are coded at the same
2837 // padded size, so the reference each inter frame predicts from -- the
2838 // previous frame's own uncropped reconstruction, at the size a decoder's
2839 // reference buffer actually holds -- always matches the frame being
2840 // coded against it.
2841 let key = encode_key_frame_inner(
2842 &first.padded_to(SUPERBLOCK),
2843 base_q_idx,
2844 deadzone,
2845 &KEY_FRAME_MODES,
2846 split_blocks(),
2847 render,
2848 unspecified_color_config(),
2849 )?;
2850 let mut stream = key.stream.clone();
2851 let mut reference = key.reconstruction.clone();
2852 let mut frames = vec![crop_encoded(&key, render.0, render.1)];
2853 for (i, picture) in rest.iter().enumerate() {
2854 picture.check_even()?;
2855 if (picture.width, picture.height) != render {
2856 return Err(Error::unsupported(
2857 "AV1 encode",
2858 "every picture in a sequence must be the same size as the first",
2859 ));
2860 }
2861 let order_hint = (i + 1) as u32;
2862 let inter = encode_inter_frame(
2863 &picture.padded_to(SUPERBLOCK),
2864 &reference,
2865 base_q_idx,
2866 deadzone,
2867 order_hint,
2868 render,
2869 )?;
2870 stream.extend_from_slice(&inter.stream);
2871 reference = inter.reconstruction.clone();
2872 frames.push(crop_encoded(&inter, render.0, render.1));
2873 }
2874 Ok(EncodedSequence { stream, frames })
2875}
2876
2877#[cfg(test)]
2878mod tests {
2879 use super::*;
2880 use crate::intra::{D45_PRED, D135_PRED, H_PRED, KEY_FRAME_MODES, NON_DIRECTIONAL, V_PRED};
2881 use std::io::Write;
2882 use std::process::{Command, Stdio};
2883
2884 fn have_ffmpeg() -> bool {
2885 Command::new("ffmpeg")
2886 .arg("-version")
2887 .stdout(Stdio::null())
2888 .stderr(Stdio::null())
2889 .status()
2890 .is_ok_and(|s| s.success())
2891 }
2892
2893 /// Decodes an AV1 OBU stream with ffmpeg and hands back the three planes.
2894 fn ffmpeg_decode(stream: &[u8], width: usize, height: usize) -> Picture {
2895 let mut child = Command::new("ffmpeg")
2896 .args([
2897 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
2898 ])
2899 .stdin(Stdio::piped())
2900 .stdout(Stdio::piped())
2901 .stderr(Stdio::piped())
2902 .spawn()
2903 .expect("ffmpeg failed to start");
2904 child
2905 .stdin
2906 .take()
2907 .expect("ffmpeg stdin")
2908 .write_all(stream)
2909 .expect("writing the stream to ffmpeg");
2910 let out = child.wait_with_output().expect("ffmpeg failed to run");
2911 assert!(
2912 out.status.success(),
2913 "ffmpeg refused the stream: {}",
2914 String::from_utf8_lossy(&out.stderr)
2915 );
2916 let (luma, chroma) = (width * height, width * height / 4);
2917 assert_eq!(
2918 out.stdout.len(),
2919 luma + 2 * chroma,
2920 "expected one 4:2:0 frame"
2921 );
2922 Picture {
2923 width,
2924 height,
2925 y: out.stdout[..luma].to_vec(),
2926 u: out.stdout[luma..luma + chroma].to_vec(),
2927 v: out.stdout[luma + chroma..].to_vec(),
2928 }
2929 }
2930
2931 /// A picture with something of everything in it: a gradient, an edge, a
2932 /// ripple and a block of flat colour, none of them aligned to the block
2933 /// grid.
2934 fn test_card(width: usize, height: usize) -> Picture {
2935 let mut picture = Picture::grey(width, height);
2936 for y in 0..height {
2937 for x in 0..width {
2938 let gradient = x as f64 * 200.0 / width as f64;
2939 let ripple = 30.0
2940 * (x as f64 * std::f64::consts::PI / 23.0).sin()
2941 * (y as f64 * std::f64::consts::PI / 37.0).cos();
2942 let edge = if x > width * 3 / 7 && y > height / 3 {
2943 40.0
2944 } else {
2945 0.0
2946 };
2947 picture.y[y * width + x] =
2948 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u8;
2949 }
2950 }
2951 for y in 0..height / 2 {
2952 for x in 0..width / 2 {
2953 let i = y * width / 2 + x;
2954 picture.u[i] = (100 + (x * 60 / (width / 2))) as u8;
2955 picture.v[i] = (200 - (y * 80 / (height / 2))) as u8;
2956 }
2957 }
2958 picture
2959 }
2960
2961 fn psnr(a: &[u8], b: &[u8]) -> f64 {
2962 let squared: f64 = a
2963 .iter()
2964 .zip(b)
2965 .map(|(&x, &y)| {
2966 let d = f64::from(x) - f64::from(y);
2967 d * d
2968 })
2969 .sum();
2970 if squared == 0.0 {
2971 return f64::INFINITY;
2972 }
2973 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
2974 }
2975
2976 /// The claim the whole encoder rests on: what a decoder produces is what
2977 /// the encoder said it would, sample for sample, on every plane.
2978 ///
2979 /// Prediction reads the reconstruction, so a single sample of drift
2980 /// anywhere would spread into every block below and to the right of it —
2981 /// which is why this is an equality and not a tolerance.
2982 #[test]
2983 fn ffmpeg_decodes_exactly_what_the_encoder_reconstructed() {
2984 if !have_ffmpeg() {
2985 eprintln!("SKIP ffmpeg_decodes_exactly_what_the_encoder_reconstructed: no ffmpeg");
2986 return;
2987 }
2988 for &(width, height) in &[(64usize, 64usize), (96, 64), (160, 96), (32, 48)] {
2989 let picture = test_card(width, height);
2990 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
2991 let decoded = ffmpeg_decode(&encoded.stream, width, height);
2992 assert_eq!(
2993 decoded.y, encoded.reconstruction.y,
2994 "{width}x{height}: luma"
2995 );
2996 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
2997 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
2998 }
2999 // One q index from each of the four coefficient-CDF contexts
3000 // (0..=20, 21..=60, 61..=120, 121..=255), on a single frame size.
3001 let (width, height) = (64usize, 64usize);
3002 let picture = test_card(width, height);
3003 for &q in &[15u8, 45, 100, 200] {
3004 let encoded = encode_key_frame(&picture, q, 0.5).unwrap();
3005 let decoded = ffmpeg_decode(&encoded.stream, width, height);
3006 assert_eq!(decoded.y, encoded.reconstruction.y, "q={q}: luma");
3007 assert_eq!(decoded.u, encoded.reconstruction.u, "q={q}: U");
3008 assert_eq!(decoded.v, encoded.reconstruction.v, "q={q}: V");
3009 }
3010 }
3011
3012 /// The minimal repro that isolated the inter-residual desync: a key frame
3013 /// followed by one inter frame whose single superblock carries one
3014 /// `NEARESTMV` block (`mv == (0, 0)`) with exactly one nonzero luma
3015 /// coefficient, its three sibling blocks all `skip: true`. Before the
3016 /// `is_inter` transform-block fix this broke ffmpeg/dav1d ("Invalid data
3017 /// found when processing input") even though every symbol either block
3018 /// codes is otherwise proven (all-skip inter blocks decode clean, and the
3019 /// same coefficient syntax decodes clean on every intra key-frame gate).
3020 #[test]
3021 fn a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean() {
3022 if !have_ffmpeg() {
3023 eprintln!(
3024 "SKIP a_nearestmv_block_with_one_nonzero_coefficient_decodes_clean: no ffmpeg"
3025 );
3026 return;
3027 }
3028 let (width, height) = (64usize, 64usize);
3029 let picture = Picture::grey(width, height);
3030 let key = encode_key_frame(&picture, 100, 0.5).unwrap();
3031
3032 let (seq, _) = key_frame_headers(width, height, 100).unwrap();
3033 let (_, inter_header) = inter_frame_headers(width, height, 100, 1, 0).unwrap();
3034
3035 let residual_block = BlockCoeffs {
3036 luma: vec![Coeff {
3037 row: 0,
3038 col: 0,
3039 level: 4,
3040 }],
3041 u: Vec::new(),
3042 v: Vec::new(),
3043 mode: 0,
3044 skip: false,
3045 eight: None,
3046 inter: Some(InterInfo {
3047 mode: InterMode::NearestMv,
3048 mv: (0, 0),
3049 }),
3050 };
3051 let skipped_block = BlockCoeffs {
3052 skip: true,
3053 inter: Some(InterInfo {
3054 mode: InterMode::NearestMv,
3055 mv: (0, 0),
3056 }),
3057 ..BlockCoeffs::default()
3058 };
3059 let blocks = vec![
3060 Quadrant::Whole(residual_block),
3061 Quadrant::Whole(skipped_block.clone()),
3062 Quadrant::Whole(skipped_block.clone()),
3063 Quadrant::Whole(skipped_block),
3064 ];
3065 let tile =
3066 sb_coeff_inter_frame_tile(inter_header.mi_cols, inter_header.mi_rows, 100, &blocks)
3067 .unwrap();
3068
3069 // `key.stream` is already a temporal delimiter, the sequence header
3070 // and the key frame's own OBU (`encode_key_frame` built it from the
3071 // same `key_frame_headers(width, height, 100)` this test calls), so
3072 // the inter frame's OBU is appended straight onto it rather than
3073 // re-deriving the key frame's tile bytes.
3074 let mut stream = key.stream.clone();
3075 stream.extend_from_slice(&temporal_delimiter());
3076 stream.extend_from_slice(&frame_obu(&seq, &inter_header, &tile).unwrap());
3077
3078 ffmpeg_decode_sequence(&stream, width, height, 2);
3079 }
3080
3081 /// `ffprobe`'s reported `width,height` for one OBU stream -- the coded
3082 /// frame size an AV1 decoder allocates, not necessarily the render size
3083 /// (see [`a_frame_round_trips_at_its_own_size`]).
3084 fn ffprobe_size(stream: &[u8]) -> (u32, u32) {
3085 // Distinct per call, not per process: the test binary runs callers on
3086 // parallel threads, and a shared name lets one test's cleanup delete
3087 // the stream another test's ffprobe is still reading.
3088 static PROBE_SEQ: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3089 let path = std::env::temp_dir().join(format!(
3090 "ec-av1-probe-{}-{}.obu",
3091 std::process::id(),
3092 PROBE_SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
3093 ));
3094 let _ = std::fs::remove_file(&path);
3095 std::fs::write(&path, stream).expect("writing the probe stream");
3096 let out = Command::new("ffprobe")
3097 .args([
3098 "-v",
3099 "error",
3100 "-f",
3101 "obu",
3102 "-select_streams",
3103 "v:0",
3104 "-show_entries",
3105 "stream=width,height",
3106 "-of",
3107 "csv=p=0",
3108 ])
3109 .arg(&path)
3110 .output()
3111 .expect("ffprobe failed to run");
3112 let _ = std::fs::remove_file(&path);
3113 assert!(
3114 out.status.success(),
3115 "ffprobe refused the stream: {}",
3116 String::from_utf8_lossy(&out.stderr)
3117 );
3118 let text = String::from_utf8_lossy(&out.stdout);
3119 let mut fields = text.trim().split(',');
3120 let width: u32 = fields.next().expect("ffprobe width").parse().unwrap();
3121 let height: u32 = fields.next().expect("ffprobe height").parse().unwrap();
3122 (width, height)
3123 }
3124
3125 /// A key frame at an arbitrary even size round-trips through ffmpeg over
3126 /// its own render rectangle: [`Encoded::reconstruction`] is exactly the
3127 /// picture's own size, and what ffmpeg decodes over that same top-left
3128 /// region equals it sample for sample.
3129 ///
3130 /// This does not check that `ffprobe` reports the picture's own size,
3131 /// because it does not: `ffprobe`/ffmpeg's AV1 decoder reports the coded
3132 /// (block-padded) frame size, the same one libaom itself would code for
3133 /// a non-block-aligned picture. `render_width`/`render_height` (which
3134 /// this crate sets correctly, spec 5.9.6) is a display hint no AV1
3135 /// decoder is required to crop pixels by, and ffmpeg's does not --
3136 /// checked empirically against ffprobe here and against a real libaom
3137 /// encode separately. So the coded size, not the render size, is what
3138 /// `ffprobe` is asserted to report below.
3139 #[test]
3140 fn a_frame_round_trips_at_its_own_size() {
3141 if !have_ffmpeg() {
3142 eprintln!("SKIP a_frame_round_trips_at_its_own_size: no ffmpeg");
3143 return;
3144 }
3145 // 854x480 is covered separately by
3146 // `an_854x480_picture_round_trips_through_its_padding`, which its own
3147 // doc comment explains was worth keeping as its own test.
3148 for &(width, height) in &[
3149 (1920usize, 1080usize),
3150 (640, 352),
3151 (1280, 720),
3152 (64, 56),
3153 (854, 480),
3154 (216, 96),
3155 (192, 120),
3156 ] {
3157 let picture = test_card(width, height);
3158 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
3159 assert_eq!(
3160 (encoded.reconstruction.width, encoded.reconstruction.height),
3161 (width, height),
3162 "{width}x{height}: reconstruction is cropped to the picture's own size"
3163 );
3164 assert_eq!(
3165 ffprobe_size(&encoded.stream),
3166 (width as u32, height as u32),
3167 "{width}x{height}: ffprobe reports the true (display) size, not the padded one"
3168 );
3169 let decoded = ffmpeg_decode(&encoded.stream, width, height);
3170 assert_eq!(
3171 decoded.y, encoded.reconstruction.y,
3172 "{width}x{height}: luma"
3173 );
3174 assert_eq!(decoded.u, encoded.reconstruction.u, "{width}x{height}: U");
3175 assert_eq!(decoded.v, encoded.reconstruction.v, "{width}x{height}: V");
3176 }
3177 }
3178
3179 /// 854x480 (padded to 864x480, an edge-replication padded key frame) used
3180 /// to diverge from ffmpeg's decode at luma (row 161, col 369): a debug
3181 /// `aomdec` trace of `has_top_right`/`has_bottom_left` at that exact
3182 /// block (a 16x16 at mi (40, 88)) showed libaom indexing its pinned
3183 /// `has_bl_16x16` table at bit 18 (`row * 8 + col`, row=2 col=2), while
3184 /// `Reach::bottom_left` indexed the same table at bit 10 (`row * 4 +
3185 /// col`) -- different bits of an 8-byte table, one true, one false. The
3186 /// stride libaom indexes by is fixed at its compile-time maximum
3187 /// superblock (128px, `MAX_MIB_SIZE_LOG2` = 5), not the actual superblock
3188 /// size a stream uses, so the right stride for a 16x16 or 32x32 block is
3189 /// `128 / side`, not `SUPERBLOCK / side` (64-relative) -- `Reach::of`'s
3190 /// row/col position within the (correctly 64-relative) superblock stayed
3191 /// right, only the table's own row stride was wrong. Fixed in
3192 /// `Reach::table_stride`; not an arithmetic-coder desync (an
3193 /// EC_RNG-per-symbol trace against the same debug decoder found the
3194 /// bitstream byte-for-byte identical to libaom's across all 51188
3195 /// symbols of this frame before this bug was found).
3196 ///
3197 /// Since the frame header started writing the true (unpadded) display
3198 /// size into `frame_width`/`frame_height` rather than the padded coded
3199 /// size, ffmpeg crops to 854x480 on its own -- decoding at the padded
3200 /// 864x480 and cropping ourselves now reads past what ffmpeg actually
3201 /// emits (`av1_common_int.h`'s render/upscale path, mirrored by
3202 /// `av1_frame_size` on the decode side, crops the loop-filtered picture to
3203 /// the header's own size before output).
3204 #[test]
3205 fn an_854x480_picture_round_trips_through_its_padding() {
3206 if !have_ffmpeg() {
3207 return;
3208 }
3209 let (width, height) = (854usize, 480usize);
3210 let picture = test_card(width, height);
3211 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
3212 let decoded = ffmpeg_decode(&encoded.stream, width, height);
3213 assert_eq!(decoded.y, encoded.reconstruction.y, "854x480: luma");
3214 assert_eq!(decoded.u, encoded.reconstruction.u, "854x480: U");
3215 assert_eq!(decoded.v, encoded.reconstruction.v, "854x480: V");
3216 }
3217
3218 /// `Reach::top_right`/`bottom_left` against a from-scratch transcription
3219 /// of libaom's `has_top_right`/`has_bottom_left` (`av1/common/
3220 /// reconintra.c`), for every 16x16 and 32x32 block position across three
3221 /// superblocks square -- interior and every superblock edge (top row,
3222 /// left column, right column, bottom row) both sizes reach. Written to
3223 /// catch the class the `table_stride` bug was: an index stride silently
3224 /// wrong for one block size while looking plausible for the other.
3225 #[test]
3226 fn reach_matches_libaom_has_top_right_and_has_bottom_left() {
3227 // Transcribed from has_top_right/has_bottom_left's row_off==0,
3228 // col_off==0 (whole-transform) path, with MAX_MIB_SIZE_LOG2 = 5 (a
3229 // 128px reference grid) pinned as libaom pins it, independent of the
3230 // 64px superblock this crate actually codes.
3231 fn libaom_top_right(side: usize, x: usize, y: usize, width: usize, height: usize) -> bool {
3232 if y == 0 || x + side >= width {
3233 return false;
3234 }
3235 let (row, col, per_side) = (
3236 (y % SUPERBLOCK) / side,
3237 (x % SUPERBLOCK) / side,
3238 SUPERBLOCK / side,
3239 );
3240 if row == 0 {
3241 return true;
3242 }
3243 if col + 1 == per_side {
3244 return false;
3245 }
3246 let stride = 128 / side;
3247 let index = row * stride + col;
3248 let table = if side == BLOCK {
3249 [95u8, 87].to_vec()
3250 } else {
3251 vec![255, 85, 119, 85, 127, 85, 119, 85]
3252 };
3253 (table[index / 8] >> (index % 8)) & 1 != 0
3254 }
3255
3256 fn libaom_bottom_left(side: usize, x: usize, y: usize, height: usize) -> bool {
3257 if x == 0 || y + side >= height {
3258 return false;
3259 }
3260 let (row, col, per_side) = (
3261 (y % SUPERBLOCK) / side,
3262 (x % SUPERBLOCK) / side,
3263 SUPERBLOCK / side,
3264 );
3265 if col == 0 {
3266 return row * side + side < SUPERBLOCK;
3267 }
3268 if row + 1 == per_side {
3269 return false;
3270 }
3271 let stride = 128 / side;
3272 let index = row * stride + col;
3273 let table = if side == BLOCK {
3274 [4u8, 4].to_vec()
3275 } else {
3276 vec![84, 16, 84, 0, 84, 16, 84, 0]
3277 };
3278 (table[index / 8] >> (index % 8)) & 1 != 0
3279 }
3280
3281 let (width, height) = (SUPERBLOCK * 3, SUPERBLOCK * 3);
3282 for side in [16usize, BLOCK] {
3283 for y in (0..height).step_by(side) {
3284 for x in (0..width).step_by(side) {
3285 let reach = Reach::of(side, x, y, width, height);
3286 assert_eq!(
3287 reach.above_right,
3288 libaom_top_right(side, x, y, width, height),
3289 "side={side} x={x} y={y}: above_right"
3290 );
3291 assert_eq!(
3292 reach.below_left,
3293 libaom_bottom_left(side, x, y, height),
3294 "side={side} x={x} y={y}: below_left"
3295 );
3296 }
3297 }
3298 }
3299 }
3300
3301 /// An odd width or height is refused by name, not by however the padder
3302 /// or the block coder would happen to fail on it.
3303 #[test]
3304 fn odd_dimensions_are_refused() {
3305 for &(width, height) in &[(1921usize, 1080usize), (1920, 1081), (63, 63)] {
3306 let picture = Picture::grey(width, height);
3307 let err = encode_key_frame(&picture, 100, 0.5)
3308 .expect_err(&format!("{width}x{height} is odd and must be refused"));
3309 assert!(
3310 err.to_string().contains("even"),
3311 "{width}x{height}: error was {err}"
3312 );
3313 }
3314 }
3315
3316 /// A sequence at a size that is not a multiple of the block grid decodes
3317 /// to the right frame count and the right size for every frame,
3318 /// including the inter frames whose reference is the previous frame's
3319 /// own (padded) reconstruction.
3320 #[test]
3321 fn sequence_round_trips_at_a_non_multiple_size() {
3322 if !have_ffmpeg() {
3323 eprintln!("SKIP sequence_round_trips_at_a_non_multiple_size: no ffmpeg");
3324 return;
3325 }
3326 let (width, height) = (160usize, 96usize);
3327 let pictures: Vec<Picture> = (0..3)
3328 .map(|i| panned_test_card(width, height, i * 3))
3329 .collect();
3330 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
3331 assert_eq!(encoded.frames.len(), 3);
3332 for (i, frame) in encoded.frames.iter().enumerate() {
3333 assert_eq!(
3334 (frame.reconstruction.width, frame.reconstruction.height),
3335 (width, height),
3336 "frame {i}: reconstruction size"
3337 );
3338 }
3339 // See `a_frame_round_trips_at_its_own_size`: `ffprobe` reports the
3340 // true (display) size a sequence's frames share, not the padded one.
3341 assert_eq!(
3342 ffprobe_size(&encoded.stream),
3343 (width as u32, height as u32),
3344 "sequence: ffprobe reports the true (display) size"
3345 );
3346 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
3347 assert_eq!(decoded.len(), 3, "decoded frame count");
3348 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
3349 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
3350 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
3351 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
3352 }
3353 }
3354
3355 /// 1280x720 -- the export size a real edith timeline hits -- is exactly
3356 /// the "half straddle" class: 720 mod 32 == 16, so the true frame edge
3357 /// falls at exactly half of the last row of 32x32 blocks (`has_half`'s
3358 /// `pos + side_mi / 2 < bound` boundary), which is the case
3359 /// `sb_coeff_inter_frame_tile`'s `Quadrant::Split` now codes rather than
3360 /// refusing. A key frame alone already covered this size; this proves the
3361 /// inter tile writer's parity with it across a real multi-frame export.
3362 #[test]
3363 fn a_sequence_round_trips_at_the_exactly_half_straddle_size() {
3364 if !have_ffmpeg() {
3365 eprintln!("SKIP a_sequence_round_trips_at_the_exactly_half_straddle_size: no ffmpeg");
3366 return;
3367 }
3368 let (width, height) = (1280usize, 720usize);
3369 let pictures: Vec<Picture> = (0..3)
3370 .map(|i| panned_test_card(width, height, i * 3))
3371 .collect();
3372 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
3373 assert_eq!(encoded.frames.len(), 3);
3374 for (i, frame) in encoded.frames.iter().enumerate() {
3375 assert_eq!(
3376 (frame.reconstruction.width, frame.reconstruction.height),
3377 (width, height),
3378 "frame {i}: reconstruction size"
3379 );
3380 }
3381 assert_eq!(
3382 ffprobe_size(&encoded.stream),
3383 (width as u32, height as u32),
3384 "ffprobe reports the true (display) 1280x720 size"
3385 );
3386 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 3);
3387 assert_eq!(decoded.len(), 3, "decoded frame count");
3388 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
3389 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
3390 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
3391 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
3392 }
3393 }
3394
3395 /// 640x360 is the class the charter names: 360 mod 32 == 8, so a 16x16
3396 /// leaf's own half (`has_half` at the SUB level) itself straddles the
3397 /// true edge on one axis only. lane-av1-rect r7 wired the key frame
3398 /// writer's 8x8-leaf path (`crate::tile::write_leaf8`) live for exactly
3399 /// this case; lane-av1inter8 extends the same leaf-8 path to inter
3400 /// frames (`code_square_inter` at `side == 8`, `sb_coeff_inter_frame_tile`'s
3401 /// straddling-16x16 branch), so an inter frame no longer refuses this
3402 /// size either. This only proves the encoder does not error out -- see
3403 /// `a_640x360_half_straddle_sequence_round_trips_through_ffmpeg` for the
3404 /// decoder-clean proof (a 3-frame sequence, so the inter path is
3405 /// actually exercised).
3406 #[test]
3407 fn key_frame_and_inter_frame_both_encode_at_half_straddle_size() {
3408 let (width, height) = (640usize, 360usize);
3409 let picture = Picture::grey(width, height);
3410 encode_key_frame(&picture, 100, 0.5).expect("key frame now codes the mod-32==8 straddle");
3411
3412 // `encode_sequence`'s second frame is the inter path: same size, now
3413 // wired the same way.
3414 let pictures = vec![picture.clone(), picture];
3415 encode_sequence(&pictures, 100, 0.5)
3416 .expect("inter frame now codes the mod-32==8 straddle too");
3417 }
3418
3419 /// The r15 fix at production size: three 640x360 key frames (inter is
3420 /// still refused at this size, per the test above, so this stands in for
3421 /// the charter's "3-frame sequence" using three independent key frames of
3422 /// shifted content), each proven decoder-clean through ffmpeg rather than
3423 /// only encoder-clean.
3424 #[test]
3425 fn a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames() {
3426 if !have_ffmpeg() {
3427 eprintln!(
3428 "SKIP a_640x360_half_straddle_round_trips_through_ffmpeg_across_three_frames: \
3429 no ffmpeg"
3430 );
3431 return;
3432 }
3433 let (width, height) = (640usize, 360usize);
3434 for shift in [0i64, 7, 19] {
3435 let picture = panned_test_card(width, height, shift);
3436 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
3437 let decoded = ffmpeg_decode(&encoded.stream, width, height);
3438 assert_eq!(decoded.y, encoded.reconstruction.y, "shift {shift}: luma");
3439 assert_eq!(decoded.u, encoded.reconstruction.u, "shift {shift}: U");
3440 assert_eq!(decoded.v, encoded.reconstruction.v, "shift {shift}: V");
3441 }
3442 }
3443
3444 /// The 640x360 straddle class, but through the inter path an actual
3445 /// 3-frame sequence exercises (lane-av1inter8's own ladder rung (b)):
3446 /// proves the leaf-8 inter stream this round wires up is not just
3447 /// encoder-clean (the test above) but decoder-clean against ffmpeg too.
3448 #[test]
3449 fn a_640x360_half_straddle_sequence_round_trips_through_ffmpeg() {
3450 if !have_ffmpeg() {
3451 eprintln!(
3452 "SKIP a_640x360_half_straddle_sequence_round_trips_through_ffmpeg: no ffmpeg"
3453 );
3454 return;
3455 }
3456 let (width, height) = (640usize, 360usize);
3457 let pictures: Vec<Picture> = (0..4)
3458 .map(|i| panned_test_card(width, height, i * 3))
3459 .collect();
3460 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
3461 assert_eq!(encoded.frames.len(), 4);
3462 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
3463 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
3464 }
3465 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 4);
3466 assert_eq!(decoded.len(), 4, "decoded frame count");
3467 for (i, (frame, decoded)) in encoded.frames.iter().zip(&decoded).enumerate() {
3468 assert_eq!(decoded.y, frame.reconstruction.y, "frame {i}: luma");
3469 assert_eq!(decoded.u, frame.reconstruction.u, "frame {i}: U");
3470 assert_eq!(decoded.v, frame.reconstruction.v, "frame {i}: V");
3471 }
3472 }
3473
3474 /// One frame of a real clip, scaled to a whole number of 32x32 blocks.
3475 fn clip_frame(clip: &str, skip: &str, width: usize, height: usize) -> Picture {
3476 let out = Command::new("ffmpeg")
3477 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "1"])
3478 .args(["-vf", &format!("scale={width}:{height}")])
3479 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
3480 .output()
3481 .expect("ffmpeg failed to run");
3482 assert!(
3483 out.status.success(),
3484 "ffmpeg: {}",
3485 String::from_utf8_lossy(&out.stderr)
3486 );
3487 let (luma, chroma) = (width * height, width * height / 4);
3488 assert_eq!(
3489 out.stdout.len(),
3490 luma + 2 * chroma,
3491 "expected one 4:2:0 frame"
3492 );
3493 Picture {
3494 width,
3495 height,
3496 y: out.stdout[..luma].to_vec(),
3497 u: out.stdout[luma..luma + chroma].to_vec(),
3498 v: out.stdout[luma + chroma..].to_vec(),
3499 }
3500 }
3501
3502 /// Prints what the mode search saves over DC prediction alone, for the
3503 /// synthetic pictures and for whatever clips `EC_AV1_CLIPS` names, so the
3504 /// weight the search puts on rate can be swept.
3505 #[test]
3506 #[ignore = "a sweep, not a gate"]
3507 fn probe_lambda() {
3508 let mut pictures = vec![
3509 ("test card".to_string(), test_card(160, 96)),
3510 ("stripes".to_string(), stripes(160, 96, true)),
3511 ];
3512 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
3513 for entry in clips.split(':').filter(|e| !e.is_empty()) {
3514 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
3515 let name = path.rsplit('/').next().unwrap_or(path).to_string();
3516 pictures.push((name, clip_frame(path, skip, 640, 352)));
3517 }
3518 }
3519 for (name, picture) in pictures {
3520 let dc = ladder(&picture, &[DC_PRED]);
3521 let searched = ladder(&picture, &NON_DIRECTIONAL);
3522 println!(
3523 "{name}: {:+.1}% rate against DC alone, {:.0}B/{:.2}dB against {:.0}B/{:.2}dB at the middle point",
3524 bd_rate(&dc, &searched) * 100.0,
3525 10f64.powf(searched[1].1),
3526 searched[1].0,
3527 10f64.powf(dc[1].1),
3528 dc[1].0,
3529 );
3530 }
3531 }
3532
3533 /// Prints the whole mode-search ladder, so two builds of the search can be
3534 /// compared against each other rather than each against its own baseline.
3535 #[test]
3536 #[ignore = "a sweep, not a gate"]
3537 fn probe_ladder() {
3538 for (name, picture) in sweep_pictures() {
3539 let all = ladder(&picture, &KEY_FRAME_MODES);
3540 let points = all
3541 .iter()
3542 .map(|&(db, log_bytes)| format!("{:.0}@{db:.3}", 10f64.powf(log_bytes)))
3543 .collect::<Vec<_>>()
3544 .join(" ");
3545 println!("ladder {name}: {points}");
3546 }
3547 }
3548
3549 /// Splitting a 32x32 block into four 16x16 ones, measured both ways over
3550 /// the sweep pictures and whatever clips `EC_AV1_CLIPS` names. This is what
3551 /// sets [`SPLIT_BLOCKS`]; the table it prints is in the lane report.
3552 #[test]
3553 #[ignore = "a sweep, not a gate"]
3554 fn probe_split() {
3555 for (name, picture) in sweep_pictures() {
3556 let ladder = |split: bool| {
3557 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
3558 .iter()
3559 .map(|&q| {
3560 let encoded = encode_key_frame_inner(
3561 &picture,
3562 q,
3563 0.5,
3564 &KEY_FRAME_MODES,
3565 split,
3566 (picture.width, picture.height),
3567 unspecified_color_config(),
3568 )
3569 .unwrap();
3570 (
3571 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
3572 (encoded.stream.len() as f64).log10(),
3573 )
3574 })
3575 .collect();
3576 points.sort_by(|a, b| a.0.total_cmp(&b.0));
3577 points
3578 };
3579 let (whole, split) = (ladder(false), ladder(true));
3580 let blocks = encode_key_frame_inner(
3581 &picture,
3582 90,
3583 0.5,
3584 &KEY_FRAME_MODES,
3585 true,
3586 (picture.width, picture.height),
3587 unspecified_color_config(),
3588 )
3589 .unwrap()
3590 .modes
3591 .len();
3592 let quadrants = (picture.width / BLOCK) * (picture.height / BLOCK);
3593 println!(
3594 "split {name}: {:+.2}% rate, {blocks} blocks for {quadrants} quadrants at q90",
3595 bd_rate(&whole, &split) * 100.0
3596 );
3597 }
3598 }
3599
3600 /// A striped picture, running one way or the other. The stripes are what
3601 /// separates a vertical predictor from a horizontal one: a mode search
3602 /// reading a transposed edge would pick the wrong one of the pair, which no
3603 /// symmetric picture would show.
3604 fn stripes(width: usize, height: usize, vertical: bool) -> Picture {
3605 let mut picture = Picture::grey(width, height);
3606 for y in 0..height {
3607 for x in 0..width {
3608 let along = if vertical { x } else { y };
3609 picture.y[y * width + x] = if (along / 4) % 2 == 0 { 40 } else { 210 };
3610 }
3611 }
3612 picture
3613 }
3614
3615 /// Where two planes first disagree, and by how much: a mismatch reported as
3616 /// a position says which block and which sample of it went wrong, which a
3617 /// pair of thousand-sample arrays does not.
3618 fn first_difference(ours: &[u8], theirs: &[u8], width: usize) -> Option<String> {
3619 let i = ours.iter().zip(theirs).position(|(a, b)| a != b)?;
3620 let differ = ours.iter().zip(theirs).filter(|(a, b)| a != b).count();
3621 Some(format!(
3622 "{differ} samples differ, first at ({}, {}): ours {} theirs {}",
3623 i % width,
3624 i / width,
3625 ours[i],
3626 theirs[i]
3627 ))
3628 }
3629
3630 /// Every mode the encoder offers has to predict what the decoder predicts,
3631 /// not just the ones a particular picture happens to choose: each is forced
3632 /// over a whole picture and the reconstruction gated against ffmpeg.
3633 #[test]
3634 fn every_mode_decodes_to_what_the_encoder_predicted() {
3635 if !have_ffmpeg() {
3636 eprintln!("SKIP every_mode_decodes_to_what_the_encoder_predicted: no ffmpeg");
3637 return;
3638 }
3639 // 128 wide is a whole number of superblocks and 160 is not: the last
3640 // superblock of a 160-wide row is half a one, whose blocks have no
3641 // above-right samples inside the frame at all.
3642 for (width, height) in [(128, 96), (160, 96)] {
3643 let picture = test_card(width, height);
3644 for mode in KEY_FRAME_MODES {
3645 let encoded = encode_key_frame_with_modes(&picture, 100, 0.5, &[mode]).unwrap();
3646 let decoded = ffmpeg_decode(&encoded.stream, width, height);
3647 for (plane, ours, theirs, stride) in [
3648 ("luma", &encoded.reconstruction.y, &decoded.y, width),
3649 ("U", &encoded.reconstruction.u, &decoded.u, width / 2),
3650 ("V", &encoded.reconstruction.v, &decoded.v, width / 2),
3651 ] {
3652 assert!(
3653 first_difference(ours, theirs, stride).is_none(),
3654 "{width}x{height} mode {mode}, {plane}: {}",
3655 first_difference(ours, theirs, stride).unwrap()
3656 );
3657 }
3658 assert!(
3659 encoded.modes.iter().all(|&m| m == mode),
3660 "mode {mode}: the encoder coded something else"
3661 );
3662 }
3663 }
3664 }
3665
3666 /// The search has to follow the picture: vertical stripes are cheapest
3667 /// predicted from the row above, horizontal ones from the column to the
3668 /// left. Reading the edges the other way round would swap the two answers
3669 /// while leaving every fidelity gate intact.
3670 #[test]
3671 fn the_search_picks_the_direction_the_picture_runs() {
3672 for (vertical, want) in [(true, V_PRED), (false, H_PRED)] {
3673 let picture = stripes(128, 96, vertical);
3674 // Only the pair, because on stripes a third mode predicts exactly
3675 // what the right one of the pair does -- PAETH reads the corner and
3676 // the left column, which a striped picture makes equal -- and the
3677 // tie then goes to whichever is cheaper to name, which is not what
3678 // this gate is about.
3679 let encoded =
3680 encode_key_frame_with_modes(&picture, 100, 0.5, &[V_PRED, H_PRED]).unwrap();
3681 // The first block of the picture has neither neighbour, so it
3682 // cannot tell the modes apart; every other one can.
3683 let picked = encoded.modes[1..].iter().filter(|&&m| m == want).count();
3684 assert!(
3685 picked * 2 > encoded.modes.len() - 1,
3686 "vertical={vertical}: only {picked} of {} blocks picked mode {want}, modes {:?}",
3687 encoded.modes.len() - 1,
3688 encoded.modes
3689 );
3690 }
3691 }
3692
3693 /// What the search is for: the same picture, at the same quantizer, coded
3694 /// smaller and more faithfully than DC alone can manage.
3695 /// Rate saved at matched fidelity, over a three-point ladder: the trapezoid
3696 /// between the two rate-distortion curves in log-rate against PSNR, as a
3697 /// fraction of the reference's rate. Negative means the second curve costs
3698 /// less for the same picture.
3699 fn bd_rate(reference: &[(f64, f64)], other: &[(f64, f64)]) -> f64 {
3700 let low = reference[0].0.max(other[0].0);
3701 let high = reference[reference.len() - 1]
3702 .0
3703 .min(other[other.len() - 1].0);
3704 assert!(high > low, "the two ladders have to overlap in PSNR");
3705 let log_rate_at = |curve: &[(f64, f64)], psnr: f64| {
3706 let i = curve
3707 .windows(2)
3708 .position(|w| psnr >= w[0].0 && psnr <= w[1].0)
3709 .unwrap_or(0);
3710 let (x0, y0) = curve[i];
3711 let (x1, y1) = curve[i + 1];
3712 y0 + (y1 - y0) * (psnr - x0) / (x1 - x0)
3713 };
3714 let steps = 64;
3715 let mut area = 0.0;
3716 for step in 0..steps {
3717 let psnr = low + (high - low) * (f64::from(step) + 0.5) / f64::from(steps);
3718 area += log_rate_at(other, psnr) - log_rate_at(reference, psnr);
3719 }
3720 10f64.powf(area / f64::from(steps)) - 1.0
3721 }
3722
3723 /// A ladder of (luma PSNR, log10 bytes) for one mode set, ordered by
3724 /// fidelity.
3725 fn ladder(picture: &Picture, modes: &[u8]) -> Vec<(f64, f64)> {
3726 let mut points: Vec<(f64, f64)> = [110u8, 90, 70]
3727 .iter()
3728 .map(|&q| {
3729 let encoded = encode_key_frame_with_modes(picture, q, 0.5, modes).unwrap();
3730 (
3731 psnr(&encoded.reconstruction.y, picture.y.as_slice()),
3732 (encoded.stream.len() as f64).log10(),
3733 )
3734 })
3735 .collect();
3736 points.sort_by(|a, b| a.0.total_cmp(&b.0));
3737 points
3738 }
3739
3740 /// What the search is for: the same pictures cost less to code at the same
3741 /// fidelity than DC prediction alone can manage. A picture that runs one
3742 /// way saves far more than a busy one, which is the shape a working
3743 /// directional pair has.
3744 #[test]
3745 fn the_search_beats_dc_alone() {
3746 for (name, picture, want) in [
3747 ("test card", test_card(160, 96), -0.05),
3748 ("stripes", stripes(160, 96, true), -0.40),
3749 ] {
3750 let saved = bd_rate(
3751 &ladder(&picture, &[DC_PRED]),
3752 &ladder(&picture, &NON_DIRECTIONAL),
3753 );
3754 assert!(
3755 saved < want,
3756 "{name}: the search saved {:.1}% of the rate, wanted at least {:.1}%",
3757 saved * 100.0,
3758 -want * 100.0
3759 );
3760 }
3761 }
3762
3763 /// The pictures a sweep is measured over: two synthetic ones, plus a frame
3764 /// from each clip named in `EC_AV1_CLIPS` as `path@skip`, colon separated.
3765 fn sweep_pictures() -> Vec<(String, Picture)> {
3766 let mut pictures = vec![
3767 ("test card".to_string(), test_card(160, 96)),
3768 ("stripes".to_string(), stripes(160, 96, true)),
3769 ("diagonal".to_string(), diagonal(160, 96, true)),
3770 ];
3771 if let Ok(clips) = std::env::var("EC_AV1_CLIPS") {
3772 for entry in clips.split(':').filter(|e| !e.is_empty()) {
3773 let (path, skip) = entry.split_once('@').unwrap_or((entry, "0"));
3774 let name = path.rsplit('/').next().unwrap_or(path).to_string();
3775 pictures.push((name, clip_frame(path, skip, 640, 352)));
3776 }
3777 }
3778 pictures
3779 }
3780
3781 /// What the six directional modes are worth, per picture, at whatever
3782 /// `LAMBDA_SCALE` currently is: the rate they save over the seven that read
3783 /// no further, and how often the search picks one.
3784 #[test]
3785 #[ignore = "a sweep, not a gate"]
3786 fn probe_directional() {
3787 for (name, picture) in sweep_pictures() {
3788 let dc = ladder(&picture, &[DC_PRED]);
3789 let flat = ladder(&picture, &NON_DIRECTIONAL);
3790 let all = ladder(&picture, &KEY_FRAME_MODES);
3791 let encoded = encode_key_frame(&picture, 90, 0.5).unwrap();
3792 let directional = encoded
3793 .modes
3794 .iter()
3795 .filter(|&&m| (3..=8).contains(&m))
3796 .count();
3797 // A picture whose ladders sit at different fidelities altogether
3798 // has no BD-rate to report -- see the flat-sample-window class.
3799 let overlap = |a: &[(f64, f64)], b: &[(f64, f64)]| {
3800 a[0].0.max(b[0].0) < a[a.len() - 1].0.min(b[b.len() - 1].0)
3801 };
3802 let against = |a: &[(f64, f64)], b: &[(f64, f64)]| {
3803 if overlap(a, b) {
3804 format!("{:+.2}%", bd_rate(a, b) * 100.0)
3805 } else {
3806 "no overlap".to_string()
3807 }
3808 };
3809 println!(
3810 "{name}: {} against the seven, {} against DC alone, {directional} of {} blocks directional",
3811 against(&flat, &all),
3812 against(&dc, &all),
3813 encoded.modes.len(),
3814 );
3815 }
3816 }
3817
3818 /// A picture whose stripes run along a diagonal, one way or the other.
3819 /// This is to the directional modes what [`stripes`] is to the vertical and
3820 /// horizontal pair: a predictor that walked the edge in the wrong direction
3821 /// would answer the two pictures the same way round.
3822 fn diagonal(width: usize, height: usize, down_right: bool) -> Picture {
3823 let mut picture = Picture::grey(width, height);
3824 for y in 0..height {
3825 for x in 0..width {
3826 let along = if down_right { x + height - y } else { x + y };
3827 picture.y[y * width + x] = if (along / 6) % 2 == 0 { 40 } else { 210 };
3828 }
3829 }
3830 picture
3831 }
3832
3833 /// The mode picked by the most blocks of a picture, ignoring the first
3834 /// block, which has no neighbours to tell the modes apart with.
3835 fn favourite_mode(picture: &Picture) -> (u8, usize, usize) {
3836 let encoded = encode_key_frame(picture, 100, 0.5).unwrap();
3837 let blocks = &encoded.modes[1..];
3838 let mut counts = [0usize; 13];
3839 for &mode in blocks {
3840 counts[usize::from(mode)] += 1;
3841 }
3842 let (mode, count) = counts
3843 .iter()
3844 .enumerate()
3845 .max_by_key(|&(_, count)| *count)
3846 .expect("thirteen modes");
3847 (mode as u8, *count, blocks.len())
3848 }
3849
3850 /// The search has to follow a diagonal the way it runs: stripes down and to
3851 /// the right are cheapest predicted at 135 degrees, stripes down and to the
3852 /// left at 45. A walk that stepped the wrong way along the edge, or read
3853 /// the above row where it should read the left column, would swap these.
3854 #[test]
3855 fn the_search_picks_the_diagonal_the_picture_runs() {
3856 for (down_right, want) in [(true, D135_PRED), (false, D45_PRED)] {
3857 let picture = diagonal(160, 96, down_right);
3858 let (mode, count, blocks) = favourite_mode(&picture);
3859 assert_eq!(
3860 mode, want,
3861 "down_right={down_right}: {count} of {blocks} blocks picked mode {mode}"
3862 );
3863 }
3864 }
3865
3866 /// What the directional modes are for: a picture that runs along a diagonal
3867 /// costs far less to code with them than the seven that read only their own
3868 /// edges can manage, and a picture that runs no particular way costs no
3869 /// more. The second half is the one that bites: a mode set the search
3870 /// cannot price is a mode set that loses rate on content that does not want
3871 /// it, which is what costing the mode symbol is for.
3872 #[test]
3873 fn the_diagonals_beat_the_modes_that_read_no_further() {
3874 for (name, picture, want) in [
3875 ("down-right", diagonal(160, 96, true), -0.20),
3876 ("down-left", diagonal(160, 96, false), -0.20),
3877 ("test card", test_card(160, 96), 0.01),
3878 ] {
3879 let saved = bd_rate(
3880 &ladder(&picture, &NON_DIRECTIONAL),
3881 &ladder(&picture, &KEY_FRAME_MODES),
3882 );
3883 assert!(
3884 saved < want,
3885 "{name}: the directional modes saved {:.1}% of the rate, wanted better than {:.1}%",
3886 saved * 100.0,
3887 -want * 100.0
3888 );
3889 }
3890 }
3891
3892 /// A mode the encoder cannot predict must be refused rather than coded as
3893 /// something else, and a search with nothing to choose from likewise.
3894 #[test]
3895 fn a_mode_the_encoder_cannot_predict_is_refused() {
3896 let picture = test_card(64, 64);
3897 let message = encode_key_frame_with_modes(&picture, 100, 0.5, &[13])
3898 .unwrap_err()
3899 .to_string();
3900 assert!(
3901 message.contains("intra mode 13"),
3902 "the refusal must name the mode, got {message}"
3903 );
3904 assert!(encode_key_frame_with_modes(&picture, 100, 0.5, &[]).is_err());
3905 }
3906
3907 /// The picture that comes back is the picture that went in, to within the
3908 /// quantizer. A prediction that read the wrong neighbours, or a block
3909 /// written into the wrong place, would still decode to what the encoder
3910 /// reconstructed — it is this gate that says the reconstruction is of the
3911 /// right picture.
3912 #[test]
3913 fn the_encoded_picture_is_the_one_that_went_in() {
3914 let picture = test_card(160, 96);
3915 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
3916 let luma = psnr(&encoded.reconstruction.y, &picture.y);
3917 assert!(luma > 36.0, "luma PSNR {luma} at q 100");
3918 for (plane, (got, want)) in [
3919 (encoded.reconstruction.u.as_slice(), picture.u.as_slice()),
3920 (encoded.reconstruction.v.as_slice(), picture.v.as_slice()),
3921 ]
3922 .iter()
3923 .enumerate()
3924 {
3925 let chroma = psnr(got, want);
3926 assert!(chroma > 40.0, "chroma plane {plane} PSNR {chroma} at q 100");
3927 }
3928 }
3929
3930 /// A finer quantizer costs bits and buys fidelity, and a wider deadzone
3931 /// does the opposite. Both are monotone, which is what a rate-distortion
3932 /// loop above this will assume.
3933 #[test]
3934 fn fidelity_and_rate_move_with_the_quantizer() {
3935 let picture = test_card(128, 128);
3936 let mut previous: Option<(usize, f64)> = None;
3937 for &q in &[70u8, 90, 110] {
3938 let encoded = encode_key_frame(&picture, q, 0.5).unwrap();
3939 let quality = psnr(&encoded.reconstruction.y, &picture.y);
3940 if let Some((bytes, better)) = previous {
3941 assert!(
3942 encoded.stream.len() < bytes,
3943 "q {q}: {} bytes",
3944 encoded.stream.len()
3945 );
3946 assert!(quality < better, "q {q}: PSNR {quality}");
3947 }
3948 previous = Some((encoded.stream.len(), quality));
3949 }
3950
3951 let mut previous = None;
3952 for &deadzone in &[0.5f64, 0.3, 0.15] {
3953 let encoded = encode_key_frame(&picture, 100, deadzone).unwrap();
3954 let quality = psnr(&encoded.reconstruction.y, &picture.y);
3955 if let Some((bytes, better)) = previous {
3956 assert!(
3957 encoded.stream.len() < bytes,
3958 "deadzone {deadzone}: {} bytes",
3959 encoded.stream.len()
3960 );
3961 assert!(quality < better, "deadzone {deadzone}: PSNR {quality}");
3962 }
3963 previous = Some((encoded.stream.len(), quality));
3964 }
3965
3966 // Bytes must not jump up across a q-context boundary: a wrong CDF
3967 // table for the far side would show up as a rate discontinuity here,
3968 // even though a coarser quantizer always codes no more than a finer
3969 // one on the same picture.
3970 for &(lo, hi) in &[(20u8, 21u8), (60, 61), (120, 121)] {
3971 let lo_bytes = encode_key_frame(&picture, lo, 0.5).unwrap().stream.len();
3972 let hi_bytes = encode_key_frame(&picture, hi, 0.5).unwrap().stream.len();
3973 assert!(
3974 hi_bytes <= lo_bytes,
3975 "q {lo}->{hi} crosses a context boundary: {lo_bytes} -> {hi_bytes} bytes"
3976 );
3977 }
3978 }
3979
3980 /// A flat picture is a flat stream: every block predicts its neighbours'
3981 /// average, which is the picture's own value, and codes nothing.
3982 #[test]
3983 fn a_flat_picture_costs_almost_nothing() {
3984 let mut picture = Picture::grey(128, 128);
3985 picture.y.fill(97);
3986 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
3987 // The first block has no neighbour and predicts 128, so it carries a
3988 // DC; every block after it predicts 97 and carries nothing.
3989 assert!(
3990 encoded.stream.len() < 100,
3991 "{} bytes for a flat picture",
3992 encoded.stream.len()
3993 );
3994 for (i, &s) in encoded.reconstruction.y.iter().enumerate().skip(32 * 128) {
3995 assert_eq!(s, 97, "sample {i} of a flat picture");
3996 }
3997 }
3998
3999 /// The sizes the encoder refuses, refused for a reason rather than by
4000 /// panicking somewhere below. Most sizes off the 32x32 block grid encode
4001 /// fine now (see `a_frame_round_trips_at_its_own_size`) -- the true frame
4002 /// edge lands past the halfway point of whichever block it falls in, so
4003 /// `PARTITION_NONE` or a single gathered split flag still says everything
4004 /// the spec needs. lane-av1-rect r7 wires the 8x8-leaf path live, so a
4005 /// 16x16 leaf straddling on exactly one axis (e.g. 40x32, cols mod 32 ==
4006 /// 8) now encodes too (see `a_frame_round_trips_at_its_own_size`'s
4007 /// sibling below). Only a leaf whose true edge cuts *both* axes (e.g.
4008 /// 40x40, both dims mod 32 == 8) needs the rectangular transform neither
4009 /// writer has, so that class is still refused, by name rather than by
4010 /// corrupting the stream.
4011 #[test]
4012 fn a_picture_off_the_block_grid_is_refused() {
4013 let msg = encode_key_frame(&Picture::grey(40, 40), 100, 0.5)
4014 .expect_err("40x40 straddles both axes of a 16x16 leaf, needs a rectangular transform")
4015 .to_string();
4016 assert!(msg.contains("rectangular"), "refusal: {msg}");
4017
4018 let mut short = Picture::grey(64, 64);
4019 short.u.truncate(10);
4020 assert!(encode_key_frame(&short, 100, 0.5).is_err());
4021 }
4022
4023 /// 40x32: cols mod 32 == 8, so the true edge cuts a 16x16 leaf's own
4024 /// column half only (`has_half` false on cols, true on rows) -- exactly
4025 /// the single-axis straddle lane-av1-rect r7 wires through
4026 /// `crate::tile::write_leaf8`'s 8x8 leaves. Not yet decoder-clean:
4027 /// dav1d rejects the stream ("Invalid data found"). r7's falsification
4028 /// candidate (`partition_w8`'s ctx reading the enclosing 16x16 slot) is
4029 /// FALSIFIED by r8's rng trace against a debug `aomdec`: libaom's own
4030 /// `partition_plane_context` masks at `bsl = 0` for `BLOCK_8X8`, and every
4031 /// `partition_context_lookup` entry this writer ever produces (no 4x4
4032 /// splits exist) has bit 0 clear, so the ctx is provably 0 for every
4033 /// leaf regardless of neighbour state -- our writer already agreed with
4034 /// the decoder here (`ctx=0` both sides). r8 still ported the mi-precise
4035 /// tracking (`Neighbours::{above,left}_side_mi`, `partition_ctx_mi`) as a
4036 /// spec-accurate fix in its own right (it matters once 4x4 exists), and
4037 /// it does not regress the gate. r11 tell-for-tell traced two further,
4038 /// real bugs and fixed both: (1) `write_leaf8`'s intra-mode context read
4039 /// the *enclosing* 16x16 slot's stale `above_mode`/`left_mode` for both
4040 /// leaves, when the second leaf's true above (or left) neighbour is the
4041 /// first leaf itself -- fixed by threading the first leaf's mode into the
4042 /// second leaf's context, mi-precise, like `record_mi` already does for
4043 /// coefficients; (2) `TxbSet::Luma8`'s transform-type table was
4044 /// `INTRA_TX_TYPE_SET1_8` (`TX_SET_INTRA_1`, 7-way, correct only when
4045 /// `reduced_tx_set` is false), but this crate's key frames set
4046 /// `reduced_tx_set: true`, which per `get_tx_set` (spec 5.11.48) puts
4047 /// *every* intra size up to 16x16 -- not only 16x16 -- on `TX_SET_INTRA_2`
4048 /// (5-way); the wrong cardinality read enough of the stream as `TX_TYPE`
4049 /// symbol bits to desync everything after it. Fixed with a new
4050 /// `INTRA_TX_TYPE_SET2_8` (libaom's flat default for that exact
4051 /// eset/size slot). Both fixes are provably correct against libaom
4052 /// source and each closed part of the gap (leaf0's `eob` went from a
4053 /// desynced 36 to a near-miss 3, writer's real eob is 7), but a residual
4054 /// divergence remained in the `EOB_PT` symbol's decoded value despite an
4055 /// aligned bit cost. r12 traced that residual with a fresh dual-trace
4056 /// (do not reuse r11's committed logs, which predate its own fixes) and
4057 /// found two more real bugs, both now fixed: (3) `write_leaf8` hardcoded
4058 /// `cfl: false` for `write_intra_mode`'s chroma-mode CDF choice, but
4059 /// `is_cfl_allowed` (spec 5.11.5) is true for any block `<= 32x32` --
4060 /// every other `write_block` caller at 16x16 and up already passes
4061 /// `true`; the narrower `uv_mode_no_cfl` alphabet is one symbol short of
4062 /// `uv_mode_cfl`, so even an identical `DC_PRED` decision consumed a
4063 /// different amount of arithmetic range and derailed everything after
4064 /// it. (4) `record()`'s `above_mode`/`left_mode` write is a no-op at an
4065 /// 8x8 leaf's own side (`side / SUB == 0` for `SUB` = 16), and
4066 /// `write_leaf8` called only `record_mi` (the coefficient-context half),
4067 /// never updating those coarse arrays itself -- so a *second* straddling
4068 /// 16x16 quadrant stacked above or left of the first (never covered by
4069 /// r11's same-call `prev_leaf` override, which only threads state
4070 /// between the two leaves of one shared quadrant) read whatever stale
4071 /// mode sat in that slot before either leaf ran. Fixed by writing the
4072 /// leaf's own mode into `above_mode[c]`/`left_mode[r]` directly. Fixing
4073 /// (3) alone shrank the tell drift after leaf(0,8) from a decoder
4074 /// `eob_pt=3` (wrong) vs the writer's real `eob_pt=4` down to a `tell`
4075 /// offset of a single unit; fixing (3)+(4) together still leaves a
4076 /// residual divergence one leaf further in -- the decoder now reads
4077 /// leaf(2,8)'s own luma coefficient block as `txs_ctx=1` (a 32-sample
4078 /// transform) where the writer intends `TX_8X8` (`txs_ctx=2`), meaning
4079 /// something *before* this leaf's own `EC_TXBSKIP`/`EC_TXTYPE` still
4080 /// desyncs the stream by exactly the width of one earlier symbol -- not
4081 /// yet isolated to a single named symbol. r15 found the last bug: the
4082 /// header fix from r14 explained the rng skew fully, and the remaining
4083 /// desync (still past `mi_row=4`) was `write_leaf8`'s (4) fix itself --
4084 /// its `above_mode[c]`/`left_mode[r]` forced write ran *inside* the leaf
4085 /// loop, once per leaf, so the first leaf's write clobbered the true
4086 /// external neighbour mode the second leaf of the *same* straddling
4087 /// quadrant still needed for its non-adjacency axis (a column-straddle
4088 /// case: two leaves share one `outer_at` column index, so leaf 1's
4089 /// write to `left_mode[r]` overwrote the real western neighbour before
4090 /// leaf 2 read it). Fixed by moving the write out of `write_leaf8` and
4091 /// doing it once, after the whole leaf loop, from the last (bottom/
4092 /// right-most) leaf's mode. The stream now round-trips through ffmpeg.
4093 #[test]
4094 fn a_single_axis_straddle_round_trips_through_ffmpeg() {
4095 if !have_ffmpeg() {
4096 eprintln!("SKIP a_single_axis_straddle_round_trips_through_ffmpeg: no ffmpeg");
4097 return;
4098 }
4099 let (width, height) = (40usize, 32usize);
4100 let picture = test_card(width, height);
4101 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
4102 assert_eq!(
4103 (encoded.reconstruction.width, encoded.reconstruction.height),
4104 (width, height)
4105 );
4106 if let Ok(path) = std::env::var("EC_AV1_DUMP") {
4107 std::fs::write(&path, &encoded.stream).expect("dump the raw stream");
4108 }
4109 let decoded = ffmpeg_decode(&encoded.stream, width, height);
4110 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
4111 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
4112 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
4113 }
4114
4115 /// A frame of real video, rather than a picture built to be easy.
4116 ///
4117 /// `EC_AV1_CLIP` names the clip and `EC_AV1_CLIP_SKIP` how far into it to
4118 /// seek; ffmpeg decodes one frame, crops it to the block grid, and the
4119 /// encoder's reconstruction has to survive the same equality gate as the
4120 /// synthetic pictures — real video reaches contexts a test card does not.
4121 #[test]
4122 fn a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed() {
4123 let Ok(clip) = std::env::var("EC_AV1_CLIP") else {
4124 eprintln!(
4125 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: \
4126 set EC_AV1_CLIP to a clip"
4127 );
4128 return;
4129 };
4130 if !have_ffmpeg() {
4131 eprintln!(
4132 "SKIP a_frame_of_real_video_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
4133 );
4134 return;
4135 }
4136 let skip = std::env::var("EC_AV1_CLIP_SKIP").unwrap_or_else(|_| "0".into());
4137 // A 4:2:0 frame cropped to whole 32x32 blocks, in a size that keeps the
4138 // test quick while still spanning many superblocks.
4139 let (width, height) = (640usize, 352usize);
4140 let picture = clip_frame(&clip, &skip, width, height);
4141
4142 let encoded = encode_key_frame(&picture, 100, 0.5).unwrap();
4143 let decoded = ffmpeg_decode(&encoded.stream, width, height);
4144 assert_eq!(decoded.y, encoded.reconstruction.y, "luma");
4145 assert_eq!(decoded.u, encoded.reconstruction.u, "U");
4146 assert_eq!(decoded.v, encoded.reconstruction.v, "V");
4147 eprintln!(
4148 "{} bytes, luma PSNR {:.2} dB",
4149 encoded.stream.len(),
4150 psnr(&decoded.y, &picture.y)
4151 );
4152 }
4153
4154 /// [`test_card`], panned `shift` samples to the right (wrapping), so a
4155 /// sequence of these is a translation a motion search can actually find
4156 /// — the content [`test_card`] itself draws, not a fresh pattern, so an
4157 /// inter frame's rate against the key frame's is measuring the same
4158 /// picture moving, not two different pictures.
4159 fn panned_test_card(width: usize, height: usize, shift: i64) -> Picture {
4160 let mut picture = Picture::grey(width, height);
4161 for y in 0..height {
4162 for x in 0..width {
4163 let sx = (x as i64 - shift).rem_euclid(width as i64) as f64;
4164 let gradient = sx * 200.0 / width as f64;
4165 let ripple = 30.0
4166 * (sx * std::f64::consts::PI / 23.0).sin()
4167 * (y as f64 * std::f64::consts::PI / 37.0).cos();
4168 let edge = if sx > (width * 3 / 7) as f64 && y > height / 3 {
4169 40.0
4170 } else {
4171 0.0
4172 };
4173 picture.y[y * width + x] =
4174 (20.0 + gradient + ripple + edge).clamp(0.0, 255.0) as u8;
4175 }
4176 }
4177 for y in 0..height / 2 {
4178 for x in 0..width / 2 {
4179 let sx = (x as i64 - shift / 2).rem_euclid((width / 2) as i64) as usize;
4180 let i = y * width / 2 + x;
4181 picture.u[i] = (100 + (sx * 60 / (width / 2))) as u8;
4182 picture.v[i] = (200 - (y * 80 / (height / 2))) as u8;
4183 }
4184 }
4185 picture
4186 }
4187
4188 /// Decodes `frames` concatenated 4:2:0 frames out of one AV1 OBU stream.
4189 fn ffmpeg_decode_sequence(
4190 stream: &[u8],
4191 width: usize,
4192 height: usize,
4193 frames: usize,
4194 ) -> Vec<Picture> {
4195 let mut child = Command::new("ffmpeg")
4196 .args([
4197 "-v", "error", "-f", "obu", "-i", "-", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-",
4198 ])
4199 .stdin(Stdio::piped())
4200 .stdout(Stdio::piped())
4201 .stderr(Stdio::piped())
4202 .spawn()
4203 .expect("ffmpeg failed to start");
4204 child
4205 .stdin
4206 .take()
4207 .expect("ffmpeg stdin")
4208 .write_all(stream)
4209 .expect("writing the stream to ffmpeg");
4210 let out = child.wait_with_output().expect("ffmpeg failed to run");
4211 assert!(
4212 out.status.success(),
4213 "ffmpeg refused the stream: {}",
4214 String::from_utf8_lossy(&out.stderr)
4215 );
4216 let (luma, chroma) = (width * height, width * height / 4);
4217 let frame_bytes = luma + 2 * chroma;
4218 assert_eq!(
4219 out.stdout.len(),
4220 frame_bytes * frames,
4221 "expected {frames} 4:2:0 frames, ffmpeg said: {}",
4222 String::from_utf8_lossy(&out.stderr)
4223 );
4224 (0..frames)
4225 .map(|i| {
4226 let base = i * frame_bytes;
4227 Picture {
4228 width,
4229 height,
4230 y: out.stdout[base..base + luma].to_vec(),
4231 u: out.stdout[base + luma..base + luma + chroma].to_vec(),
4232 v: out.stdout[base + luma + chroma..base + frame_bytes].to_vec(),
4233 }
4234 })
4235 .collect()
4236 }
4237
4238 /// The same claim [`ffmpeg_decodes_exactly_what_the_encoder_reconstructed`]
4239 /// makes for a key frame, extended down the reference chain: each inter
4240 /// frame's reconstruction predicts from the previous frame's own decoded
4241 /// reconstruction, so a single sample of drift anywhere would propagate
4242 /// into every frame after it -- which is why every frame is checked, not
4243 /// just the last one, and why this is an equality and not a tolerance.
4244 #[test]
4245 fn every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed() {
4246 if !have_ffmpeg() {
4247 eprintln!(
4248 "SKIP every_frame_of_a_sequence_decodes_to_what_the_encoder_reconstructed: no ffmpeg"
4249 );
4250 return;
4251 }
4252 let (width, height) = (128usize, 64usize);
4253 let pictures: Vec<Picture> = (0..5)
4254 .map(|i| panned_test_card(width, height, i * 3))
4255 .collect();
4256 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
4257 assert_eq!(encoded.frames.len(), 5);
4258
4259 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, 5);
4260 for (i, (frame, dec)) in encoded.frames.iter().zip(&decoded).enumerate() {
4261 assert_eq!(dec.y, frame.reconstruction.y, "frame {i}: luma");
4262 assert_eq!(dec.u, frame.reconstruction.u, "frame {i}: U");
4263 assert_eq!(dec.v, frame.reconstruction.v, "frame {i}: V");
4264 }
4265
4266 eprintln!("frame bytes luma PSNR (dB) inter share");
4267 for (i, frame) in encoded.frames.iter().enumerate() {
4268 eprintln!(
4269 "{i:5} {:5} {:14.2} {:11.2}",
4270 frame.stream.len(),
4271 psnr(&frame.reconstruction.y, &pictures[i].y),
4272 frame.inter_block_share
4273 );
4274 }
4275 }
4276
4277 /// Low motion has to actually buy something: at least one inter frame of
4278 /// a panning sequence has to cost fewer bytes than the key frame that
4279 /// starts it, and the inter-block share it prints has to be non-zero --
4280 /// a search that never picks an inter mode would still pass a rate gate
4281 /// on a picture with no motion in it (the class this repo calls
4282 /// gate-blind-to-feature), so the share is printed even though it is not
4283 /// asserted on beyond being reachable at all.
4284 #[test]
4285 fn low_motion_makes_an_inter_frame_smaller_than_the_key_frame() {
4286 let (width, height) = (256usize, 128usize);
4287 let pictures: Vec<Picture> = (0..5)
4288 .map(|i| panned_test_card(width, height, i * 2))
4289 .collect();
4290 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
4291
4292 let key_bytes = encoded.frames[0].stream.len();
4293 eprintln!("frame bytes inter share");
4294 for (i, frame) in encoded.frames.iter().enumerate() {
4295 eprintln!(
4296 "{i:5} {:5} {:11.2}",
4297 frame.stream.len(),
4298 frame.inter_block_share
4299 );
4300 }
4301 assert!(
4302 encoded.frames[1..]
4303 .iter()
4304 .any(|f| f.stream.len() < key_bytes),
4305 "no inter frame of a panning sequence beat the key frame's {key_bytes} bytes"
4306 );
4307 assert!(
4308 encoded.frames[1..]
4309 .iter()
4310 .any(|f| f.inter_block_share > 0.0),
4311 "no inter frame coded a single inter block -- the search never fired"
4312 );
4313 }
4314
4315 /// A manual perf probe, not a gate: prints where a key frame's and an
4316 /// inter frame's time goes, coarse stage by coarse stage, so a perf lane
4317 /// measures before it optimizes rather than guessing. Run with
4318 /// `cargo test -p ec-av1 --release stage_timing_breakdown -- --ignored --nocapture`.
4319 #[test]
4320 #[ignore = "a perf probe, not a gate"]
4321 fn stage_timing_breakdown() {
4322 use std::time::Instant;
4323
4324 for &(width, height) in &[(1920usize, 1080usize), (3840, 2160)] {
4325 let picture = test_card(width, height);
4326
4327 let t = Instant::now();
4328 let dc_only = encode_key_frame_with_modes(&picture, 100, 0.5, &[DC_PRED]).unwrap();
4329 let dc_only_t = t.elapsed();
4330
4331 let t = Instant::now();
4332 let non_directional =
4333 encode_key_frame_with_modes(&picture, 100, 0.5, &NON_DIRECTIONAL).unwrap();
4334 let non_directional_t = t.elapsed();
4335
4336 let t = Instant::now();
4337 let all_modes = encode_key_frame(&picture, 100, 0.5).unwrap();
4338 let all_modes_t = t.elapsed();
4339
4340 eprintln!(
4341 "\n=== key frame {width}x{height} ===\n\
4342 1 mode (DC only): {dc_only_t:>9.2?} ({} bytes)\n\
4343 7 modes (non-directional): {non_directional_t:>9.2?} ({} bytes)\n\
4344 13 modes (default search): {all_modes_t:>9.2?} ({} bytes)",
4345 dc_only.stream.len(),
4346 non_directional.stream.len(),
4347 all_modes.stream.len(),
4348 );
4349
4350 // One inter frame predicting off the key frame's own
4351 // reconstruction, the (256, 256)-padded surface encode_sequence
4352 // itself would hand encode_inter_frame.
4353 let padded_ref = all_modes.reconstruction.padded_to(SUPERBLOCK);
4354 let padded_pic = picture.padded_to(SUPERBLOCK);
4355 let t = Instant::now();
4356 let inter =
4357 encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap();
4358 let inter_t = t.elapsed();
4359 eprintln!(
4360 "inter frame vs its own key frame: {inter_t:>9.2?} ({} bytes, inter share \
4361 {:.2})",
4362 inter.stream.len(),
4363 inter.inter_block_share
4364 );
4365 }
4366
4367 // Isolated per-call cost of the trial pipeline's own stages, at both
4368 // transform sizes the search runs, averaged over enough calls to
4369 // rise above `Instant::now`'s own noise.
4370 for side in [16usize, 32] {
4371 const N: u32 = 20_000;
4372 let residual: Vec<i32> = (0..side * side)
4373 .map(|i| ((i * 37 % 61) as i32) - 30)
4374 .collect();
4375
4376 let t = Instant::now();
4377 let mut levels = Vec::new();
4378 for _ in 0..N {
4379 levels = forward_and_quantize(&residual, side, 8, 100, 0.5);
4380 }
4381 let forward_t = t.elapsed() / N;
4382
4383 let t = Instant::now();
4384 for _ in 0..N {
4385 std::hint::black_box(dequant_and_inverse(&levels, side, 8, 100));
4386 }
4387 let inverse_t = t.elapsed() / N;
4388
4389 let set = if side == 32 {
4390 crate::cdf_state::TxbSet::Luma32
4391 } else {
4392 crate::cdf_state::TxbSet::Luma16
4393 };
4394 let t = Instant::now();
4395 for _ in 0..N {
4396 std::hint::black_box(crate::tile::coeff_bits(&levels, set));
4397 }
4398 let entropy_t = t.elapsed() / N;
4399
4400 let above = vec![128u8; side * 2];
4401 let left = vec![128u8; side * 2];
4402 let mut prediction = vec![0u8; side * side];
4403 let t = Instant::now();
4404 for _ in 0..N {
4405 crate::intra::predict(
4406 D45_PRED,
4407 Some(&above),
4408 Some(&left),
4409 Some(128),
4410 side,
4411 &mut prediction,
4412 );
4413 }
4414 let predict_t = t.elapsed() / N;
4415
4416 eprintln!(
4417 "\n=== per-call cost at {side}x{side}, averaged over {N} calls ===\n\
4418 predict (1 directional mode): {predict_t:>9.2?}\n\
4419 forward_and_quantize: {forward_t:>9.2?}\n\
4420 dequant_and_inverse: {inverse_t:>9.2?}\n\
4421 coeff_bits: {entropy_t:>9.2?}"
4422 );
4423 }
4424 }
4425
4426 /// Breaks one inter frame's own cost into the four [`STAGE_NS`] buckets
4427 /// (motion search, [`crate::mc::predict`], transform+quantize,
4428 /// `coeff_bits`), plus what is left over once those are subtracted --
4429 /// the thirteen-mode intra-candidate loop `search_inter_block` still
4430 /// runs on every inter block (its own transform/quant/entropy calls are
4431 /// already inside buckets 2/3, so "left over" here is everything NOT
4432 /// timed: `crate::intra::predict` for those 13 modes, RD bookkeeping,
4433 /// symbol-cost lookups outside `coeff_bits`).
4434 ///
4435 /// `cargo test -p ec-av1 --release stage_timing_breakdown_inter -- --ignored --nocapture`.
4436 #[test]
4437 #[ignore = "a perf probe, not a gate"]
4438 fn stage_timing_breakdown_inter() {
4439 use std::time::Instant;
4440
4441 let (width, height) = (1280usize, 720);
4442 let picture = test_card(width, height);
4443 let key = encode_key_frame(&picture, 100, 0.5).unwrap();
4444 let padded_ref = key.reconstruction.padded_to(SUPERBLOCK);
4445 let padded_pic = picture.padded_to(SUPERBLOCK);
4446
4447 stage_reset();
4448 let t = Instant::now();
4449 let inter =
4450 encode_inter_frame(&padded_pic, &padded_ref, 100, 0.5, 1, (width, height)).unwrap();
4451 let total_t = t.elapsed();
4452 let [motion_search, interpolation, transform_quant, entropy] = stage_read();
4453 let accounted = motion_search + transform_quant + entropy;
4454 // motion_search already contains interpolation's own time (every
4455 // candidate the search costs calls crate::mc::predict), so it is not
4456 // added again here -- interpolation is reported alongside as "of
4457 // which interpolation", not as a fifth additive bucket.
4458 let other = total_t.saturating_sub(accounted);
4459
4460 eprintln!(
4461 "\n=== inter frame {width}x{height}, one frame ===\n\
4462 total: {total_t:>9.2?} ({} bytes)\n\
4463 motion search (NEWMV): {motion_search:>9.2?} (of which interpolation \
4464 {interpolation:>9.2?})\n\
4465 transform + quantize: {transform_quant:>9.2?}\n\
4466 coeff_bits (entropy pricing): {entropy:>9.2?}\n\
4467 everything else (13-mode intra {other:>9.2?}\n\
4468 candidate loop's own predict/bookkeeping, NEARESTMV's own \
4469 predict, RD glue):",
4470 inter.stream.len(),
4471 );
4472 }
4473
4474 /// The quality gate [`Search::top_k`]'s lever lives or dies by: three real
4475 /// frames (a dark/flat one, a detailed one, a normal film one) at two
4476 /// `base_q_idx` values, encoded with the mode search unpruned (`top_k =
4477 /// None`, the baseline this same build produces without
4478 /// `EC_AV1_PRUNE_K` set) and with it pruned to each of a few `K`, bytes
4479 /// and luma PSNR compared side by side. Not a gate itself -- the numbers
4480 /// go in the lane report, which is where "ship as default" is decided --
4481 /// so it stays `#[ignore]`, run by hand with real clips on this machine.
4482 /// `cargo test -p ec-av1 --release prune_k_quality_sweep -- --ignored --nocapture`.
4483 #[test]
4484 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
4485 fn prune_k_quality_sweep() {
4486 if !have_ffmpeg() {
4487 eprintln!("SKIP prune_k_quality_sweep: no ffmpeg");
4488 return;
4489 }
4490 let (width, height) = (640usize, 352usize);
4491 let frames: &[(&str, &str, &str)] = &[
4492 // (label, clip, seek) -- a near-black scene, a busy one, and an
4493 // ordinary film frame, each from a different real file.
4494 (
4495 "dark/flat",
4496 "/home/user/Videos/reela.mp4",
4497 "3",
4498 ),
4499 (
4500 "detailed",
4501 "/home/user/Downloads/reelb.mkv",
4502 "1200",
4503 ),
4504 (
4505 "film",
4506 "/home/user/Videos/Films/reelc.mkv",
4507 "600",
4508 ),
4509 ];
4510 for &(label, clip, skip) in frames {
4511 if !std::path::Path::new(clip).exists() {
4512 eprintln!("SKIP {label}: {clip} not present on this machine");
4513 continue;
4514 }
4515 let picture = clip_frame(clip, skip, width, height);
4516 for &q in &[60u8, 150] {
4517 // SAFETY (not literally unsafe, just process-global): this is
4518 // a single-threaded #[ignore] probe, run by hand, never
4519 // alongside other tests that read Search::top_k.
4520 set_test_top_k_override(None);
4521 let baseline = encode_key_frame(&picture, q, 0.5).unwrap();
4522 let baseline_psnr = psnr(&baseline.reconstruction.y, &picture.y);
4523 eprint!(
4524 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
4525 baseline.stream.len(),
4526 baseline_psnr
4527 );
4528 for &k in &[3usize, 4, 6] {
4529 set_test_top_k_override(Some(k));
4530 let pruned = encode_key_frame(&picture, q, 0.5).unwrap();
4531 let pruned_psnr = psnr(&pruned.reconstruction.y, &picture.y);
4532 eprint!(
4533 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
4534 pruned.stream.len(),
4535 pruned_psnr,
4536 pruned_psnr - baseline_psnr
4537 );
4538 }
4539 eprintln!();
4540 }
4541 }
4542 set_test_top_k_override(None);
4543 }
4544
4545 /// Two consecutive decoded frames from one clip, for an inter-frame
4546 /// sweep -- [`clip_frame`] alone only ever gives one.
4547 fn clip_frame_pair(clip: &str, skip: &str, width: usize, height: usize) -> [Picture; 2] {
4548 let out = Command::new("ffmpeg")
4549 .args(["-v", "error", "-ss", skip, "-i", clip, "-frames:v", "2"])
4550 .args(["-vf", &format!("scale={width}:{height}")])
4551 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
4552 .output()
4553 .expect("ffmpeg failed to run");
4554 assert!(
4555 out.status.success(),
4556 "ffmpeg: {}",
4557 String::from_utf8_lossy(&out.stderr)
4558 );
4559 let (luma, chroma) = (width * height, width * height / 4);
4560 let frame_len = luma + 2 * chroma;
4561 assert_eq!(out.stdout.len(), frame_len * 2, "expected two 4:2:0 frames");
4562 std::array::from_fn(|i| {
4563 let bytes = &out.stdout[i * frame_len..][..frame_len];
4564 Picture {
4565 width,
4566 height,
4567 y: bytes[..luma].to_vec(),
4568 u: bytes[luma..luma + chroma].to_vec(),
4569 v: bytes[luma + chroma..].to_vec(),
4570 }
4571 })
4572 }
4573
4574 /// The quality gate [`INTER_PRUNE_TOP_K`] lives or dies by: the same
4575 /// three real clips as [`prune_k_quality_sweep`], but coding a key frame
4576 /// then one inter frame off it (`search_inter_block`'s own intra
4577 /// candidates are what [`prune_by_sad`] prunes here, not the key-frame
4578 /// loop), at 1280x704 -- a whole number of 64x64 superblocks, so no
4579 /// padding step complicates the comparison. Prints bytes and luma PSNR
4580 /// for the inter frame alone, unpruned vs each `K`.
4581 /// `cargo test -p ec-av1 --release prune_k_quality_sweep_inter -- --ignored --nocapture`.
4582 #[test]
4583 #[ignore = "needs real clips and ffmpeg; prints numbers for the lane report to judge"]
4584 fn prune_k_quality_sweep_inter() {
4585 if !have_ffmpeg() {
4586 eprintln!("SKIP prune_k_quality_sweep_inter: no ffmpeg");
4587 return;
4588 }
4589 let (width, height) = (1280usize, 704usize);
4590 let frames: &[(&str, &str, &str)] = &[
4591 (
4592 "dark/flat",
4593 "/home/user/Videos/reela.mp4",
4594 "3",
4595 ),
4596 (
4597 "detailed",
4598 "/home/user/Downloads/reelb.mkv",
4599 "1200",
4600 ),
4601 (
4602 "film",
4603 "/home/user/Videos/Films/reelc.mkv",
4604 "600",
4605 ),
4606 ];
4607 for &(label, clip, skip) in frames {
4608 if !std::path::Path::new(clip).exists() {
4609 eprintln!("SKIP {label}: {clip} not present on this machine");
4610 continue;
4611 }
4612 let [key_source, inter_source] = clip_frame_pair(clip, skip, width, height);
4613 for &q in &[60u8, 150] {
4614 // SAFETY (not literally unsafe, just process-global): a
4615 // single-threaded #[ignore] probe, run by hand, never
4616 // alongside other tests that read Search::top_k.
4617 set_test_top_k_override_inter(None);
4618 let key = encode_key_frame(&key_source, q, 0.5).unwrap();
4619 let baseline = encode_inter_frame(
4620 &inter_source,
4621 &key.reconstruction,
4622 q,
4623 0.5,
4624 1,
4625 (width, height),
4626 )
4627 .unwrap();
4628 let baseline_psnr = psnr(&baseline.reconstruction.y, &inter_source.y);
4629 eprint!(
4630 "{label:9} q={q:3} baseline {:6} bytes {:6.2} dB",
4631 baseline.stream.len(),
4632 baseline_psnr
4633 );
4634 for &k in &[3usize, 4, 6] {
4635 set_test_top_k_override_inter(Some(k));
4636 let pruned = encode_inter_frame(
4637 &inter_source,
4638 &key.reconstruction,
4639 q,
4640 0.5,
4641 1,
4642 (width, height),
4643 )
4644 .unwrap();
4645 let pruned_psnr = psnr(&pruned.reconstruction.y, &inter_source.y);
4646 eprint!(
4647 " K={k} {:6} bytes {:6.2} dB ({:+.3} dB)",
4648 pruned.stream.len(),
4649 pruned_psnr,
4650 pruned_psnr - baseline_psnr
4651 );
4652 }
4653 eprintln!();
4654 }
4655 }
4656 set_test_top_k_override_inter(None);
4657 }
4658
4659 /// `frames` consecutive pictures out of a real clip, scaled to a whole
4660 /// number of 32x32 blocks. Generalizes [`clip_frame`]/[`clip_frame_pair`]
4661 /// to an arbitrary count for the fixture regression gate below.
4662 fn clip_frames(
4663 clip: &str,
4664 skip: &str,
4665 width: usize,
4666 height: usize,
4667 frames: usize,
4668 ) -> Vec<Picture> {
4669 let out = Command::new("ffmpeg")
4670 .args(["-v", "error", "-ss", skip, "-i", clip])
4671 .args(["-frames:v", &frames.to_string()])
4672 .args(["-vf", &format!("scale={width}:{height}")])
4673 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
4674 .output()
4675 .expect("ffmpeg failed to run");
4676 assert!(
4677 out.status.success(),
4678 "ffmpeg: {}",
4679 String::from_utf8_lossy(&out.stderr)
4680 );
4681 let (luma, chroma) = (width * height, width * height / 4);
4682 let frame_len = luma + 2 * chroma;
4683 assert_eq!(
4684 out.stdout.len(),
4685 frame_len * frames,
4686 "expected {frames} 4:2:0 frames"
4687 );
4688 (0..frames)
4689 .map(|i| {
4690 let bytes = &out.stdout[i * frame_len..][..frame_len];
4691 Picture {
4692 width,
4693 height,
4694 y: bytes[..luma].to_vec(),
4695 u: bytes[luma..luma + chroma].to_vec(),
4696 v: bytes[luma + chroma..].to_vec(),
4697 }
4698 })
4699 .collect()
4700 }
4701
4702 /// The standing regression gate on real content: 12 frames of a real
4703 /// clip (`fixtures/video/h264-1080p-23.976-8bit.mp4`, decoded down to
4704 /// this crate's own input regardless of its own source codec), encoded
4705 /// as an AV1 GOP and checked against three numeric floors so a
4706 /// compatibility or quality regression fails the suite instead of
4707 /// waiting for a downstream repo's gate to catch it (as happened for a
4708 /// padded-size inter `FrameHeader` dav1d rejected, and a 1280x720 export
4709 /// refusal, both caught only that way).
4710 ///
4711 /// 640x384 is a whole number of 32x32 blocks (no straddle edge case;
4712 /// that geometry is already covered elsewhere), chosen only so encode
4713 /// time and gate numbers are not muddied by an edge-block class this
4714 /// test is not about.
4715 ///
4716 /// Measured 2026-08-27 at q=100: stream 69861 bytes, average luma PSNR
4717 /// 45.41 dB across the 12 decoded frames vs the source. Floor/ceiling
4718 /// below carry a margin off those measured numbers (PSNR floor =
4719 /// measured - 0.5 dB; byte ceiling = measured * 1.15).
4720 #[test]
4721 fn real_clip_encodes_within_its_quality_and_size_budget() {
4722 if !have_ffmpeg() {
4723 eprintln!("SKIP real_clip_encodes_within_its_quality_and_size_budget: no ffmpeg");
4724 return;
4725 }
4726 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
4727 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
4728 if !clip.exists() {
4729 eprintln!(
4730 "SKIP real_clip_encodes_within_its_quality_and_size_budget: {} missing",
4731 clip.display()
4732 );
4733 return;
4734 }
4735 let (width, height, frame_count) = (640usize, 384usize, 12usize);
4736 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
4737 let encoded = encode_sequence(&source, 100, 0.5).unwrap();
4738 assert_eq!(encoded.frames.len(), frame_count);
4739
4740 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
4741 // stream and hands back every frame -- a stream a downstream
4742 // decoder refuses is the exact class of regression this gate
4743 // exists for.
4744 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
4745 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
4746
4747 // Gate 2: quality vs the source did not silently collapse.
4748 let mean_psnr: f64 = decoded
4749 .iter()
4750 .zip(&source)
4751 .map(|(d, s)| psnr(&d.y, &s.y))
4752 .sum::<f64>()
4753 / frame_count as f64;
4754 assert!(
4755 mean_psnr >= 44.91,
4756 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.91 dB floor"
4757 );
4758
4759 // Gate 3: the stream did not silently bloat.
4760 assert!(
4761 encoded.stream.len() <= 80_340,
4762 "stream grew to {} bytes, over the 80340-byte ceiling",
4763 encoded.stream.len()
4764 );
4765 }
4766
4767 /// Sibling of `real_clip_encodes_within_its_quality_and_size_budget` at a
4768 /// straddle size: 640x384 is exact on both axes (32-aligned), so
4769 /// `Quadrant::Split` never fires there and the 16x16 `NEARESTMV` leaf
4770 /// path landed in e19bb47 goes unexercised by real, mixed intra/inter
4771 /// content. 704x400 has 400 mod 32 == 16 -- the same "exactly half
4772 /// straddle" class as `a_sequence_round_trips_at_the_exactly_half_
4773 /// straddle_size`'s 1280x720, but that test is a synthetic panned test
4774 /// card; this one is the real-clip gate, same three floors.
4775 ///
4776 /// Measured 2026-08-27 at q=100, 8 frames: stream 54525 bytes, average
4777 /// luma PSNR 45.48 dB across the 8 decoded frames vs the source.
4778 /// Floor/ceiling below carry the same margin as the sibling test (PSNR
4779 /// floor = measured - 0.5 dB; byte ceiling = measured * 1.15).
4780 #[test]
4781 fn real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size() {
4782 if !have_ffmpeg() {
4783 eprintln!(
4784 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
4785 no ffmpeg"
4786 );
4787 return;
4788 }
4789 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
4790 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
4791 if !clip.exists() {
4792 eprintln!(
4793 "SKIP real_clip_encodes_within_its_quality_and_size_budget_at_a_straddle_size: \
4794 {} missing",
4795 clip.display()
4796 );
4797 return;
4798 }
4799 let (width, height, frame_count) = (704usize, 400usize, 8usize);
4800 let source = clip_frames(clip.to_str().unwrap(), "0", width, height, frame_count);
4801 let encoded = encode_sequence(&source, 100, 0.5).unwrap();
4802 assert_eq!(encoded.frames.len(), frame_count);
4803
4804 // Gate 1: a real AV1 decoder (dav1d, via ffmpeg) accepts the whole
4805 // stream and hands back every frame.
4806 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frame_count);
4807 assert_eq!(decoded.len(), frame_count, "dav1d decoded every frame");
4808
4809 // Gate 2: quality vs the source did not silently collapse.
4810 let mean_psnr: f64 = decoded
4811 .iter()
4812 .zip(&source)
4813 .map(|(d, s)| psnr(&d.y, &s.y))
4814 .sum::<f64>()
4815 / frame_count as f64;
4816 assert!(
4817 mean_psnr >= 44.98,
4818 "mean luma PSNR {mean_psnr:.2} dB fell below the 44.98 dB floor"
4819 );
4820
4821 // Gate 3: the stream did not silently bloat.
4822 assert!(
4823 encoded.stream.len() <= 62_703,
4824 "stream grew to {} bytes, over the 62703-byte ceiling",
4825 encoded.stream.len()
4826 );
4827 }
4828
4829 /// The replica-shaped path: 24 frames, 1280x720, one key frame followed
4830 /// by inter frames -- the same GOP shape [`encode_sequence`] gives the
4831 /// facade -- timed end to end, so the edith export-time projection is a
4832 /// real number rather than a guess from the isolated key/inter numbers
4833 /// above. Run with and without `EC_AV1_PRUNE_K` set to compare.
4834 /// `cargo test -p ec-av1 --release sequence_bench_sanity -- --ignored --nocapture`.
4835 #[test]
4836 #[ignore = "a perf probe, not a gate"]
4837 fn sequence_bench_sanity() {
4838 use std::time::Instant;
4839 let (width, height) = (1280usize, 720usize);
4840 let pictures: Vec<Picture> = (0..24)
4841 .map(|i| panned_test_card(width, height, i * 3))
4842 .collect();
4843 let t = Instant::now();
4844 let encoded = encode_sequence(&pictures, 100, 0.5).unwrap();
4845 let elapsed = t.elapsed();
4846 let total_bytes: usize = encoded.frames.iter().map(|f| f.stream.len()).sum();
4847 eprintln!(
4848 "24 frames @ 1280x720: {elapsed:>9.2?} total, {:>9.2?}/frame, {total_bytes} bytes",
4849 elapsed / 24
4850 );
4851 }
4852
4853 /// The `base_q_idx` calibration sweep for `lane-av1-ratectl` -- feeds the
4854 /// `Quality`/`BytesPerFrame` rate-control surface in `encoder.rs`, not a
4855 /// gate itself. `cargo test -p ec-av1 --release calibration_sweep_base_q_idx
4856 /// -- --ignored --nocapture`.
4857 #[test]
4858 #[ignore = "a calibration probe, not a gate"]
4859 fn calibration_sweep_base_q_idx() {
4860 if !have_ffmpeg() {
4861 eprintln!("SKIP calibration_sweep_base_q_idx: no ffmpeg");
4862 return;
4863 }
4864 let (width, height, frames) = (640usize, 384usize, 12usize);
4865 for clip in [
4866 "h264-1080p-23.976-8bit.mp4", // film-ish, 23.976fps
4867 "h264-1080p-60-8bit.mp4", // higher motion, 60fps
4868 ] {
4869 let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
4870 .join("../../fixtures/video")
4871 .join(clip);
4872 if !path.exists() {
4873 eprintln!("SKIP {clip}: fixture missing");
4874 continue;
4875 }
4876 let source = clip_frames(path.to_str().unwrap(), "0", width, height, frames);
4877 eprintln!("--- {clip} ---");
4878 for q in [40u8, 70, 100, 130, 160, 190, 220, 240] {
4879 let encoded = encode_sequence(&source, q, 0.5).unwrap();
4880 let decoded = ffmpeg_decode_sequence(&encoded.stream, width, height, frames);
4881 let mean_psnr: f64 = decoded
4882 .iter()
4883 .zip(&source)
4884 .map(|(d, s)| psnr(&d.y, &s.y))
4885 .sum::<f64>()
4886 / frames as f64;
4887 let bytes_per_px = encoded.stream.len() as f64 / (width * height * frames) as f64;
4888 eprintln!(
4889 "q={q:3} bytes={:7} bytes/px={bytes_per_px:.5} psnr={mean_psnr:.2} dB",
4890 encoded.stream.len()
4891 );
4892 }
4893 }
4894 }
4895}