forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB576f72dTahinli3 months ago1275 commits

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