forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2a2adbaTahinli2 months ago2117 commits

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