forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBa5441e8Tahinli3 months ago1014 commits

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