forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

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