forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiBea3c0dfTahinli3 months ago1465 commits

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