forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBf44b458Tahinli3 months ago649 commits

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