forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB231663eTahinli3 months ago1475 commits

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