forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB50503afTahinli3 months ago1344 commits

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