forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8fd360cTahinli2 months ago2655 commits

encoder.rs4146 lines, 187.1 KiBHistoryRawDownload
1//! The streaming encoder facade — I11 of `lanes/av1-inter-plan.md`, the
2//! surface `edith_replica`'s engine calls in place of rav1e.
3//!
4//! ONE FRAME OF LATENCY, everywhere: a picture handed to
5//! [`Av1Encoder::encode`]/[`Av1Encoder::encode_frames`] is held until the
6//! NEXT picture arrives, because an inter frame's per-superblock temporal
7//! lambda map reads the next source picture as its lookahead (lane-av1tpl)
8//! — exactly as [`crate::encode::encode_sequence`] does, so the facade and
9//! the sequence path now code the same bytes for the same pictures. A
10//! stream therefore ENDS with [`Av1Encoder::flush`], which codes whatever is
11//! still held. [`Av1Encoder::with_pyramid`] holds a whole mini-GOP for the
12//! same kind of reason (it reorders pictures) and is driven through
13//! [`Av1Encoder::encode_frames`]/[`Av1Encoder::flush`] too. Internally it
14//! is [`crate::encode::encode_key_frame_inner`] and
15//! [`crate::encode::encode_inter_frame`] driven by a small state machine —
16//! a key frame every `gop` pictures, an inter frame predicting from the
17//! previous picture's own reconstruction otherwise — which is the same core
18//! [`crate::encode::encode_sequence`] uses for its one-key-frame-then-all-inter
19//! case; both now share it rather than each padding/cropping/refreshing the
20//! reference on their own.
21
22use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig};
23use ec_core::{Error, Result};
24
25use crate::encode::{
26 Encoded, GOLDEN_SLOT, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame,
27 encode_key_frame_inner, split_blocks,
28};
29use crate::intra::KEY_FRAME_MODES;
30
31/// A quantizer step round to nearest: half a step either way costs the same
32/// rate, so this is the deadzone every facade-driven frame is coded with.
33/// (`crate::encode`'s public entry points take a caller-chosen deadzone
34/// instead; the facade has no field for it because nothing downstream of it
35/// picks one.)
36const DEADZONE: f64 = 0.5;
37
38/// The colour a played-back frame is transformed by, named at what a
39/// container/player picks a colour space from (spec 5.5.2's CICP triple plus
40/// range) rather than at the raw integers. `edith_replica`'s rav1e seat sets
41/// limited-range BT.709 or BT.601 (`export.rs:3494-3507`); this crate's
42/// pre-facade sequence header always wrote [`Colour::Unspecified`].
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
44pub enum Colour {
45 /// `color_primaries`/`transfer_characteristics`/`matrix_coefficients` =
46 /// 1 (BT.709, H.273), studio range: consumer HD video's own space, and
47 /// the default a player assumes when nothing is signalled at all.
48 #[default]
49 Bt709Limited,
50 /// The same three fields = 6 (BT.601, H.273), studio range: SD video's
51 /// space.
52 Bt601Limited,
53 /// Every field = 2 ("unspecified", H.273): what this crate wrote before
54 /// any of this was configurable.
55 Unspecified,
56}
57
58impl Colour {
59 fn color_config(self) -> ColorConfig {
60 let (color_primaries, transfer_characteristics, matrix_coefficients) = match self {
61 Colour::Bt709Limited => (1, 1, 1),
62 Colour::Bt601Limited => (6, 6, 6),
63 Colour::Unspecified => (2, 2, 2),
64 };
65 ColorConfig {
66 bit_depth: 8,
67 mono_chrome: false,
68 num_planes: 3,
69 color_primaries,
70 transfer_characteristics,
71 matrix_coefficients,
72 // Every variant here is studio (limited) swing; a full-range
73 // variant would need its own name, not a fourth field on this
74 // enum, since a played-back frame's range is a property of the
75 // pictures fed in, not just a label.
76 color_range: false,
77 subsampling_x: 1,
78 subsampling_y: 1,
79 chroma_sample_position: ChromaSamplePosition::Unknown,
80 separate_uv_delta_q: false,
81 }
82 }
83}
84
85/// A quality/size targeting surface for callers who would rather not pick a
86/// `base_q_idx` themselves, oracled at CRF's own shape (a single "quality"
87/// dial that holds a stable perceptual level across content, `ffmpeg -crf`)
88/// since a from-scratch scheme is not this lane's charter to invent.
89/// [`Av1Encoder::with_rate_target`] is additive: [`EncoderConfig::base_q_idx`]
90/// keeps working exactly as before for every existing caller, this is a
91/// second, opt-in constructor.
92#[derive(Debug, Clone, Copy, PartialEq)]
93pub enum RateTarget {
94 /// Exactly `base_q_idx`, unchanged — the `EncoderConfig` field's own
95 /// value, for a caller that already has one.
96 QIndex(u8),
97 /// A CRF-like single dial, 0 (smallest/worst) to 100 (largest/best),
98 /// mapped to a fixed `base_q_idx` by the calibration in
99 /// `encode::tests::calibration_sweep_base_q_idx` (linear in `q_idx`
100 /// across the sweep's own 40..=240 span, since the measured bytes/PSNR
101 /// curve is close enough to log-linear there that a straight line is
102 /// the "simplest correct" fit this lane's charter asks for). No
103 /// per-frame feedback: one value, picked once at construction.
104 Quality(u8),
105 /// A closed loop that steers `base_q_idx` frame by frame to land each
106 /// coded frame near this many bytes, via [`RateLoop`] — see there for
107 /// the controller and its windup bound.
108 BytesPerFrame(u32),
109 /// A target BITRATE: the same closed loop, with the per-frame byte
110 /// target derived from `bits_per_second` and `frames_per_second`
111 /// (`bits_per_second / 8 / frames_per_second`), and — in pyramid mode —
112 /// split across the levels by their reference weight, since a hidden
113 /// `ALTREF` and a leaf differ by several times in size and one shared
114 /// predictor would swing the quantizer every frame.
115 Bitrate {
116 /// The stream's target bitrate.
117 bits_per_second: u32,
118 /// The frame rate the bitrate is spent at.
119 frames_per_second: f64,
120 },
121}
122
123impl RateTarget {
124 /// Applies this target to `config` and returns the closed loop it needs
125 /// (`None` for the two open-loop variants). `mini_gop` is `Some` in
126 /// pyramid mode, which is what makes the loop keep a quantizer per level.
127 fn into_loop(self, config: &mut EncoderConfig, pyramid: Option<Pyramid>) -> Option<RateLoop> {
128 let target_bytes = match self {
129 RateTarget::QIndex(q) => {
130 config.base_q_idx = q;
131 return None;
132 }
133 RateTarget::Quality(quality) => {
134 config.base_q_idx = quality_to_q_idx(quality);
135 return None;
136 }
137 RateTarget::BytesPerFrame(target_bytes) => f64::from(target_bytes),
138 RateTarget::Bitrate {
139 bits_per_second,
140 frames_per_second,
141 } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0),
142 };
143 Some(RateLoop::new(
144 target_bytes,
145 f64::from(config.base_q_idx),
146 pyramid,
147 config.gop,
148 ))
149 }
150}
151
152/// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's
153/// span (`q_idx` 40 at `quality` 100 down to `q_idx` 240 at `quality` 0);
154/// `quality` above 100 clamps to the best point measured, matching a CRF
155/// dial's own saturating ends rather than extrapolating past calibrated
156/// data.
157fn quality_to_q_idx(quality: u8) -> u8 {
158 let quality = f64::from(quality.min(100));
159 (240.0 - quality * 2.0).round() as u8
160}
161
162/// What one coded frame is worth, relative to a leaf, as a function of how
163/// much FINER than the leaf it is coded (`leaf_q_offset - own offset`, in
164/// `q_idx` steps): `exp(WEIGHT_LEVEL_GAIN * delta)`.
165///
166/// This is the level model the byte budget is split by, and it is MEASURED,
167/// not the old flat "a hidden frame is worth two leaves" guess: the long-GOP
168/// census (`lanes/rc.report.md`, films A and B at three quantizers each,
169/// `lanes/census-longgop-v2.md`'s q150 row among them) reads a level's
170/// bytes/frame as very close to log-linear in its own q offset, at
171/// d(ln bytes)/d(q_idx) = -0.0557 -- three and a half times the SLOPE of the
172/// controller's own `RateLoop::GAIN` (0.0154), because a deeper level is not
173/// just quantized finer, it also carries the group's residual for every
174/// frame that predicts off it.
175const WEIGHT_LEVEL_GAIN: f64 = 0.0557;
176
177/// The key frame's own correction on top of `WEIGHT_LEVEL_GAIN`: an intra
178/// frame at the key's offset codes this much of what the level model alone
179/// predicts (the census's key frames are consistently smaller than the pure
180/// exponential, since the exponential is fitted on INTER levels whose size
181/// keeps growing with reference depth).
182const KEY_WEIGHT: f64 = 1.08;
183
184/// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and
185/// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from
186/// the calibration sweep's own log-linear slope (bytes roughly halve every
187/// ~45 `q_idx` steps there, i.e. `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped
188/// per frame. Pure proportional — no accumulated error term — is the windup
189/// bound itself ([[vorbis-rate-loop-windup]]'s class): the only state carried
190/// between frames is `q`, already clamped to `0..=255`, so a quiet lead-in
191/// cannot build a debt a later transient has to repay; each frame's step is
192/// bounded by `STEP_CLAMP` regardless of history.
193///
194/// In pyramid mode the state is kept PER LEVEL: each frame's size is
195/// predicted from the previous frame of its own level, against that level's
196/// own share of the budget, which is the whole "two-pass-free model" this
197/// encoder carries.
198#[derive(Debug, Clone, Copy)]
199struct RateLoop {
200 /// Byte target per level, indexed by [`RateLoop::slot`].
201 target: [f64; 3],
202 /// Quantizer per level, same index.
203 q: [f64; 3],
204 /// Whether the three slots are actually distinct (pyramid mode) or all
205 /// one shared controller (the flat path, unchanged from before levels
206 /// existed).
207 per_level: bool,
208 /// Whether each slot has already steered off a real coded frame. The
209 /// FIRST update of a slot is the seeding one and takes the model's whole
210 /// step ([`RateLoop::update`]); every later one is clamped.
211 seeded: [bool; 3],
212 /// The leaf's own q offset: the zero of the level weight
213 /// ([`WEIGHT_LEVEL_GAIN`]), so slot 1's target can be read in
214 /// LEAF-EQUIVALENT bytes and scaled per frame by that frame's offset.
215 leaf_q_offset: i16,
216 /// The key frame's own leaf-equivalent weight ([`KEY_WEIGHT`]).
217 key_weight: f64,
218 /// The leaf-equivalent weight of a whole run (key included), and the
219 /// run's whole byte budget (`gop` frame targets): what a run RE-PLANS
220 /// from, and what a key frame resets the re-plan to.
221 run_weight: f64,
222 run_bytes: f64,
223 /// What is left of both, ahead of the next frame.
224 left_weight: f64,
225 left_bytes: f64,
226}
227
228impl RateLoop {
229 /// The steepest a single frame is allowed to move `base_q_idx`, in
230 /// either direction — chosen so one wildly over/under-sized frame
231 /// (a scene cut, a black lead-in) nudges the next frame's quantizer
232 /// rather than slamming it to an extreme.
233 const STEP_CLAMP: f64 = 12.0;
234 /// The calibration sweep's own slope (see the struct doc), inverted to
235 /// convert a bytes ratio into a `q_idx` step.
236 const GAIN: f64 = 1.0 / 0.0154;
237
238 fn new(target_bytes: f64, start_q: f64, pyramid: Option<Pyramid>, gop: usize) -> Self {
239 let Some(p) = pyramid else {
240 return Self {
241 target: [target_bytes; 3],
242 q: [start_q; 3],
243 per_level: false,
244 seeded: [false; 3],
245 leaf_q_offset: 0,
246 key_weight: 1.0,
247 run_weight: 0.0,
248 run_bytes: 0.0,
249 left_weight: 0.0,
250 left_bytes: 0.0,
251 };
252 };
253 // THE LEVEL MODEL. Every coded frame of the run is priced by its own
254 // q offset through `WEIGHT_LEVEL_GAIN`, in units of one leaf, and the
255 // run's `gop` frame targets are shared out in those units. The old
256 // model priced a group as "one hidden frame worth `ARF_WEIGHT` = 2
257 // leaves plus `m - 1` leaves", which was wrong twice over and the two
258 // errors cancelled (lane-pyr6): the group has coded TWO hidden frames
259 // since the mid level landed (four with
260 // [`Pyramid::quarter_q_offset`]), and a hidden frame is worth far
261 // more than two leaves -- the census reads the top ARF at 24x a leaf
262 // and the mid at 5x. Both are fixed here, in one diff.
263 let w = |offset: i16| {
264 ((f64::from(p.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp()
265 };
266 let (hidden, leaves) = gop_shape(p, gop);
267 let key = KEY_WEIGHT * w(p.key_q_offset);
268 let total: f64 = key
269 + leaves as f64
270 + hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum::<f64>();
271 // One leaf's byte target: the run is worth `gop` frame targets and
272 // `total` leaves.
273 let scale = target_bytes * gop.max(1) as f64 / total.max(f64::EPSILON);
274 // THE HIDDEN SLOT holds every hidden level at once (`Level::Arf` is
275 // the top ARF, the mid and the quarters alike -- one controller,
276 // different q offsets), so its target is kept in LEAF-EQUIVALENT
277 // bytes and [`RateLoop::update`] scales it by the coded frame's own
278 // `w(offset)`. Measuring each hidden frame against its OWN predicted
279 // size is what keeps the shared slot from oscillating between the
280 // levels it mixes.
281 Self {
282 target: [scale * key, scale, scale],
283 q: [start_q; 3],
284 per_level: true,
285 seeded: [false; 3],
286 leaf_q_offset: p.leaf_q_offset,
287 key_weight: key,
288 run_weight: total,
289 run_bytes: target_bytes * gop.max(1) as f64,
290 left_weight: total,
291 left_bytes: target_bytes * gop.max(1) as f64,
292 }
293 }
294
295 /// What a frame coded `offset` steps off `base_q_idx` is worth in
296 /// leaf-equivalent bytes ([`WEIGHT_LEVEL_GAIN`]).
297 fn weight(&self, offset: i16) -> f64 {
298 ((f64::from(self.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp()
299 }
300
301 /// Which controller a level uses: one shared slot on the flat path, three
302 /// separate ones under a pyramid.
303 fn slot(&self, level: Level) -> usize {
304 if !self.per_level {
305 return 0;
306 }
307 match level {
308 Level::Key => 0,
309 Level::Arf => 1,
310 // A `show_existing_frame` packet codes no pixels and never
311 // reaches `update`; it shares the leaf slot so `q_idx` is total.
312 Level::Leaf | Level::ShowExisting => 2,
313 }
314 }
315
316 fn q_idx(&self, level: Level) -> u8 {
317 self.q[self.slot(level)].round().clamp(0.0, 255.0) as u8
318 }
319
320 /// Steers this level's `q` toward its own target from the frame's actual
321 /// coded size.
322 fn update(&mut self, level: Level, offset: i16, actual_bytes: usize) {
323 let slot = self.slot(level);
324 if self.target[slot] <= 0.0 || actual_bytes == 0 {
325 return;
326 }
327 // A hidden frame is measured against ITS OWN level's predicted size:
328 // slot 1's target is in leaf-equivalent bytes.
329 let frame_weight = match slot {
330 0 => self.key_weight,
331 1 => self.weight(offset),
332 _ => 1.0,
333 };
334 let target = match self.per_level && slot == 1 {
335 true => self.target[slot] * frame_weight,
336 false => self.target[slot],
337 };
338 let ratio = actual_bytes as f64 / target;
339 // `STEP_CLAMP` protects an operating point this slot has not found
340 // yet: its `q` is still the caller's `base_q_idx` guess, and the
341 // clamp makes the loop WALK to the right quantizer at twelve steps a
342 // frame. Measured on the 48-frame bitrate gate, the pyramid's ARF
343 // slot spent five of its twelve frames pinned at `-STEP_CLAMP` and
344 // the stream landed -10.2% under target -- convergence lag, not a
345 // steady-state offset (the fixed point of this loop is `actual ==
346 // target` exactly). So a slot's FIRST frame takes the model's whole
347 // step and seeds `q` where the log-linear slope says it belongs; from
348 // the second frame on the clamp is back, and nothing is accumulated
349 // between frames, so [[vorbis-rate-loop-windup]]'s bound still holds.
350 let raw = ratio.ln() * Self::GAIN;
351 let step = if std::mem::replace(&mut self.seeded[slot], true) {
352 raw.clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP)
353 } else {
354 raw
355 };
356 self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0);
357 self.replan(level, frame_weight, actual_bytes as f64);
358 }
359
360 /// Re-plans the REST OF THE RUN from what it has actually spent: the
361 /// level model says how the budget SPLITS, and nothing but a measurement
362 /// says what a frame of this content costs at all.
363 ///
364 /// Two frames of a run cannot be steered by the loop and both are pure
365 /// model error without this: the KEY, coded once at the caller's seed `q`
366 /// before anything has been measured (the census's key frames run 0.5x to
367 /// 2.7x the model across the two films), and any level whose `q` has hit
368 /// the floor -- at 3 Mbit/s on the gate's clip the hidden slot codes at
369 /// `q_idx` 1 and physically cannot spend its share, which the leaves must
370 /// then absorb or the stream lands a third under target.
371 ///
372 /// It is NOT an accumulated error term in `q` ([[vorbis-rate-loop-windup]]
373 /// is about exactly that): `q` still moves only by this frame's own
374 /// clamped proportional step, the re-plan only moves the TARGET the next
375 /// frame is measured against, and every key frame resets the whole plan,
376 /// so no debt outlives one run.
377 fn replan(&mut self, level: Level, frame_weight: f64, actual_bytes: f64) {
378 if !self.per_level {
379 return;
380 }
381 if level == Level::Key {
382 self.left_weight = self.run_weight;
383 self.left_bytes = self.run_bytes;
384 }
385 self.left_weight -= frame_weight;
386 self.left_bytes -= actual_bytes;
387 // The tail of a run is not re-planned: under a leaf's worth of weight
388 // left, the division is noise.
389 if self.left_weight <= 1.0 {
390 return;
391 }
392 let scale = (self.left_bytes / self.left_weight).max(0.0);
393 self.target = [scale * self.key_weight, scale, scale];
394 }
395}
396
397/// What [`Av1Encoder::new`] takes: geometry, rate, key-frame cadence and
398/// colour. `base_q_idx` is picked directly (0..=255, `crate::encode`'s own
399/// unit) rather than a bitrate — a bitrate control loop is not part of this
400/// lane's charter, and a caller that wants one can still derive a
401/// `base_q_idx` from its own target and set that field. A caller who wants
402/// [`RateTarget`]'s quality/size dials instead of picking `base_q_idx`
403/// itself uses [`Av1Encoder::with_rate_target`], which still starts from an
404/// `EncoderConfig` (its `base_q_idx` is the loop's seed/fallback for
405/// [`RateTarget::BytesPerFrame`], and is overwritten outright for the other
406/// two variants).
407#[derive(Debug, Clone, Copy)]
408pub struct EncoderConfig {
409 /// The picture's width in luma samples; must be even and nonzero.
410 pub width: usize,
411 /// The picture's height in luma samples; must be even and nonzero.
412 pub height: usize,
413 /// The quantizer index every frame is coded at (0..=255).
414 pub base_q_idx: u8,
415 /// Pictures between key frames, inclusive of the key frame itself: `1`
416 /// codes every picture as a key frame, `gop` codes picture `gop` (and
417 /// `2*gop`, ...) as a key frame and every other picture inter.
418 pub gop: usize,
419 /// The colour the sequence header signals.
420 pub colour: Colour,
421 /// `TileColsLog2` (spec 5.9.15): the frame is split into `1 <<
422 /// tile_cols_log2` uniformly spaced tile columns, each coded and
423 /// decodable on its own. `0` -- one tile column -- is the default and
424 /// is byte for byte the stream this encoder wrote before tiles existed.
425 pub tile_cols_log2: u32,
426 /// `TileRowsLog2`, the same down the rows.
427 pub tile_rows_log2: u32,
428}
429
430impl EncoderConfig {
431 /// A config at `width`x`height` with one tile, `gop` pictures between
432 /// key frames and no colour signalling -- what every caller that does
433 /// not care about tiles writes, so that adding a field here does not
434 /// rewrite them.
435 #[must_use]
436 pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self {
437 Self {
438 width,
439 height,
440 base_q_idx,
441 gop,
442 colour,
443 tile_cols_log2: 0,
444 tile_rows_log2: 0,
445 }
446 }
447}
448
449/// One coded picture: its OBUs, in the order a demuxer that just wants bytes
450/// on the wire can concatenate them, and the two things a muxer needs to
451/// know without parsing them back out.
452#[derive(Debug, Clone)]
453pub struct Packet {
454 /// A temporal delimiter, a sequence header and the frame OBU for a key
455 /// frame; a temporal delimiter and the frame OBU alone for an inter
456 /// frame (the sequence header is identical across a stream's key
457 /// frames, since only [`EncoderConfig`]'s own fields feed it, so it is
458 /// simplest to let every key frame carry its own copy rather than have
459 /// the facade special-case the first one).
460 pub data: Vec<u8>,
461 /// Whether this picture was coded as a key frame.
462 pub key: bool,
463 /// This picture's position in DISPLAY (presentation) order, starting at
464 /// 0 — a muxer's `pts` in picture units. Without a [`Pyramid`] this is
465 /// also the coding order and equals `dts`.
466 pub order: u64,
467 /// This packet's position in CODING (decode) order, starting at 0 — a
468 /// muxer's `dts` in packet units. With a [`Pyramid`] the hidden frame of
469 /// each mini-GOP is coded before the leaves it precedes in display order,
470 /// so `dts` and `order` diverge, and the `show_existing_frame` packet
471 /// that re-outputs the hidden frame carries the hidden frame's own
472 /// `order` with its own later `dts`.
473 pub dts: u64,
474 /// Which pyramid level this packet is.
475 pub level: Level,
476}
477
478/// One mini-GOP of a two-level coding pyramid, and the quantizer offsets its
479/// two levels are coded at. libaom's `gf_group` shape, cut down to the two
480/// levels this encoder's reference set can carry: the last picture of each
481/// mini-GOP is coded FIRST, hidden (`show_frame == 0`), as the group's
482/// `ALTREF_FRAME`, then the pictures before it are coded as shown leaves that
483/// may predict backward off it, and finally a `show_existing_frame` header
484/// re-outputs the hidden frame in its own display position.
485#[derive(Debug, Clone, Copy, PartialEq, Eq)]
486pub struct Pyramid {
487 /// Pictures per mini-GOP: the hidden frame is `mini_gop` pictures ahead
488 /// of the group's anchor, and `mini_gop - 1` leaves sit between them.
489 /// `1` would leave no leaf at all and is refused. It is the group size a
490 /// long run takes; the last group of a run is up to 1.5x it, since
491 /// [`group_target`] absorbs a tail shorter than half a group rather than
492 /// leaving one behind.
493 pub mini_gop: usize,
494 /// Added to `base_q_idx` for the hidden `ALTREF_FRAME` — negative, since
495 /// every leaf of the group predicts off it.
496 pub arf_q_offset: i16,
497 /// Added to `base_q_idx` for each shown leaf — positive, since nothing
498 /// predicts off a leaf but the next leaf.
499 pub leaf_q_offset: i16,
500 /// THE THIRD LEVEL, or `None` for the two-level pyramid: the offset a
501 /// second hidden frame, at the middle of the mini-GOP, is coded at
502 /// (between [`Pyramid::arf_q_offset`] and [`Pyramid::leaf_q_offset`], so
503 /// the group reads key -> top ARF -> mid ARF -> leaves). The leaves
504 /// before it name it as their `ALTREF_FRAME` and the leaves after it
505 /// start their chain from it, which halves every leaf's distance to its
506 /// nearest good reference. Ignored by a group of fewer than four
507 /// pictures, where there is no leaf on both sides of a midpoint.
508 pub mid_q_offset: Option<i16>,
509 /// THE FOURTH LEVEL, or `None` for the three-level pyramid: the offset
510 /// the two hidden QUARTER-POINT ARFs are coded at (between
511 /// [`Pyramid::mid_q_offset`] and [`Pyramid::leaf_q_offset`], so the group
512 /// reads key -> top ARF -> mid ARF -> quarter ARFs -> leaves). In a group
513 /// of eight they sit at pictures 2 and 6, halving again the distance from
514 /// a leaf to its nearest good reference; every leaf then names the
515 /// nearest hidden frame on each side. Ignored by a group with fewer than
516 /// seven leaves, where a quarter point has no leaf on both sides, and --
517 /// like the mid level -- by a run no longer than one mini-GOP.
518 pub quarter_q_offset: Option<i16>,
519 /// Added to `base_q_idx` for the GOP's KEY FRAME — negative, since every
520 /// frame of the run reads it, directly or through an ARF. The 48-frame
521 /// census (`lanes/census-longgop.md`) found ours coded at base q while
522 /// its own ARFs sat 32 steps finer, where rav1e (key 100 / arf 120 /
523 /// leaf 153) and libaom (63 / 95 / 163) both make the key the best frame
524 /// of the run and spend 22--37% of the stream on it against our 10--11%.
525 pub key_q_offset: i16,
526}
527
528/// How many pictures the mini-GOP now being collected takes, given how many
529/// are left in this run (the pictures before the next key frame) and the
530/// [`Pyramid::mini_gop`] shape.
531///
532/// A fixed `mini_gop` leaves a SHORT TAIL group whenever the run is not a
533/// multiple of it: a 12-picture GOP under `mini_gop` 8 codes 8 + 3, and that
534/// 3-picture tail is the expensive part -- the 12-frame gate preferred one
535/// group of 11 by 7.0 / 20.5 BD points while the 48-frame gate picked 8
536/// (lane-pyr4). The rule here ABSORBS a tail shorter than half a group into
537/// the group before it, so a run takes groups of `mini_gop` until at most
538/// 1.5 x `mini_gop` is left and then one final group of all of it:
539/// remaining 11 under 8 -> 11 (was 8 + 3)
540/// remaining 47 under 8 -> 8, 8, 8, 8, 8, 7 -- what the fixed rule already
541/// coded, so a long GOP is byte-identical
542/// (`the_mini_gop_layout_leaves_no_short_tail`; sweep `lanes/gopad.sweep.txt`).
543///
544/// `EC_AV1_GOP_LAYOUT=fixed` restores the old fixed-size rule for an A/B.
545fn group_target(remaining: usize, mini_gop: usize, absorb_tail: bool) -> usize {
546 match absorb_tail && remaining <= mini_gop + mini_gop / 2 {
547 true => remaining.max(1),
548 false => mini_gop,
549 }
550}
551
552/// How one GOP of `gop` pictures is actually coded, as [`Av1Encoder::encode_frames`]
553/// and [`Av1Encoder::drain_pending`] lay it out: the HIDDEN frames as
554/// `(q offset, count)` (the group's top `ALTREF`, the mid level and the two
555/// quarter-point ARFs, each at its own offset) and the number of shown
556/// leaves. The key frame is the remaining picture and is not listed.
557///
558/// This is what [`RateLoop::new`] prices the run by, so the two must agree on
559/// the gating rules -- a mid level needs three leaves and a run longer than
560/// 1.5 mini-GOPs, quarters need seven leaves and a mid -- which
561/// `the_rate_loop_prices_the_frames_the_pyramid_codes` pins against the real
562/// packet stream.
563fn gop_shape(p: Pyramid, gop: usize) -> (Vec<(i16, usize)>, usize) {
564 let (mut hidden, mut leaves) = (Vec::<(i16, usize)>::new(), 0usize);
565 let mut add = |offset: i16, n: usize| match hidden.iter_mut().find(|(o, _)| *o == offset) {
566 Some((_, c)) => *c += n,
567 None => hidden.push((offset, n)),
568 };
569 let long_run = gop > p.mini_gop + p.mini_gop / 2;
570 let mut left = gop.saturating_sub(1);
571 while left > 0 {
572 let g = group_target(left, p.mini_gop, absorb_tail()).min(left);
573 left -= g;
574 if g == 1 {
575 leaves += 1;
576 continue;
577 }
578 let inner = g - 1;
579 add(p.arf_q_offset, 1);
580 let mid = p.mid_q_offset.filter(|_| inner >= 3 && long_run);
581 let quarters = mid.and(p.quarter_q_offset).filter(|_| inner >= 7);
582 if let Some(o) = mid {
583 add(o, 1);
584 }
585 if let Some(o) = quarters {
586 add(o, 2);
587 }
588 leaves += inner - usize::from(mid.is_some()) - 2 * usize::from(quarters.is_some());
589 }
590 (hidden, leaves)
591}
592
593/// Whether this run absorbs a short tail group (the default) or cuts every
594/// mini-GOP at `mini_gop`: `EC_AV1_GOP_LAYOUT=fixed`, read once.
595fn absorb_tail() -> bool {
596 static ABSORB: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
597 std::env::var("EC_AV1_GOP_LAYOUT").ok().as_deref() != Some("fixed")
598 });
599 *ABSORB
600}
601
602impl Pyramid {
603 /// The pyramid a run asks for through the environment:
604 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>[:<mid>[:<key>]]]`,
605 /// where `<mid>` is the third level's offset or `off` for none, with
606 /// `0` (or anything that is not a mini-GOP of at least 2, e.g. `flat`)
607 /// meaning the flat one-picture-one-frame path. UNSET is
608 /// [`Pyramid::default`]: the pyramid is what
609 /// [`crate::encode::encode_sequence`], the BD gate and `ec-bench` code
610 /// under unless a run turns it off for an A/B.
611 #[must_use]
612 pub fn from_env() -> Option<Self> {
613 let d = Self::default();
614 let Some(spec) = std::env::var("EC_AV1_PYRAMID").ok() else {
615 return Some(d);
616 };
617 let mut f = spec.split(':');
618 let mini_gop: usize = f.next().and_then(|v| v.parse().ok()).unwrap_or(0);
619 if mini_gop < 2 {
620 return None;
621 }
622 Some(Self {
623 mini_gop,
624 arf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.arf_q_offset),
625 leaf_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.leaf_q_offset),
626 // A fourth field is the mid-level offset; the literal `off` asks
627 // for the two-level pyramid at the same shape (the A/B arm the
628 // sweep needs), and no field at all keeps the default's.
629 mid_q_offset: match f.next() {
630 None => d.mid_q_offset,
631 Some("off") => None,
632 Some(v) => v.parse().ok().or(d.mid_q_offset),
633 },
634 // A fifth field is the key frame's own offset.
635 key_q_offset: f.next().and_then(|v| v.parse().ok()).unwrap_or(d.key_q_offset),
636 // A sixth field is the quarter level's offset, `off` for none.
637 quarter_q_offset: match f.next() {
638 None => d.quarter_q_offset,
639 Some("off") => None,
640 Some(v) => v.parse().ok().or(d.quarter_q_offset),
641 },
642 })
643 }
644}
645
646impl Default for Pyramid {
647 /// The best point of the offset sweep run through the BD gate's own
648 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` knob
649 /// (`encode::tests::bd_rate_vs_libaom_and_rav1e`, 12 frames of each of
650 /// the three gate clips, BD-rate vs libaom / vs rav1e, wall = the four
651 /// encodes of the ladder together).
652 ///
653 /// First sweep, before the motion-search lane merged (its extra-reference
654 /// `NEWMV` is exactly what a pyramid leaf needs to reach its hidden
655 /// frame), so read it for the OFFSETS, not for the verdict:
656 ///
657 /// | mini_gop:arf:leaf | 1080p | 2160p | screen |
658 /// |---|---|---|---|
659 /// | flat (no pyramid) | +122.7 / +73.4 | +147.3 / +98.5 | +79.4 / +17.2 |
660 /// | 4:0:0 | +152.2 / +97.9 | +214.7 / +158.1 | +91.4 / +26.2 |
661 /// | 4:-16:8 | +139.9 / +87.1 | +201.5 / +143.7 | +78.5 / +19.5 |
662 /// | 4:-24:12 | +141.3 / +85.0 | +190.0 / +132.9 | +84.5 / +22.8 |
663 /// | 2:0:0 | +149.3 / +93.1 | +203.0 / +149.4 | +88.3 / +23.6 |
664 /// | 2:-8:4 | +143.1 / +89.1 | +196.2 / +141.6 | +82.5 / +20.4 |
665 /// | 2:-16:8 | +137.6 / +84.5 | +187.2 / +130.6 | +84.9 / +23.1 |
666 ///
667 /// `0:0` is the worst row at both mini-GOP sizes and `-16/+8` buys 12-16
668 /// BD points over it, in the direction libaom's `gf_group` spends them
669 /// (lowest quantizer on the frame everything else predicts from). Those
670 /// are these defaults.
671 ///
672 /// Re-measured after that lane merged (wall ours, 1080p/2160p/screen):
673 ///
674 /// | arm | 1080p | 2160p | screen | wall |
675 /// |---|---|---|---|---|
676 /// | flat (no pyramid) | +121.1 / +71.8 | +146.1 / +97.5 | +79.3 / +17.2 | 6.3 / 5.8 / 6.2 s |
677 /// | 4:-16:8 | +131.9 / +81.1 | +178.7 / +123.6 | +78.4 / +19.5 | 6.2 / 5.6 / 5.5 s |
678 /// | 2:-16:8 | +125.4 / +76.2 | +173.0 / +119.5 | +84.9 / +23.1 | 6.2 / 5.6 / 6.2 s |
679 ///
680 /// So the pyramid still does NOT pay, and ships OFF: it wins 0.9 points
681 /// on screen capture at `4:-16:8` and loses 11 on 1080p and 33 on 2160p.
682 /// What keeps it from paying, in the order the numbers point at it:
683 ///
684 /// * The hidden frame predicts `mini_gop` pictures ahead of its own
685 /// reference with the SAME forward search a neighbouring frame gets,
686 /// and it is the largest frame in the group (73.8 kB of the 1080p
687 /// ladder's 184 kB at `4:-16:8`). On the 2160p clip, whose motion the
688 /// search only just reaches at distance 1, distance 4 is where it
689 /// falls off — that clip loses twice what 1080p does, and shrinking
690 /// the mini-GOP to 2 recovers most of the gap (+178.7 -> +173.0,
691 /// +131.9 -> +125.4). A distance-scaled search range is the fix, and
692 /// it lives in the motion-search lane, not here.
693 /// * The leaves reach the hidden frame through the extra-reference
694 /// modes only: `ALTREF_FRAME` wins about 13% of blocks
695 /// (`encode::take_ref_frame_hits`, printed by the round-trip test),
696 /// up from 4% before the motion lane merged. A compound
697 /// (`LAST` + `ALTREF`) prediction mode is the other half of what a
698 /// real B frame buys, and this crate codes no compound blocks at all.
699 ///
700 /// Neither is a defect in the pyramid itself: the reordering is exact
701 /// (`encoder::tests::a_pyramid_stream_decodes_in_display_order_through_both_decoders`
702 /// checks every shown frame in display order against ffmpeg AND our own
703 /// decoder, with the hidden frame proven to win blocks), and the
704 /// Re-measured a third time at NATIVE resolution (`encode::tests::
705 /// bd_rate_screen_native`, 1920x1024 crops, 12 frames, four quantizers,
706 /// BD-rate vs libaom / vs rav1e), because every earlier verdict was taken
707 /// on the 4x-downscaled gate (class `gate-recipe-confound`) and because
708 /// leaf compound and the distance-scaled search have landed since:
709 ///
710 /// | arm | film 1080p | film 2160p | screen |
711 /// |---|---|---|---|
712 /// | flat (no pyramid) | +18.7 / +1.4 | +48.1 / +19.8 | +59.4 / -10.0 |
713 /// | 4:-16:8 | +23.2 / +5.3 | +48.1 / +19.7 | +62.7 / -6.5 |
714 /// | 2:-16:8 | +24.9 / +6.9 | +46.9 / +19.5 | +69.0 / -3.8 |
715 /// | 8:-16:8 | +22.6 / +4.6 | +48.7 / +19.8 | +59.3 / -8.2 |
716 /// | 4:-24:12 (before the leaf-compound merge) | +24.3 / +6.3 | +48.5 / +20.2 | +67.2 / -3.7 |
717 ///
718 /// The confound was real -- at native the gap is 5 BD points, not 30 --
719 /// but the sign is not: no arm beats flat on both films, every arm costs
720 /// 4-6 points on 1080p, and the best 2160p arm (`2:-16:8`, -1.1 vs
721 /// libaom) pays +10 on screen. So the pyramid still ships OFF.
722 ///
723 /// A native offset sweep on the 2160p clip alone (mini-GOP 4) says the
724 /// offsets are not what is missing -- the whole 3x3 grid spans 2.9 BD
725 /// points and none of it reaches flat's +48.1:
726 ///
727 /// | arf \ leaf | +4 | +8 | +12 |
728 /// |---|---|---|---|
729 /// | -8 | +48.9 / +20.4 | +49.2 / +20.1 | +50.2 / +20.5 |
730 /// | -16 | +47.8 / +20.0 | +48.1 / +19.7 | +49.2 / +20.2 |
731 /// | -24 | +47.3 / +20.0 | +47.6 / +19.7 | +48.5 / +20.2 |
732 ///
733 /// The gradient is monotone in both knobs (deeper ARF better, shallower
734 /// leaf better), which is the shape of a group whose leaves cannot cash
735 /// in the ARF's extra quality: what the leaves reach the hidden frame
736 /// with is still one forward search per reference. Shrinking the mini-GOP
737 /// helps for the same reason (2:-16:8 is the only arm that beats flat on
738 /// any clip, and it beats it on the clip with the fastest motion).
739 ///
740 /// RE-SWEPT on lane-av1pyrgate, once the content gate below existed and
741 /// on the current defaults (`LAMBDA_SCALE` 0.0275, the 32x32 tx-depth
742 /// search and compound var-tx on): the earlier verdicts were taken with
743 /// the screen capture inside the arm, and it is the one clip a pyramid
744 /// never helps. With the gate, the screen row is the flat row by
745 /// construction, so the sweep is decided on the two real films
746 /// (`encode::tests::bd_rate_screen_native`, BD-rate vs libaom / vs
747 /// rav1e; bars are fixtures, recorded only):
748 ///
749 /// | arm | film A | film B | screen | bars 1080p | bars 2160p |
750 /// |---|---|---|---|---|---|
751 /// | flat (no pyramid) | +62.8 / +32.5 | +86.3 / +50.5 | +50.1 / -15.4 | +16.4 / -1.1 | +48.2 / +20.4 |
752 /// | 2:-16:8 | +60.3 / +29.1 | +83.6 / +50.2 | +50.1 / -15.4 | +24.0 / +5.9 | +47.2 / +20.2 |
753 /// | **4:-16:8** | **+54.1 / +24.2** | **+82.6 / +47.4** | +50.1 / -15.4 | +21.5 / +3.7 | +48.3 / +20.4 |
754 /// | 8:-16:8 | +55.9 / +25.8 | +83.6 / +47.3 | +50.1 / -15.4 | +19.8 / +2.0 | +48.7 / +20.4 |
755 /// | 4:-24:12 | +51.5 / +22.3 | +84.9 / +50.3 | +50.1 / -15.4 | +21.9 / +4.0 | +48.4 / +20.7 |
756 /// | 4:-12:6 | +57.6 / +27.1 | +84.8 / +49.3 | +50.1 / -15.4 | +21.7 / +3.9 | +48.8 / +20.9 |
757 ///
758 /// `4:-16:8` is the only arm that improves BOTH films on BOTH columns by
759 /// several points (-8.7 / -8.3 on film A, -3.7 / -3.1 on film B) and it
760 /// stays these defaults. `4:-24:12` buys another 2.6 on film A and gives
761 /// 2.3 back on film B (where it barely beats flat vs rav1e, -0.2), which
762 /// is the same "leaves cannot cash in the ARF's quality" shape as before,
763 /// now content-dependent rather than uniform. The screen column is
764 /// IDENTICAL in every arm -- that is the content gate, measured, not
765 /// asserted. `EC_AV1_LAMBDA=0.035` on top of `4:-16:8` was re-judged once
766 /// (the pyramid changes the reference structure): +54.5 / +24.5 and
767 /// +85.2 / +49.4, worse on both films, so 0.0275 stands.
768 ///
769 /// SHIPPED AS THE DEFAULT on lane-av1pyrdef. `4:-16:8` is what
770 /// [`crate::encode::encode_sequence`] (through
771 /// [`Av1Encoder::encode_sequence_pyramid`], the one mini-GOP driver both
772 /// paths run), the BD gates and `ec-bench` code a non-screen stream
773 /// under; a screen stream still codes flat, decided once per stream by
774 /// the content gate in [`Av1Encoder::encode_frames`]. `EC_AV1_PYRAMID=0`
775 /// restores the flat path everywhere for an A/B, and
776 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf>:<leaf>]` another shape of it
777 /// ([`Pyramid::from_env`]).
778 ///
779 /// [`Av1Encoder::new`] is unchanged: the one-picture-one-packet facade
780 /// entry point still codes flat, since a picture no longer maps to a
781 /// packet under a pyramid — [`Av1Encoder::with_pyramid`] plus
782 /// [`Av1Encoder::encode_frames`] is the streaming surface that reorders.
783 /// RE-SWEPT on lane-pyr3, on main 503d7aa9 -- `4:-16:8` was chosen when
784 /// the gate's "film" rows were still colour bars, and CfL, the luma
785 /// angle deltas, filter intra, the propagating tpl map and the rate-loop
786 /// step have all landed since (class `unswept decision constants`). The
787 /// axes were swept in the order mini-GOP first at the shipped offsets,
788 /// then both offset axes at the best mini-GOP, then the joint corners
789 /// (`encode::tests::bd_rate_screen_native`, BD-rate vs libaom / vs
790 /// rav1e; the bars rows move by at most 4 points across the WHOLE sweep
791 /// and decide nothing, the screen row is byte-identical in every arm
792 /// because the content gate codes it flat):
793 ///
794 /// | arm | film A | film B |
795 /// |---|---|---|
796 /// | flat (no pyramid) | +61.4 / +31.3 | +85.3 / +49.7 |
797 /// | 2:-16:8 | +59.2 / +28.1 | +82.3 / +49.1 |
798 /// | 4:-16:8 (was shipped) | +52.8 / +23.3 | +81.0 / +46.1 |
799 /// | 8:-16:8 | +54.3 / +24.4 | +81.8 / +45.8 |
800 /// | 16:-16:8 | +50.8 / +21.4 | +73.8 / +38.7 |
801 /// | 8:-8:8 | +58.0 / +27.5 | +83.3 / +46.5 |
802 /// | 8:-24:8 | +52.7 / +23.4 | +83.7 / +48.4 |
803 /// | 8:-32:8 | +52.3 / +23.1 | +86.8 / +51.9 |
804 /// | 8:-16:0 | +60.7 / +30.7 | +85.3 / +51.2 |
805 /// | 8:-16:4 | +57.6 / +27.4 | +84.1 / +48.6 |
806 /// | 8:-16:12 | +51.8 / +22.2 | +80.4 / +43.9 |
807 /// | 8:-16:16 | +50.1 / +20.5 | +80.6 / +43.4 |
808 /// | 16:-24:8 | +47.8 / +19.0 | +71.5 / +37.4 |
809 /// | 16:-16:12 | +48.0 / +18.9 | +71.1 / +35.7 |
810 /// | 16:-16:16 | +45.9 / +17.0 | +69.3 / +34.0 |
811 /// | 16:-24:12 | +45.6 / +17.0 | +70.2 / +35.6 |
812 /// | **16:-24:16** | **+44.2 / +15.7** | **+70.5 / +35.2** |
813 /// | 16:-32:16 | +43.6 / +15.2 | +71.2 / +36.2 |
814 /// | 16:-24:20 (past the swept range) | +42.9 / +14.5 | +70.8 / +34.9 |
815 /// | 16:-24:24 (past the swept range) | +42.6 / +14.1 | +71.3 / +35.7 |
816 ///
817 /// `16:-24:16` ships: it takes 8.6 / 7.6 points off film A and 10.5 /
818 /// 10.9 off film B against the old defaults, and every axis through it
819 /// is at or next to its own minimum. The two arms past the swept leaf
820 /// range were run because leaf `+16` was the range's edge and still
821 /// improving (class `instrument at bound`): film A keeps falling to
822 /// `+24` but film B turns back up at `+20`, so `+16` is where BOTH films
823 /// are minimal and the bound is not the answer. Deeper ARF is the same
824 /// shape -- `-32` buys 0.6 on film A and gives 0.7 back on film B.
825 ///
826 /// WHAT THAT SWEEP COULD NOT SAY, and the LONG-GOP sweep that answers it
827 /// (lane-pyr4, `lanes/pyr4.sweep.txt`). The table above is measured
828 /// against a gate that codes 12 frames with `gop = 12`, and a group is
829 /// cut at every key frame (`encode_frames`), so `16` there is really
830 /// "one hidden ARF per GOP" and ANY mini-GOP over 12 codes the same
831 /// stream (class `instrument at bound`). The user's exports are long
832 /// GOPs, so the shape is decided on
833 /// [`crate::encode::tests::bd_rate_film_long_gop`] -- 48 pictures, `gop
834 /// = 48`, the two real films, four quantizers, vs libaom `cpu-used 6`
835 /// and rav1e `speed=6` at the same key interval:
836 ///
837 /// | mini_gop:arf:leaf | film A vs libaom / rav1e | film B vs libaom / rav1e |
838 /// |---|---|---|
839 /// | 32:-24:16 | +79.0 / +29.8 | +164.4 / +58.8 |
840 /// | 16:-24:16 (was the default) | +67.4 / +21.0 | +165.5 / +57.6 |
841 /// | 8:-16:16 | +63.7 / +19.0 | +167.6 / +58.6 |
842 /// | 4:-24:16 | +61.9 / +19.5 | +160.8 / +56.7 |
843 /// | 8:-24:16 | +58.5 / +15.5 | +166.1 / +56.8 |
844 /// | 8:-24:12 | +60.2 / +17.3 | +166.8 / +58.0 |
845 /// | 8:-24:20 | +57.1 / +14.0 | +166.2 / +56.6 |
846 /// | 8:-40:16 | +56.1 / +13.3 | +167.6 / +57.3 |
847 /// | 8:-32:12 | +56.5 / +14.7 | +163.0 / +56.3 |
848 /// | 8:-32:20 | +55.4 / +12.9 | +167.9 / +57.4 |
849 /// | **8:-32:16** | **+55.7 / +13.5** | **+165.1 / +56.6** |
850 ///
851 /// `8:-32:16` ships: against the old `16:-24:16` it takes 11.7 / 7.5
852 /// points off film A and 0.4 / 1.0 off film B -- all four columns down.
853 /// A real 16- or 32-picture group is WORSE than an 8-picture one on film
854 /// A once the GOP is long enough for the distinction to exist, which the
855 /// 12-frame gate could not see; `4` was probed below the swept edge and
856 /// turns back up on film A. ARF `-32` is an interior optimum (`-40`
857 /// turns back on both films). The leaf axis has content-opposite optima
858 /// (film A wants `20`, film B wants `12`, within 1.1 and 4.9 points) so
859 /// `16` stays, being the only value down on all four columns.
860 ///
861 /// THE PRICE THAT WAS, and how it was paid (lane-gopad): on the
862 /// SHORT-GOP gate (12 frames, `gop = 12`) a fixed mini-GOP of 8 split the
863 /// run into 8 + 3 and read film A +51.2 / +21.4, film B +91.0 / +53.5,
864 /// against `16:-24:16`'s +44.2 / +15.7 and +70.5 / +35.2 -- the tail
865 /// group, not the shape, was the cost. [`group_target`] now absorbs a
866 /// short tail, so the same 12 pictures code as ONE group of 11 and read
867 /// film A +43.9 / +15.6 and film B +68.4 / +38.2 (three of the four
868 /// columns better than `16:-24:16` ever was, film B vs rav1e 3.0 short),
869 /// while 47 inter pictures still take 8 x 5 + 7 -- the long-GOP table
870 /// above is coded byte for byte as it was measured.
871 /// THE THIRD LEVEL (lane-pyr5, `lanes/pyr5.sweep.txt`), swept on the
872 /// long-GOP gate against a control arm on this very head:
873 ///
874 /// | mini_gop:arf:leaf:mid | film A vs libaom / rav1e | film B vs libaom / rav1e |
875 /// |---|---|---|
876 /// | 8:-32:16 (control, 2-level) | +55.2 / +12.8 | +151.3 / +47.4 |
877 /// | 8:-32:16:-4 | +51.8 / +11.4 | +146.2 / +45.4 |
878 /// | **8:-32:16:-8** | **+52.1 / +11.7** | **+145.3 / +45.0** |
879 /// | 8:-32:16:-16 | +53.4 / +13.0 | +146.0 / +46.1 |
880 /// | 8:-32:20:-8 | +52.4 / +11.5 | +148.0 / +46.1 |
881 /// | 16:-32:16:-8 | +55.0 / +12.3 | +146.0 / +44.3 |
882 /// | 16:-32:16:-16 | +54.6 / +12.1 | +148.7 / +46.0 |
883 /// | 4:-32:16:-8 | +61.7 / +20.4 | +147.5 / +51.3 |
884 ///
885 /// `-4` and `-8` are within a point of each other and split the two
886 /// films; `-8` ships because film B is the wider gap. A mini-GOP of 4
887 /// with a mid level -- rav1e's own shape at speed 6 -- is far worse here,
888 /// so the third level is worth more than a shorter group, and the census
889 /// (`lanes/census-longgop.md`) says why: at 8 pictures our leaves are
890 /// already cheap and the bytes sit in the ARFs.
891 ///
892 /// The 12-frame gate keeps its numbers exactly (+43.9 / +15.6 and +68.4 /
893 /// +38.2, byte-identical streams): a GOP that is one single mini-GOP does
894 /// not code the third level at all (see `drain_pending`).
895 /// THE LEAF OFFSET, RE-SWEPT ONCE THE ANCHORS MOVED (lane-arfq,
896 /// `lanes/arfq.sweep.txt`). The table above chose `16` when the key frame
897 /// still sat at the base quantizer; with [`Pyramid::key_q_offset`] at
898 /// `-48` the whole run predicts off a much finer anchor and the leaves
899 /// want to be finer with it. Long-GOP gate, control arm on the same head:
900 ///
901 /// | mini_gop:arf:leaf:mid:key | film A vs libaom / rav1e | film B vs libaom / rav1e |
902 /// |---|---|---|
903 /// | 8:-32:8:-8:-48 | +43.4 / +5.1 | +127.6 / +34.1 |
904 /// | **8:-32:12:-8:-48** | **+43.1 / +4.6** | **+129.0 / +34.3** |
905 /// | 8:-32:16:-8:-48 (control) | +43.5 / +4.6 | +131.3 / +35.0 |
906 /// | 8:-32:24:-8:-48 | +45.6 / +5.6 | +138.8 / +38.4 |
907 /// | 8:-32:12:-12:-48 | +43.4 / +5.0 | +128.1 / +33.8 |
908 /// | 8:-32:12:-16:-48 | +44.0 / +5.6 | +127.7 / +34.1 |
909 /// | 8:-24:12:-8:-48 | +44.5 / +5.2 | +128.6 / +33.3 |
910 /// | 16:-32:12:-8:-48 | +47.2 / +6.3 | +134.7 / +35.6 |
911 ///
912 /// `12` ships: film B 2.3 / 0.7 down, film A 0.4 down against libaom and
913 /// flat against rav1e. `8` is past the optimum (it buys film B and gives
914 /// film A back), `24` is worse on all four. The other two axes were
915 /// re-swept at `12` and did not move: a deeper mid (`-12`, `-16`) and a
916 /// shallower ARF (`-24`) both trade film A away for film B, so the top
917 /// ARF keeps its `-32` and the mid its `-8`. A 16-picture mini-GOP is
918 /// worse on all four -- the pyramid has exactly three levels, so one mid
919 /// frame cannot carry fifteen leaves.
920 ///
921 /// Unlike the third level this is NOT gated on GOP length: the 12-frame
922 /// gate improves on every row too (film A +38.5 / +8.2 -> +37.5 / +7.6,
923 /// film B +58.2 / +26.5 -> +54.1 / +23.9, both bars rows down, the screen
924 /// capture byte-identical).
925 fn default() -> Self {
926 Self {
927 mini_gop: 8,
928 arf_q_offset: -32,
929 leaf_q_offset: 12,
930 mid_q_offset: MID_DEFAULT,
931 key_q_offset: KEY_DEFAULT,
932 quarter_q_offset: QUARTER_DEFAULT,
933 }
934 }
935}
936
937/// Which level of the pyramid a coded frame sits at, reported on every
938/// [`Packet`] so a caller (and the BD gate's histogram) can tell them apart
939/// without parsing the frame headers back out.
940#[derive(Debug, Clone, Copy, PartialEq, Eq)]
941pub enum Level {
942 /// A key frame.
943 Key,
944 /// A hidden `ALTREF_FRAME`, coded ahead of its display position.
945 Arf,
946 /// A shown leaf.
947 Leaf,
948 /// A `show_existing_frame` header re-outputting a hidden frame: no coded
949 /// pixels at all, four bits of header.
950 ShowExisting,
951}
952
953/// The DPB slot the group anchors alternate between (see
954/// [`Av1Encoder::encode_frames`]): the hidden frame of group `g` refreshes
955/// `ANCHOR_SLOTS[(g + 1) % 2]`, which is the slot the leaves of group `g`
956/// name as `ALTREF_FRAME` and which group `g + 1` reads as its own anchor.
957/// Two slots alternate because a group's leaves must still be able to read
958/// the previous anchor while the new one is already written.
959const ANCHOR_SLOTS: [u8; 2] = [3, 4];
960
961/// The slot the leaf chain refreshes and reads as `LAST_FRAME`.
962const LEAF_SLOT: u8 = 0;
963
964/// The slot the mid-level hidden frame of a three-level group refreshes
965/// ([`Pyramid::mid_q_offset`]): free of the two anchors (3, 4), of the leaf
966/// chain (0) and of `GOLDEN_SLOT` (1), so all four levels are live at once.
967const MID_SLOT: u8 = 2;
968
969/// The two slots the QUARTER-POINT hidden frames refresh
970/// ([`Pyramid::quarter_q_offset`]). THE WHOLE SLOT MAP, with all four levels
971/// live at once:
972///
973/// | slot | holds | written by | read as |
974/// |---|---|---|---|
975/// | 0 (`LEAF_SLOT`) | the previous shown leaf | every leaf | `LAST_FRAME` of the next leaf |
976/// | 1 (`GOLDEN_SLOT`) | the key frame | the key | `GOLDEN_FRAME` everywhere |
977/// | 2 (`MID_SLOT`) | the mid ARF | the mid ARF | `LAST_FRAME` / `ALTREF_FRAME` of the leaves and quarters around it |
978/// | 3, 4 (`ANCHOR_SLOTS`) | this group's anchor and the next one (the top ARF) | the key, each top ARF | anchor = `LAST_FRAME`, next = `ALTREF_FRAME` |
979/// | 5, 6 (`QUARTER_SLOTS`) | the first and second quarter ARF | the quarter ARFs | `LAST_FRAME` / `ALTREF_FRAME` of the leaves beside them |
980/// | 7 | unused (the key's copy is never read back) | the key | -- |
981///
982/// A frame names exactly two of them plus `GOLDEN_SLOT`
983/// ([`Av1Encoder::encode_pyramid_inter`] fills all seven `ref_frame_idx`
984/// entries from `last_slot`/`altref_slot`), and `refresh_frame_flags` is the
985/// single `self_slot` bit, so no level ever overwrites a slot another level
986/// is still reading.
987const QUARTER_SLOTS: [u8; 2] = [5, 6];
988
989/// [`Pyramid::default`]'s fourth level (`None` = the three-level pyramid).
990/// The long-GOP sweep's winner (`lanes/pyr6.sweep.txt`).
991const QUARTER_DEFAULT: Option<i16> = None;
992
993/// [`Pyramid::default`]'s third level (`None` = the two-level pyramid), the
994/// long-GOP sweep's winner (`lanes/pyr5.sweep.txt`): every one of the four
995/// long-GOP columns improves against the two-level shape, film B (the wider
996/// gap) by 6.0 / 2.4 BD points.
997const MID_DEFAULT: Option<i16> = Some(-8);
998
999/// [`Pyramid::default`]'s key-frame offset: the long-GOP sweep's winner
1000/// (`lanes/keyq.sweep.txt`, 48 pictures, gop 48, BD-rate vs libaom cpu-used 6
1001/// / vs rav1e speed 6), which the 12-frame gate agrees with, so it is NOT
1002/// gated on GOP length the way the third level is:
1003///
1004/// | key offset | film A (48) | film B (48) | film A (12) | film B (12) |
1005/// |---|---|---|---|---|
1006/// | 0 (base q) | +52.0 / +11.7 | +144.5 / +44.3 | +43.3 / +15.0 | +66.9 / +35.1 |
1007/// | -16 | +48.8 / +9.4 | +138.0 / +40.2 | | |
1008/// | -32 | +45.3 / +6.7 | +132.8 / +36.8 | | |
1009/// | -48 | +43.5 / +4.6 | +131.3 / +35.0 | +38.5 / +8.2 | +58.2 / +26.5 |
1010/// | -64 | +44.9 / +3.8 | +140.7 / +37.5 | | |
1011///
1012/// `-64` overshoots on film B, and a deeper ARF (`-40`) under the same key
1013/// gives bytes back on both films (+44.4 / +5.1, +137.4 / +38.6), so what the
1014/// group was short of is the ANCHOR, not more ARF. The bars rows move by
1015/// 0.3 / 0.6 BD points and the screen capture is byte-identical (its pyramid
1016/// is gated off).
1017const KEY_DEFAULT: i16 = -48;
1018
1019/// Whether the pyramid path hands each frame a lookahead window, i.e.
1020/// whether the temporal lambda map (`encode::tpl_lambda_factors`) runs on
1021/// the DEFAULT stream at all. It did not until lane-arfcen: the pyramid
1022/// reorders pictures, so this path passed `&[]` and the map -- measured and
1023/// shipped on the flat path -- was inert on every frame of every pyramid
1024/// stream, including the ARFs that carry 54% of a long-GOP stream's bytes
1025/// (class `tool disabled in every gate recipe`).
1026fn tpl_pyramid() -> bool {
1027 match std::env::var("EC_AV1_TPL_PYRAMID").ok() {
1028 Some(v) => v != "0",
1029 None => TPL_PYRAMID,
1030 }
1031}
1032
1033/// [`tpl_pyramid`]'s default.
1034const TPL_PYRAMID: bool = true;
1035
1036/// Whether a group's TOP ARF names the ARF from TWO groups back as its own
1037/// `ALTREF_FRAME` (lane-arfcen). It has always named `GOLDEN_SLOT` there,
1038/// which for a top ARF is the key frame it already reads as `GOLDEN`, i.e.
1039/// its second reference is the same picture as its first for the first group
1040/// and adds nothing after: the ARF-vs-ARF census reads
1041/// `LAST@-8 GOLDEN@-8` on our first ARF where rav1e's reads two DISTINCT
1042/// anchors. The slot the ARF is about to refresh still holds that older
1043/// anchor while this frame is coded, so naming it costs no extra DPB slot.
1044fn arf_altref() -> bool {
1045 match std::env::var("EC_AV1_ARF_ALTREF").ok() {
1046 Some(v) => v != "0",
1047 None => ARF_ALTREF,
1048 }
1049}
1050
1051/// [`arf_altref`]'s default. ON since its long-GOP arm: film A
1052/// +42.8%/+4.5% -> +40.9%/+3.1% and film B +127.3%/+32.9% -> +125.6%/+32.0%
1053/// (BD vs libaom cpu-used 6 / vs rav1e speed 6), i.e. both films down on both
1054/// columns.
1055const ARF_ALTREF: bool = true;
1056
1057/// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per
1058/// [`Av1Encoder::encode`] call — or, with a [`Pyramid`] configured, a
1059/// coding-order burst of them per [`Av1Encoder::encode_frames`] call plus a
1060/// [`Av1Encoder::flush`] at the end of the stream.
1061#[derive(Debug)]
1062pub struct Av1Encoder {
1063 config: EncoderConfig,
1064 color_config: ColorConfig,
1065 /// The previous picture's own (padded, uncropped) reconstruction — what
1066 /// the next inter frame predicts from — or `None` right after a key
1067 /// frame's turn comes up again, where it is about to be replaced rather
1068 /// than read.
1069 reference: Option<Picture>,
1070 next_index: u64,
1071 /// `Some` only when constructed via
1072 /// [`Av1Encoder::with_rate_target`]`(_, RateTarget::BytesPerFrame(_))`;
1073 /// otherwise every picture is coded at `config.base_q_idx`, unchanged
1074 /// from before this field existed.
1075 rate_loop: Option<RateLoop>,
1076 /// This stream's decode-side per-frame state, owned here so `encode`
1077 /// keeps the public signature it had before the state stopped being
1078 /// thread-local. One per encoder, never per frame: several of its fields
1079 /// (the inter-frame inheritance guards) carry state ACROSS frames.
1080 fctx: crate::decode::FrameCtx,
1081 /// What the last coded frame stored into the reference slot the next
1082 /// inter frame reads (spec 7.20): the tables that frame's tile writer
1083 /// must start from, since the header leaves
1084 /// `disable_frame_end_update_cdf` off. `None` before the first frame.
1085 carried_cdfs: Option<crate::encode::CdfSnapshot>,
1086 /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`,
1087 /// which stays in DPB slot 1 until the next key frame refreshes it.
1088 golden: Option<Picture>,
1089 /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is
1090 /// about to refresh (`encode_inter_frame`'s 0/2 alternation).
1091 prev2: Option<Picture>,
1092 /// `Some` puts the encoder in pyramid mode: [`Av1Encoder::encode`] then
1093 /// refuses (a picture no longer maps to one packet) and the state below
1094 /// drives coding order.
1095 pyramid: Option<Pyramid>,
1096 /// The eight DPB slots, modelled exactly as the decoder does (spec 7.20):
1097 /// what picture each holds, the order hint it was coded at, and the CDF
1098 /// tables it stored. Only pyramid mode reads these; the flat path keeps
1099 /// `reference`/`golden`/`prev2` so its bytes are unchanged.
1100 dpb: [Option<DpbSlot>; 8],
1101 /// Pictures held back waiting for their mini-GOP's hidden frame.
1102 pending: Vec<(u64, Picture)>,
1103 /// The flat path's delay queue: pictures whose packets later calls
1104 /// return, each coded with the ones behind it as its lookahead window
1105 /// (lane-av1facade, deepened to [`crate::encode::tpl_depth`] - 1 on
1106 /// lane-av1tpl2). Unused in pyramid mode, which buffers in `pending`.
1107 held: std::collections::VecDeque<Picture>,
1108 /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its
1109 /// anchor.
1110 anchor: usize,
1111 /// Coding-order position of the next packet — a packet's `dts`.
1112 next_dts: u64,
1113 /// Set by [`Av1Encoder::encode_sequence_pyramid`]: every coded frame's
1114 /// own cropped [`Encoded`] (its display position and its reconstruction),
1115 /// which is what [`crate::encode::EncodedSequence`] carries and a packet
1116 /// does not. `None` for every other caller, which pays nothing for it.
1117 collected: Option<Vec<(u64, Encoded)>>,
1118}
1119
1120/// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores
1121/// and what a `ref_frame_idx` entry reads back.
1122#[derive(Debug, Clone)]
1123struct DpbSlot {
1124 picture: Picture,
1125 order_hint: u32,
1126 cdfs: crate::encode::CdfSnapshot,
1127}
1128
1129/// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are
1130/// `Send` but `!Sync`): it can move to another thread, it just cannot be
1131/// shared by reference across threads.
1132const _: fn() = || {
1133 fn assert_send<T: Send>() {}
1134 assert_send::<Av1Encoder>();
1135};
1136
1137impl Av1Encoder {
1138 /// [`Av1Encoder::new`] at a SPEED PRESET (`speed` 0..=10, rav1e's scale:
1139 /// 0 is the full search this encoder has always run and is byte for byte
1140 /// identical to [`Av1Encoder::new`]; higher presets switch search levers
1141 /// off, [`crate::speed::levers`] naming which).
1142 ///
1143 /// The preset is process-global (the tile search reads it from worker
1144 /// threads -- see [`crate::speed`]), so it is set here for every encode
1145 /// that follows on this process, and two encoders at different speeds
1146 /// must not run concurrently. `EC_AV1_SPEED=<n>` is the same knob for a
1147 /// caller that does not construct the encoder itself.
1148 ///
1149 /// # Errors
1150 /// [`Av1Encoder::new`]'s.
1151 pub fn with_speed(config: EncoderConfig, speed: u8) -> Result<Self> {
1152 crate::speed::set_speed(speed);
1153 Self::new(config)
1154 }
1155
1156 /// # Errors
1157 /// Returns an error when `config.width`/`config.height` are zero, odd,
1158 /// or larger than the 16-bit frame size an AV1 sequence header carries,
1159 /// or when `config.gop` is zero (there would be no picture to code the
1160 /// next key frame from a cadence of).
1161 pub fn new(config: EncoderConfig) -> Result<Self> {
1162 if config.gop == 0 {
1163 return Err(Error::unsupported("AV1 encode", "gop must be at least 1"));
1164 }
1165 // Validate the geometry the same way the picture-level entry points
1166 // do, before the first `encode()` call rather than only surfacing it
1167 // then.
1168 Picture::grey(config.width, config.height).check_even()?;
1169 // A tile is a whole number of superblocks, so a frame cannot carry
1170 // more tile columns (rows) than it has 64x64 superblocks across
1171 // (down) -- the header's own `max_log2_tile_cols` bound (spec
1172 // 5.9.15), refused here rather than at the first `encode()` call.
1173 let sb_cols = config.width.div_ceil(64) as u32;
1174 let sb_rows = config.height.div_ceil(64) as u32;
1175 if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows {
1176 return Err(Error::unsupported(
1177 "AV1 encode",
1178 format!(
1179 "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has",
1180 1 << config.tile_cols_log2,
1181 1 << config.tile_rows_log2
1182 ),
1183 ));
1184 }
1185 Ok(Self {
1186 carried_cdfs: None,
1187 golden: None,
1188 prev2: None,
1189 color_config: config.colour.color_config(),
1190 config,
1191 reference: None,
1192 next_index: 0,
1193 rate_loop: None,
1194 fctx: crate::decode::FrameCtx::new(),
1195 pyramid: None,
1196 dpb: [const { None }; 8],
1197 pending: Vec::new(),
1198 held: std::collections::VecDeque::new(),
1199 anchor: 0,
1200 next_dts: 0,
1201 collected: None,
1202 })
1203 }
1204
1205 /// [`Av1Encoder::new`] in pyramid mode: pictures are coded out of display
1206 /// order, so a call to [`Av1Encoder::encode_frames`] returns zero, one or
1207 /// several packets and [`Av1Encoder::flush`] drains whatever is still
1208 /// held at the end of the stream. [`Av1Encoder::encode`]'s one-in-one-out
1209 /// contract cannot hold here and it returns an error instead; a caller
1210 /// that wants the old shape simply does not call this constructor.
1211 ///
1212 /// # Errors
1213 /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be
1214 /// left between the anchor and the hidden frame) or above `config.gop`
1215 /// (the group would straddle a key frame).
1216 pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> {
1217 if pyramid.mini_gop < 2 {
1218 return Err(Error::unsupported(
1219 "AV1 encode",
1220 "a pyramid mini-GOP is at least 2 pictures",
1221 ));
1222 }
1223 let mut encoder = Self::new(config)?;
1224 encoder.pyramid = Some(pyramid);
1225 Ok(encoder)
1226 }
1227
1228 /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it,
1229 /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of
1230 /// `config.base_q_idx` being used as-is.
1231 ///
1232 /// # Errors
1233 /// Same as [`Av1Encoder::new`].
1234 pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> {
1235 let rate_loop = rate.into_loop(&mut config, None);
1236 let mut encoder = Self::new(config)?;
1237 encoder.rate_loop = rate_loop;
1238 Ok(encoder)
1239 }
1240
1241 /// [`Av1Encoder::with_pyramid`] and [`Av1Encoder::with_rate_target`] at
1242 /// once: the rate loop then keeps a separate quantizer per pyramid level,
1243 /// predicting each frame's size from the previous frame of its OWN level
1244 /// (a leaf and a hidden `ALTREF` differ by several times in size, so one
1245 /// shared predictor would swing the quantizer every frame).
1246 ///
1247 /// # Errors
1248 /// As both.
1249 pub fn with_pyramid_and_rate_target(
1250 mut config: EncoderConfig,
1251 pyramid: Pyramid,
1252 rate: RateTarget,
1253 ) -> Result<Self> {
1254 let rate_loop = rate.into_loop(&mut config, Some(pyramid));
1255 let mut encoder = Self::with_pyramid(config, pyramid)?;
1256 encoder.rate_loop = rate_loop;
1257 Ok(encoder)
1258 }
1259
1260 /// The [`Pyramid`] this stream is actually coding under: what
1261 /// [`Av1Encoder::with_pyramid`] asked for, or `None` once the content gate
1262 /// in [`Av1Encoder::encode_frames`] has dropped a screen-content stream
1263 /// back to the flat path. Meaningful after the first picture has been
1264 /// handed in.
1265 #[must_use]
1266 pub fn pyramid(&self) -> Option<Pyramid> {
1267 self.pyramid
1268 }
1269
1270 /// The coded (padded-to-64) frame size every picture in this stream is
1271 /// coded at — what a decoder allocates and what `ffprobe` reports.
1272 #[must_use]
1273 pub fn coded_size(&self) -> (usize, usize) {
1274 (
1275 self.config.width.next_multiple_of(SUPERBLOCK),
1276 self.config.height.next_multiple_of(SUPERBLOCK),
1277 )
1278 }
1279
1280 /// The display (render) size every frame header signals — [`EncoderConfig`]'s
1281 /// own `width`/`height`, always, whatever the coded size pads it to.
1282 #[must_use]
1283 pub fn display_size(&self) -> (usize, usize) {
1284 (self.config.width, self.config.height)
1285 }
1286
1287 /// Takes one picture and returns the PREVIOUS picture's packet, key or
1288 /// inter by this stream's `gop` cadence — the facade's one frame of
1289 /// latency (the picture just handed in is what the previous one is coded
1290 /// against as its lookahead). The FIRST call has no previous picture and
1291 /// returns a packet with an EMPTY `data` (its other fields are
1292 /// placeholders; test `data.is_empty()`), and the last picture's packet
1293 /// comes out of [`Av1Encoder::flush`] — so a caller that concatenates
1294 /// `data` in call order still gets the whole stream, provided it flushes
1295 /// at the end.
1296 ///
1297 /// # Errors
1298 /// Returns an error when `picture`'s size does not match
1299 /// [`EncoderConfig::width`]/[`EncoderConfig::height`], when the encoder
1300 /// was built by [`Av1Encoder::with_pyramid`] (which reorders pictures, so
1301 /// one call cannot return one packet), or under the same conditions
1302 /// [`crate::encode::encode_key_frame`]/[`crate::encode::encode_sequence`]
1303 /// do.
1304 pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {
1305 if self.pyramid.is_some() {
1306 return Err(Error::unsupported(
1307 "AV1 encode",
1308 "a pyramid stream reorders pictures -- use encode_frames()/flush()",
1309 ));
1310 }
1311 let mut packets = self.encode_frames(picture)?;
1312 Ok(packets.pop().unwrap_or(Packet {
1313 data: Vec::new(),
1314 key: false,
1315 order: 0,
1316 dts: 0,
1317 level: Level::Leaf,
1318 }))
1319 }
1320
1321 /// Takes one picture and returns every packet it completed, in coding
1322 /// order. Without a [`Pyramid`] that is one packet — the PREVIOUS
1323 /// picture's, since this one is its lookahead — and none at all on the
1324 /// first call; with one it is
1325 /// empty for most pictures and a whole mini-GOP's worth (the hidden
1326 /// frame, its leaves and the `show_existing_frame` that re-outputs it)
1327 /// for the picture that closes a group.
1328 ///
1329 /// # Errors
1330 /// As [`Av1Encoder::encode`], minus the pyramid refusal.
1331 pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {
1332 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
1333 if (picture.width, picture.height) != (self.config.width, self.config.height) {
1334 return Err(Error::unsupported(
1335 "AV1 encode",
1336 format!(
1337 "picture is {}x{}, encoder is {}x{}",
1338 picture.width, picture.height, self.config.width, self.config.height
1339 ),
1340 ));
1341 }
1342 // THE CONTENT GATE (lane-av1pyrgate): the pyramid is for camera
1343 // material. A desktop capture is the one content class every pyramid
1344 // sweep measured WORSE under it, and it is exactly the class the
1345 // screen detector separates (`encode::screen_content`: 0/48 frames on
1346 // both real films, 48/48 on the OBS capture), so a stream whose first
1347 // picture reads as screen content drops back to the flat path and
1348 // codes byte for byte what it coded before the pyramid existed.
1349 //
1350 // Decided ONCE, on the first picture, not per mini-GOP: the flat path
1351 // keeps its references in `reference`/`golden`/`prev2` and the pyramid
1352 // path in `dpb`, so a switch after the first frame would read slots
1353 // the other path never filled. Per-GOP re-decision needs the two
1354 // reference sets kept in step first; the gate's own recipe codes one
1355 // GOP per stream, where the two are the same decision.
1356 if self.pyramid.is_some()
1357 && self.next_index == 0
1358 && crate::encode::picture_is_screen(picture)
1359 {
1360 self.pyramid = None;
1361 }
1362 let Some(pyramid) = self.pyramid else {
1363 // The delay queue: the pictures behind this one are the
1364 // lookahead window the one at its head is coded with, which is
1365 // what makes the facade's bytes identical to
1366 // `encode_sequence`'s (lane-av1facade, lane-av1tpl2).
1367 self.held.push_back(picture.clone());
1368 if self.held.len() <= crate::encode::tpl_depth() - 1 {
1369 return Ok(Vec::new());
1370 }
1371 let previous = self.held.pop_front().expect("queue is over depth");
1372 let window: Vec<Picture> = self.held.iter().cloned().collect();
1373 return Ok(vec![self.encode_flat(&previous, &window)?]);
1374 };
1375 let order = self.next_index;
1376 self.next_index += 1;
1377 if order.is_multiple_of(self.config.gop as u64) {
1378 // A key frame closes whatever group is open (there is nothing for
1379 // its leaves to point forward at across the boundary) and then
1380 // restarts the pyramid from the key itself.
1381 let mut packets = self.drain_pending()?;
1382 packets.push(self.encode_key(order, picture)?);
1383 return Ok(packets);
1384 }
1385 self.pending.push((order, picture.clone()));
1386 // The group closes on the size the LAYOUT gives it (which depends on
1387 // how many pictures are left before the next key frame, so no short
1388 // tail group is left behind), or early when the next picture would be
1389 // a key frame.
1390 let run_start = self.pending[0].0;
1391 let remaining = self.config.gop - (run_start % self.config.gop as u64) as usize;
1392 let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64);
1393 if self.pending.len() >= group_target(remaining, pyramid.mini_gop, absorb_tail())
1394 || next_is_key
1395 {
1396 return self.drain_pending();
1397 }
1398 Ok(Vec::new())
1399 }
1400
1401 /// Codes and returns every picture still held back — the last picture of
1402 /// a flat stream (which has no lookahead and is coded without one), or
1403 /// the tail of a pyramid stream whose last mini-GOP never filled up.
1404 /// Empty once there is nothing held.
1405 ///
1406 /// # Errors
1407 /// As [`Av1Encoder::encode_frames`].
1408 pub fn flush(&mut self) -> Result<Vec<Packet>> {
1409 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
1410 if !self.held.is_empty() {
1411 let mut packets = Vec::with_capacity(self.held.len());
1412 while let Some(previous) = self.held.pop_front() {
1413 let window: Vec<Picture> = self.held.iter().cloned().collect();
1414 packets.push(self.encode_flat(&previous, &window)?);
1415 }
1416 return Ok(packets);
1417 }
1418 self.drain_pending()
1419 }
1420
1421 /// The flat path: one picture and its lookahead (the next source picture,
1422 /// `None` at the end of the stream) in, one packet out — the same inputs
1423 /// [`crate::encode::encode_sequence`] gives each of its inter frames, so
1424 /// the bytes are identical.
1425 fn encode_flat(&mut self, picture: &Picture, lookahead: &[Picture]) -> Result<Packet> {
1426 let render = (self.config.width, self.config.height);
1427 let padded = picture.padded_to(SUPERBLOCK);
1428 let is_key = self.next_index.is_multiple_of(self.config.gop as u64);
1429 let order = self.next_index;
1430 let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| {
1431 r.q_idx(if is_key { Level::Key } else { Level::Leaf })
1432 });
1433
1434 let encoded: Encoded = if is_key {
1435 encode_key_frame_inner(
1436 &padded,
1437 base_q_idx,
1438 DEADZONE,
1439 &KEY_FRAME_MODES,
1440 split_blocks(),
1441 render,
1442 self.color_config,
1443 &self.fctx,
1444 )?
1445 } else {
1446 let reference = self.reference.as_ref().ok_or_else(|| {
1447 Error::unsupported(
1448 "AV1 encode",
1449 "an inter frame needs a previous reconstruction",
1450 )
1451 })?;
1452 encode_inter_frame(
1453 &padded,
1454 reference,
1455 base_q_idx,
1456 DEADZONE,
1457 order as u32,
1458 // The flat path's own slot plan, in order hints: the key frame
1459 // of the GOP this picture sits in is what `GOLDEN_FRAME`
1460 // names, and every reference but `ALTREF_FRAME` is the frame
1461 // just coded.
1462 crate::encode::flat_order_hints(
1463 order as u32 & 0x7f,
1464 (order - order % self.config.gop as u64) as u32 & 0x7f,
1465 self.prev2.is_some(),
1466 ),
1467 render,
1468 self.carried_cdfs.as_ref().map(|c| &c.0),
1469 self.golden.as_ref(),
1470 self.prev2.as_ref(),
1471 &self.fctx,
1472 None,
1473 &lookahead.iter().map(|n| n.padded_to(SUPERBLOCK)).collect::<Vec<_>>(),
1474 )?
1475 };
1476
1477 self.carried_cdfs = Some(encoded.next_cdfs.clone());
1478 if is_key {
1479 self.golden = Some(encoded.reconstruction.clone());
1480 self.prev2 = None;
1481 } else {
1482 self.prev2 = self.reference.take();
1483 }
1484 self.reference = Some(encoded.reconstruction.clone());
1485 self.next_index += 1;
1486 let cropped = crop_encoded(&encoded, render.0, render.1);
1487 let level = if is_key { Level::Key } else { Level::Leaf };
1488 if let Some(rate_loop) = self.rate_loop.as_mut() {
1489 // The flat path codes every frame at the slot's own q, no offset.
1490 rate_loop.update(level, 0, cropped.stream.len());
1491 }
1492 Ok(self.packet(cropped.stream, is_key, order, level))
1493 }
1494
1495 /// THE SHARED MINI-GOP DRIVER: codes a whole sequence — one key frame
1496 /// then all inter, which is [`crate::encode::encode_sequence`]'s only
1497 /// shape — through this very facade, under `pyramid`, and hands back what
1498 /// that path returns. The two are byte-identical BY CONSTRUCTION rather
1499 /// than by a mirrored second implementation: there is one reordering,
1500 /// one DPB/slot policy and one set of per-level quantizer offsets, here
1501 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
1502 /// still pins it, now over a pyramid sequence too).
1503 ///
1504 /// The content gate lives in [`Av1Encoder::encode_frames`] and applies
1505 /// unchanged, so a screen-content clip handed in here codes flat.
1506 ///
1507 /// `EncodedSequence::frames` comes back in DISPLAY order, one entry per
1508 /// source picture — the order the flat path's coding order happens to be,
1509 /// and the order every reader of it (the BD gate's sample-exactness
1510 /// assertions against a decoder's output) needs. `stream` stays in coding
1511 /// order, which is the order a decoder reads.
1512 ///
1513 /// # Errors
1514 /// As [`Av1Encoder::encode_frames`].
1515 pub(crate) fn encode_sequence_pyramid(
1516 pictures: &[Picture],
1517 base_q_idx: u8,
1518 pyramid: Pyramid,
1519 tiles: (u32, u32),
1520 ) -> Result<crate::encode::EncodedSequence> {
1521 let first = pictures.first().ok_or_else(|| {
1522 Error::unsupported("AV1 encode", "a sequence needs at least one picture")
1523 })?;
1524 let config = EncoderConfig {
1525 width: first.width,
1526 height: first.height,
1527 base_q_idx,
1528 // One key frame, at picture 0, and inter for the rest.
1529 gop: pictures.len().max(1),
1530 // `encode_sequence` writes an unspecified colour config.
1531 colour: Colour::Unspecified,
1532 tile_cols_log2: tiles.0,
1533 tile_rows_log2: tiles.1,
1534 };
1535 let mut encoder = Self::with_pyramid(config, pyramid)?;
1536 encoder.collected = Some(Vec::with_capacity(pictures.len()));
1537 let mut stream = Vec::new();
1538 for picture in pictures {
1539 for packet in encoder.encode_frames(picture)? {
1540 stream.extend_from_slice(&packet.data);
1541 }
1542 }
1543 for packet in encoder.flush()? {
1544 stream.extend_from_slice(&packet.data);
1545 }
1546 let mut collected = encoder.collected.take().expect("collecting");
1547 // Every source picture is coded exactly once, so a frame's display
1548 // order IS its index once the list is sorted by it.
1549 let coding_order: Vec<usize> =
1550 collected.iter().map(|(order, _)| *order as usize).collect();
1551 collected.sort_by_key(|(order, _)| *order);
1552 let frames: Vec<Encoded> = collected.into_iter().map(|(_, encoded)| encoded).collect();
1553 assert!(
1554 coding_order.iter().all(|&i| i < frames.len()),
1555 "a coded frame's display position is outside the sequence"
1556 );
1557 Ok(crate::encode::EncodedSequence { stream, frames, coding_order })
1558 }
1559
1560 /// Stamps a packet with its display and coding positions and advances the
1561 /// coding-order clock.
1562 fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet {
1563 let dts = self.next_dts;
1564 self.next_dts += 1;
1565 Packet {
1566 data,
1567 key,
1568 order,
1569 dts,
1570 level,
1571 }
1572 }
1573
1574 /// Stores a coded frame into every DPB slot its `refresh_frame_flags`
1575 /// names (spec 7.20).
1576 fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) {
1577 let slot = DpbSlot {
1578 picture: encoded.reconstruction.clone(),
1579 order_hint,
1580 cdfs: encoded.next_cdfs.clone(),
1581 };
1582 for &s in slots {
1583 self.dpb[s as usize] = Some(slot.clone());
1584 }
1585 }
1586
1587 /// Codes a key frame in pyramid mode: it refreshes all eight slots, so it
1588 /// becomes the anchor, the `GOLDEN_FRAME` and the CDF source for the
1589 /// whole GOP at once.
1590 fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> {
1591 let render = (self.config.width, self.config.height);
1592 let base = self
1593 .rate_loop
1594 .as_ref()
1595 .map_or(i16::from(self.config.base_q_idx), |r| i16::from(r.q_idx(Level::Key)));
1596 let offset = self.pyramid.map_or(0, |p| p.key_q_offset);
1597 let base_q_idx = (base + offset).clamp(1, 255) as u8;
1598 let encoded = encode_key_frame_inner(
1599 &picture.padded_to(SUPERBLOCK),
1600 base_q_idx,
1601 DEADZONE,
1602 &KEY_FRAME_MODES,
1603 split_blocks(),
1604 render,
1605 self.color_config,
1606 &self.fctx,
1607 )?;
1608 self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0);
1609 self.anchor = 0;
1610 let cropped = crop_encoded(&encoded, render.0, render.1);
1611 if let Some(rate_loop) = self.rate_loop.as_mut() {
1612 rate_loop.update(Level::Key, 0, cropped.stream.len());
1613 }
1614 if let Some(collected) = self.collected.as_mut() {
1615 collected.push((order, cropped.clone()));
1616 }
1617 Ok(self.packet(cropped.stream, true, order, Level::Key))
1618 }
1619
1620 /// Codes one inter frame at `order` from the DPB, in coding order.
1621 #[allow(clippy::too_many_arguments)]
1622 fn encode_pyramid_inter(
1623 &mut self,
1624 order: u64,
1625 picture: &Picture,
1626 last_slot: u8,
1627 self_slot: u8,
1628 altref_slot: u8,
1629 show_frame: bool,
1630 level: Level,
1631 // The quantizer offset comes from the CALLER, not from `level`: a
1632 // three-level group codes two `Level::Arf` frames (the group's top
1633 // ARF and the mid one) at different offsets, and they share the
1634 // rate-control slot but not the offset.
1635 offset: i16,
1636 // The lookahead window this frame's temporal lambda map is built
1637 // from, already padded (lane-arfcen). Empty codes the frame at one
1638 // lambda, which is what the whole pyramid path used to do.
1639 lookahead: &[Picture],
1640 ) -> Result<Packet> {
1641 let render = (self.config.width, self.config.height);
1642 let order_hint = (order & 0x7f) as u32;
1643 let base = self
1644 .rate_loop
1645 .as_ref()
1646 .map_or(i16::from(self.config.base_q_idx), |r| {
1647 i16::from(r.q_idx(level))
1648 });
1649 let base_q_idx = (base + offset).clamp(1, 255) as u8;
1650 // spec 5.9.2's `ref_frame_sign_bias`, derived from what the slots
1651 // this frame names actually hold: a reference whose order hint is
1652 // AHEAD of this frame's is backward-biased, and the MV stack scans
1653 // (writer and decoder alike) flip borrowed candidates across the
1654 // boundary. Only `ALTREF_FRAME` can be ahead here — the leaves of a
1655 // mini-GOP name the group's hidden frame there.
1656 let mut sign_bias = crate::mvstack::NO_SIGN_BIAS;
1657 let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| {
1658 dpb[slot as usize]
1659 .as_ref()
1660 .is_some_and(|s| s.order_hint > order_hint)
1661 };
1662 let slots = [
1663 last_slot, last_slot, last_slot, GOLDEN_SLOT, last_slot, last_slot, altref_slot,
1664 ];
1665 for (i, slot) in slots.into_iter().enumerate() {
1666 sign_bias[i] = ahead(slot, &self.dpb);
1667 }
1668 // The same seven slots' order hints, for `skipModeAllowed` (spec
1669 // 5.9.22) in the frame-header writer.
1670 let order_hints: [u32; 7] = slots.map(|slot| {
1671 self.dpb[slot as usize]
1672 .as_ref()
1673 .map_or(0, |s| (s.order_hint & 0x7f) as u32)
1674 });
1675 let reference = self.dpb[last_slot as usize]
1676 .as_ref()
1677 .map(|s| s.picture.clone())
1678 .ok_or_else(|| {
1679 Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction")
1680 })?;
1681 let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone());
1682 let altref = (altref_slot != GOLDEN_SLOT)
1683 .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone()))
1684 .flatten();
1685 let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone());
1686 let encoded = || -> Result<Encoded> { encode_inter_frame(
1687 &picture.padded_to(SUPERBLOCK),
1688 &reference,
1689 base_q_idx,
1690 DEADZONE,
1691 order_hint,
1692 order_hints,
1693 render,
1694 start_cdfs.as_ref(),
1695 golden.as_ref(),
1696 altref.as_ref(),
1697 &self.fctx,
1698 Some(crate::encode::PyramidFrame {
1699 last_slot,
1700 self_slot,
1701 altref_slot,
1702 show_frame,
1703 sign_bias,
1704 }),
1705 // lane-arfcen: the group's own sources ARE this frame's window
1706 // (`tpl_window`); it was `&[]` here, which switched the temporal
1707 // lambda map off on every frame the default stream codes.
1708 lookahead,
1709 ) }();
1710 // Name the pyramid position in any failure: an error out of the tile
1711 // writer or the filter search is otherwise indistinguishable between
1712 // the hidden frame and the leaves that read it.
1713 let encoded = encoded.map_err(|e| {
1714 Error::unsupported(
1715 "AV1 encode",
1716 format!(
1717 "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \
1718 altref {altref_slot}, shown {show_frame}, golden {}, altref pic {}): {e}",
1719 golden.is_some(),
1720 altref.is_some(),
1721 ),
1722 )
1723 })?;
1724 self.refresh(&[self_slot], &encoded, order_hint);
1725 let cropped = crop_encoded(&encoded, render.0, render.1);
1726 if let Some(rate_loop) = self.rate_loop.as_mut() {
1727 rate_loop.update(level, offset, cropped.stream.len());
1728 }
1729 if let Some(collected) = self.collected.as_mut() {
1730 collected.push((order, cropped.clone()));
1731 }
1732 Ok(self.packet(cropped.stream, false, order, level))
1733 }
1734
1735 /// Codes the open mini-GOP: its hidden frame first, then its leaves, then
1736 /// the `show_existing_frame` header that puts the hidden frame back in
1737 /// display order.
1738 fn drain_pending(&mut self) -> Result<Vec<Packet>> {
1739 if self.pending.is_empty() {
1740 return Ok(Vec::new());
1741 }
1742 let group: Vec<(u64, Picture)> = std::mem::take(&mut self.pending);
1743 let mut packets = Vec::with_capacity(group.len() + 1);
1744 // The lookahead window of the group's picture at index `pos`: the
1745 // display-order successors inside this group, or -- for the group's
1746 // top ARF, the last picture, whose successors are not buffered yet --
1747 // the leaves BEHIND it in reverse display order, which are exactly
1748 // the pictures that predict backward from it. Padded like the frame
1749 // itself, as `encode_inter_frame` wants it.
1750 let tpl_window = |pos: usize, back: bool| -> Vec<Picture> {
1751 let depth = crate::encode::tpl_depth();
1752 if !tpl_pyramid() || depth < 2 {
1753 return Vec::new();
1754 }
1755 let window: Vec<&Picture> = match back {
1756 false => group[pos + 1..].iter().map(|(_, p)| p).collect(),
1757 true => group[..pos].iter().rev().map(|(_, p)| p).collect(),
1758 };
1759 window.into_iter().take(depth - 1).map(|p| p.padded_to(SUPERBLOCK)).collect()
1760 };
1761 let anchor_slot = ANCHOR_SLOTS[self.anchor];
1762 let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor];
1763 let (arf_order, arf_picture) = group.last().cloned().expect("non-empty");
1764 let pyramid = self.pyramid.expect("pyramid mode");
1765 if group.len() == 1 {
1766 // Nothing to predict backward, so no hidden frame: one shown leaf
1767 // that also becomes the next group's anchor.
1768 packets.push(self.encode_pyramid_inter(
1769 arf_order,
1770 &arf_picture,
1771 anchor_slot,
1772 next_anchor_slot,
1773 GOLDEN_SLOT,
1774 true,
1775 Level::Leaf,
1776 pyramid.leaf_q_offset,
1777 &tpl_window(0, false),
1778 )?);
1779 self.anchor = 1 - self.anchor;
1780 return Ok(packets);
1781 }
1782 // The group's top level: the last picture, hidden, off the anchor.
1783 packets.push(self.encode_pyramid_inter(
1784 arf_order,
1785 &arf_picture,
1786 anchor_slot,
1787 next_anchor_slot,
1788 // lane-arfcen: the slot this ARF refreshes still holds the ARF
1789 // from two groups back, so naming it here gives the frame a
1790 // SECOND, distinct past anchor instead of the key it already
1791 // reads as GOLDEN.
1792 match arf_altref() {
1793 true => next_anchor_slot,
1794 false => GOLDEN_SLOT,
1795 },
1796 false,
1797 Level::Arf,
1798 pyramid.arf_q_offset,
1799 &tpl_window(group.len() - 1, true),
1800 )?);
1801 let leaves = group.len() - 1;
1802 // THE THIRD LEVEL: a second hidden frame at the middle of the leaf
1803 // run, coded off the anchor with the top ARF as its own backward
1804 // reference. It needs a leaf on both sides of it, so a group of
1805 // three or fewer stays two-level.
1806 //
1807 // AND IT NEEDS A RUN LONG ENOUGH TO AMORTISE IT: a GOP that is one
1808 // single mini-GOP (`group_target` absorbs a tail, so a 12-picture GOP
1809 // under `mini_gop` 8 is ONE group of 11) pays for the second hidden
1810 // frame out of eleven pictures and reads +2.8 BD points worse against
1811 // libaom on film B at every mid offset measured (-4: +71.1, -8:
1812 // +71.2, against the two-level +68.4), while the 48-picture GOP -- six
1813 // groups sharing the same machinery -- is 6.0 points BETTER. So the
1814 // third level is switched on by the RUN's length, not by the group's:
1815 // the same GOP-length dependence `group_target` itself was built for.
1816 let long_run = self.config.gop > pyramid.mini_gop + pyramid.mini_gop / 2;
1817 let mid = pyramid.mid_q_offset.filter(|_| leaves >= 3 && long_run).map(|offset| {
1818 let at = (leaves - 1) / 2;
1819 (at, offset)
1820 });
1821 if let Some((at, offset)) = mid {
1822 let (order, picture) = group[at].clone();
1823 packets.push(self.encode_pyramid_inter(
1824 order,
1825 &picture,
1826 anchor_slot,
1827 MID_SLOT,
1828 next_anchor_slot,
1829 false,
1830 Level::Arf,
1831 offset,
1832 &tpl_window(at, false),
1833 )?);
1834 }
1835 // THE FOURTH LEVEL: one hidden frame at the middle of each half of
1836 // the leaf run, so no leaf is more than one picture from a hidden
1837 // reference on either side -- the depth the references run (rav1e
1838 // speed 6 codes 23 hidden frames per 48 pictures, libaom four levels
1839 // per 16-picture group) and the lever three levels had run out of.
1840 // It hangs off the mid level, and it needs a leaf on both sides of
1841 // both quarter points, which a run of fewer than seven leaves cannot
1842 // give.
1843 let quarters = match (mid, pyramid.quarter_q_offset) {
1844 (Some((at, _)), Some(offset)) if leaves >= 7 => {
1845 Some(([(at - 1) / 2, (at + leaves) / 2], offset))
1846 }
1847 _ => None,
1848 };
1849 if let Some((at, offset)) = quarters {
1850 // The first quarter predicts forward off the group's anchor and
1851 // backward off the mid ARF; the second starts FROM the mid ARF
1852 // and reads the group's top ARF backward.
1853 for (i, &pos) in at.iter().enumerate() {
1854 let (order, picture) = group[pos].clone();
1855 let (last_slot, altref_slot) = match i {
1856 0 => (anchor_slot, MID_SLOT),
1857 _ => (MID_SLOT, next_anchor_slot),
1858 };
1859 packets.push(self.encode_pyramid_inter(
1860 order,
1861 &picture,
1862 last_slot,
1863 QUARTER_SLOTS[i],
1864 altref_slot,
1865 false,
1866 Level::Arf,
1867 offset,
1868 &tpl_window(pos, false),
1869 )?);
1870 }
1871 }
1872 // Every hidden frame INSIDE the leaf run, by leaf index, in display
1873 // order: what a leaf reads forward (the nearest one behind it) and
1874 // backward (the nearest one ahead of it, the group's top ARF when
1875 // there is none).
1876 let mut inner: Vec<(usize, u8)> = Vec::new();
1877 if let Some((at, _)) = mid {
1878 inner.push((at, MID_SLOT));
1879 }
1880 if let Some((at, _)) = quarters {
1881 inner.extend(at.iter().zip(QUARTER_SLOTS).map(|(&at, slot)| (at, slot)));
1882 }
1883 inner.sort_unstable();
1884 let (seq, _) = crate::encode::key_frame_headers(
1885 self.config.width,
1886 self.config.height,
1887 self.config.base_q_idx,
1888 )?;
1889 let show_existing = |encoder: &mut Self, slot: u8, order: u64| -> Result<Packet> {
1890 let mut data = crate::obu::temporal_delimiter();
1891 data.extend_from_slice(&crate::frame::show_existing_frame_obu(&seq, slot)?);
1892 Ok(encoder.packet(data, false, order, Level::ShowExisting))
1893 };
1894 // The leaves, in display order, so every `show_existing_frame` lands
1895 // in its own display position. Each leaf names the nearest hidden
1896 // frame BEHIND it as `LAST_FRAME` (the group's anchor for the first
1897 // leaf, otherwise the previous leaf) and the nearest one AHEAD as
1898 // `ALTREF_FRAME` (the group's top ARF when none is closer).
1899 for (i, (order, picture)) in group[..leaves].iter().enumerate() {
1900 if let Some(&(_, slot)) = inner.iter().find(|(at, _)| *at == i) {
1901 let packet = show_existing(self, slot, *order)?;
1902 packets.push(packet);
1903 continue;
1904 }
1905 let last_slot = match i {
1906 0 => anchor_slot,
1907 i => inner
1908 .iter()
1909 .find(|(at, _)| at + 1 == i)
1910 .map_or(LEAF_SLOT, |&(_, slot)| slot),
1911 };
1912 let altref_slot = inner
1913 .iter()
1914 .find(|(at, _)| *at > i)
1915 .map_or(next_anchor_slot, |&(_, slot)| slot);
1916 packets.push(self.encode_pyramid_inter(
1917 *order,
1918 picture,
1919 last_slot,
1920 LEAF_SLOT,
1921 altref_slot,
1922 true,
1923 Level::Leaf,
1924 pyramid.leaf_q_offset,
1925 &tpl_window(i, false),
1926 )?);
1927 }
1928 let packet = show_existing(self, next_anchor_slot, arf_order)?;
1929 packets.push(packet);
1930 self.anchor = 1 - self.anchor;
1931 Ok(packets)
1932 }
1933}
1934
1935#[cfg(test)]
1936mod tests {
1937 use super::*;
1938 use std::process::{Command, Stdio};
1939
1940 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
1941 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
1942 /// aomenc gate decodes its stream through ffmpeg and is meaningless
1943 /// without it -- turns it into a hard failure. Without this the require
1944 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
1945 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
1946 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
1947 fn have_ffmpeg() -> bool {
1948 let present = Command::new("ffmpeg")
1949 .arg("-version")
1950 .stdout(Stdio::null())
1951 .stderr(Stdio::null())
1952 .status()
1953 .is_ok_and(|s| s.success());
1954 assert!(
1955 present
1956 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
1957 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
1958 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
1959 );
1960 present
1961 }
1962
1963 fn test_card(width: usize, height: usize, shift: usize) -> Picture {
1964 let mut picture = Picture::grey(width, height);
1965 for y in 0..height {
1966 for x in 0..width {
1967 let sx = (x + shift) % width;
1968 picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16;
1969 }
1970 }
1971 for y in 0..height / 2 {
1972 for x in 0..width / 2 {
1973 let i = y * (width / 2) + x;
1974 picture.u[i] = ((100 + shift * 4) % 256) as u16;
1975 picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16;
1976 }
1977 }
1978 picture
1979 }
1980
1981 /// Drives a whole stream through the facade the way a caller must since
1982 /// it holds one picture of lookahead: every picture through
1983 /// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`].
1984 fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec<Packet> {
1985 let mut packets = Vec::with_capacity(pictures.len());
1986 for (i, picture) in pictures.iter().enumerate() {
1987 packets.extend(
1988 enc.encode_frames(picture)
1989 .unwrap_or_else(|e| panic!("picture {i}: {e}")),
1990 );
1991 }
1992 packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}")));
1993 packets
1994 }
1995
1996 /// [`gop_shape`] prices the frames the pyramid actually CODES: its hidden
1997 /// counts and leaf count match the packets a real run emits, at three
1998 /// pyramid shapes, and the plan [`RateLoop::new`] builds from it spends
1999 /// the run's budget exactly (`gop` frame targets, no more and no less).
2000 ///
2001 /// Both halves matter: a shape that misses a level (the old model priced
2002 /// ONE hidden frame per group when the mid level had made it two) splits
2003 /// the budget by weights that do not add up to the run.
2004 #[test]
2005 fn the_rate_loop_prices_the_frames_the_pyramid_codes() {
2006 let _knobs = crate::speed::knob_read();
2007 let pictures: Vec<Picture> = (0..48).map(|i| test_card(64, 64, i)).collect();
2008 let quarters = Pyramid {
2009 quarter_q_offset: Some(-20),
2010 ..Pyramid::default()
2011 };
2012 let two_level = Pyramid {
2013 mid_q_offset: None,
2014 ..Pyramid::default()
2015 };
2016 for (gop, pyramid) in [
2017 (48, Pyramid::default()),
2018 (12, Pyramid::default()),
2019 (48, quarters),
2020 (48, two_level),
2021 ] {
2022 let config = EncoderConfig {
2023 width: 64,
2024 height: 64,
2025 base_q_idx: 100,
2026 gop,
2027 colour: Colour::Bt709Limited,
2028 tile_cols_log2: 0,
2029 tile_rows_log2: 0,
2030 };
2031 let rate = RateTarget::BytesPerFrame(2_000);
2032 let mut enc =
2033 Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap();
2034 let packets = encode_all(&mut enc, &pictures[..gop]);
2035 let coded = |level: Level| packets.iter().filter(|p| p.level == level).count();
2036 let (hidden, leaves) = gop_shape(pyramid, gop);
2037 let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum();
2038 assert_eq!(
2039 (hidden_frames, leaves, 1),
2040 (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)),
2041 "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves"
2042 );
2043 assert_eq!(
2044 hidden_frames + leaves + 1,
2045 gop,
2046 "gop {gop}: every picture is coded exactly once"
2047 );
2048 // The plan adds up: one leaf's target times the run's whole
2049 // weight is the run's whole budget.
2050 let target_bytes = 2_000.0;
2051 let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
2052 let planned = loop_.target[0]
2053 + loop_.target[2] * (leaves as f64
2054 + hidden.iter().map(|&(o, n)| n as f64 * loop_.weight(o)).sum::<f64>());
2055 assert!(
2056 (planned - target_bytes * gop as f64).abs() < 1.0,
2057 "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run",
2058 target_bytes * gop as f64
2059 );
2060 }
2061 }
2062
2063 /// The mini-GOP layout leaves no short tail group, and leaves the long
2064 /// GOP the fixed rule already coded alone: 47 inter pictures are
2065 /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical),
2066 /// while a 12-picture GOP stops being 8 + 3 (lane-gopad).
2067 #[test]
2068 fn the_mini_gop_layout_leaves_no_short_tail() {
2069 let groups = |remaining: usize, mini_gop: usize, absorb: bool| {
2070 let (mut left, mut out) = (remaining, Vec::new());
2071 while left > 0 {
2072 let g = group_target(left, mini_gop, absorb).min(left);
2073 assert!(g > 0);
2074 out.push(g);
2075 left -= g;
2076 }
2077 out
2078 };
2079 // gop 48: what mini_gop 8 already coded, under either rule.
2080 assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]);
2081 assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]);
2082 // gop 12: 8 + 3 becomes one group of 11.
2083 assert_eq!(groups(11, 8, false), vec![8, 3]);
2084 assert_eq!(groups(11, 8, true), vec![11]);
2085 // A run shorter than a group is one group, as before (the 4-picture
2086 // pin clip).
2087 assert_eq!(groups(3, 8, true), vec![3]);
2088 // No group is ever below half the shape, and none is over 1.5x it.
2089 for mini_gop in 2..=16 {
2090 for remaining in 1..=64 {
2091 for g in groups(remaining, mini_gop, true) {
2092 assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}");
2093 assert!(
2094 g * 2 >= mini_gop || remaining < mini_gop,
2095 "{remaining}/{mini_gop}: short tail {g}"
2096 );
2097 }
2098 }
2099 }
2100 }
2101
2102 /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
2103 /// in order.
2104 fn concat(packets: &[Packet]) -> Vec<u8> {
2105 packets.iter().flat_map(|p| p.data.clone()).collect()
2106 }
2107
2108 /// The facade's latency contract (lane-av1facade, deepened on
2109 /// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold
2110 /// their picture back and return an empty packet, every later call
2111 /// returns the packet of the picture that many frames earlier, and
2112 /// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets
2113 /// exactly one non-empty packet per picture, `depth - 1` calls later.
2114 #[test]
2115 fn one_in_one_out_delayed_by_the_lookahead_depth() {
2116 let _knobs = crate::speed::knob_read();
2117 let config = EncoderConfig {
2118 width: 64,
2119 height: 64,
2120 base_q_idx: 100,
2121 gop: 2,
2122 colour: Colour::Bt709Limited,
2123 tile_cols_log2: 0,
2124 tile_rows_log2: 0,
2125 };
2126 let delay = crate::encode::tpl_depth() as u64 - 1;
2127 let pictures = delay + 5;
2128 let mut enc = Av1Encoder::new(config).unwrap();
2129 for t in 0..pictures {
2130 let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
2131 if t < delay {
2132 assert!(packet.data.is_empty(), "call {t} holds its picture back");
2133 continue;
2134 }
2135 assert!(!packet.data.is_empty(), "picture {t}: empty packet");
2136 assert_eq!(packet.order, t - delay, "picture {t}: order");
2137 }
2138 let tail = enc.flush().unwrap();
2139 assert_eq!(tail.len() as u64, delay, "flush yields the whole queue");
2140 for (i, p) in tail.iter().enumerate() {
2141 assert_eq!(p.order, pictures - delay + i as u64, "flushed packet {i}: order");
2142 assert!(!p.data.is_empty(), "flushed packet {i}: empty");
2143 }
2144 assert!(enc.flush().unwrap().is_empty(), "nothing is held twice");
2145 }
2146
2147 /// A screen-like card: hard-edged 4-pixel bands of two flat luma values
2148 /// with a moving block over the lower half — few colours per 16x16 block
2149 /// at high variance, which is exactly what
2150 /// [`crate::encode::picture_is_screen`] separates. Used unforced, so the
2151 /// gate below runs the real detector rather than an override.
2152 fn screen_card(width: usize, height: usize, shift: usize) -> Picture {
2153 let mut picture = Picture::grey(width, height);
2154 for y in 0..height {
2155 for x in 0..width {
2156 let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 };
2157 let over = y >= height / 2 && (x + shift) % width < width / 3;
2158 picture.y[y * width + x] = if over { 128 } else { band };
2159 }
2160 }
2161 picture
2162 }
2163
2164 /// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on
2165 /// lane-av1pyrdef): the streaming facade — what the editor's export
2166 /// drives — codes byte for byte what [`crate::encode::encode_sequence`]
2167 /// codes, which is the path the BD gate measures. Both now drive ONE
2168 /// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the
2169 /// identity is by construction; this pins it anyway, over both content
2170 /// classes the content gate splits:
2171 ///
2172 /// * film-like (the gate's own clip when the fixture is there, a
2173 /// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the
2174 /// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two
2175 /// paths' whole streams are identical;
2176 /// * screen-like: the content gate drops BOTH paths back to flat, one
2177 /// packet per picture, identical frame by frame as well as whole.
2178 ///
2179 /// Never skipped, since a skipped identity gate is the defect it is meant
2180 /// to catch.
2181 #[test]
2182 fn the_facade_codes_the_same_bytes_as_encode_sequence() {
2183 let _knobs = crate::speed::knob_read();
2184 let frames = 12usize;
2185 let film = h264_clip_frames(640, 384, frames).unwrap_or_else(|| {
2186 eprintln!("no h264 clip: the facade identity gate runs on a synthetic card");
2187 (0..frames).map(|t| test_card(64, 64, t)).collect()
2188 });
2189 let screen: Vec<Picture> = (0..frames).map(|t| screen_card(64, 64, t)).collect();
2190 let pyramid = Pyramid::from_env().expect("the pyramid is this build's default");
2191 for (content, pictures, is_screen) in
2192 [("film", &film, false), ("screen", &screen, true)]
2193 {
2194 let (width, height) = (pictures[0].width, pictures[0].height);
2195 for q in [150u8, 60] {
2196 let config = EncoderConfig {
2197 width,
2198 height,
2199 base_q_idx: q,
2200 // One key frame then all inter, which is
2201 // `encode_sequence`'s only shape, and the gate's recipe.
2202 gop: frames,
2203 // `encode_sequence` writes an unspecified colour config.
2204 colour: Colour::Unspecified,
2205 tile_cols_log2: 0,
2206 tile_rows_log2: 0,
2207 };
2208 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
2209 let mut packets = Vec::new();
2210 for picture in pictures {
2211 packets.extend(enc.encode_frames(picture).unwrap());
2212 }
2213 packets.extend(enc.flush().unwrap());
2214 assert_eq!(
2215 enc.pyramid().is_none(),
2216 is_screen,
2217 "{content} q={q}: the content gate read this clip the other way round"
2218 );
2219 let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap();
2220 assert_eq!(
2221 (packets.iter().map(|p| p.data.len()).sum::<usize>(), concat(&packets)),
2222 (sequence.stream.len(), sequence.stream.clone()),
2223 "{content} q={q}: the facade's stream is not the sequence path's"
2224 );
2225 assert_eq!(
2226 sequence.frames.len(),
2227 frames,
2228 "{content} q={q}: one entry per picture, in display order"
2229 );
2230 if is_screen {
2231 assert_eq!(packets.len(), frames, "{content} q={q}: one packet per picture");
2232 for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() {
2233 let cropped = crate::encode::crop_encoded(coded, width, height);
2234 assert_eq!(
2235 (packet.data.len(), packet.data.clone()),
2236 (cropped.stream.len(), cropped.stream.clone()),
2237 "{content} q={q} frame {i}: the facade's bytes are not the \
2238 sequence path's"
2239 );
2240 }
2241 } else {
2242 assert!(
2243 packets.iter().any(|p| p.level == Level::Arf),
2244 "{content} q={q}: a non-screen stream coded no hidden frame"
2245 );
2246 }
2247 }
2248 }
2249 }
2250
2251 /// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by
2252 /// the caller but applied only to camera material. Over screen content
2253 /// the encoder must drop back to the flat path and code byte for byte
2254 /// what a flat encoder codes — that is what keeps the BD gate's screen
2255 /// row identical to the flat baseline — and over non-screen content the
2256 /// same request must still reorder (class `gate-blind-to-feature`: a gate
2257 /// that only checked the screen half would pass with the pyramid deleted).
2258 #[test]
2259 fn the_content_gate_keeps_screen_streams_flat() {
2260 let _knobs = crate::speed::knob_read();
2261 let frames = 8usize;
2262 let pictures: Vec<Picture> = (0..frames).map(|t| test_card(64, 64, t)).collect();
2263 let config = EncoderConfig {
2264 width: 64,
2265 height: 64,
2266 base_q_idx: 120,
2267 gop: frames,
2268 colour: Colour::Unspecified,
2269 tile_cols_log2: 0,
2270 tile_rows_log2: 0,
2271 };
2272 crate::encode::force_screen(Some(true));
2273 let mut flat = Av1Encoder::new(config).unwrap();
2274 let flat_packets = encode_all(&mut flat, &pictures);
2275 let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
2276 let gated_packets = encode_all(&mut gated, &pictures);
2277 assert_eq!(gated.pyramid(), None, "the gate left a screen stream on the pyramid");
2278 assert_eq!(
2279 concat(&gated_packets),
2280 concat(&flat_packets),
2281 "a screen stream's bytes are not the flat path's"
2282 );
2283 crate::encode::force_screen(Some(false));
2284 let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
2285 let kept_packets = encode_all(&mut kept, &pictures);
2286 assert_eq!(kept.pyramid(), Some(Pyramid::default()), "the gate ate a film stream");
2287 assert!(
2288 kept_packets.iter().any(|p| p.level == Level::Arf),
2289 "a non-screen stream coded no hidden frame"
2290 );
2291 crate::encode::force_screen(None);
2292 }
2293
2294 /// A key frame every `gop` pictures, inter otherwise — checked against
2295 /// what the facade itself reports, and (below) against what `ffprobe`
2296 /// reads back out of the coded bytes.
2297 #[test]
2298 fn gop_cadence_is_honored() {
2299 let _knobs = crate::speed::knob_read();
2300 let config = EncoderConfig {
2301 width: 64,
2302 height: 64,
2303 base_q_idx: 100,
2304 gop: 3,
2305 colour: Colour::Unspecified,
2306 tile_cols_log2: 0,
2307 tile_rows_log2: 0,
2308 };
2309 let mut enc = Av1Encoder::new(config).unwrap();
2310 let pictures: Vec<Picture> = (0..7).map(|t| test_card(64, 64, t)).collect();
2311 let keys: Vec<bool> = encode_all(&mut enc, &pictures)
2312 .iter()
2313 .map(|p| p.key)
2314 .collect();
2315 assert_eq!(keys, vec![true, false, false, true, false, false, true]);
2316 }
2317
2318 fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {
2319 let path = std::env::temp_dir().join(format!(
2320 "ec-av1-facade-probe-{}-{}.obu",
2321 std::process::id(),
2322 std::ptr::addr_of!(stream) as usize
2323 ));
2324 std::fs::write(&path, stream).expect("writing the probe stream");
2325 let out = Command::new("ffprobe")
2326 .args([
2327 "-v",
2328 "error",
2329 "-f",
2330 "obu",
2331 "-select_streams",
2332 "v:0",
2333 "-show_entries",
2334 "frame=key_frame,width,height",
2335 "-of",
2336 "csv=p=0",
2337 ])
2338 .arg(&path)
2339 .output()
2340 .expect("ffprobe failed to run");
2341 let _ = std::fs::remove_file(&path);
2342 assert!(
2343 out.status.success(),
2344 "ffprobe refused the stream: {}",
2345 String::from_utf8_lossy(&out.stderr)
2346 );
2347 String::from_utf8_lossy(&out.stdout)
2348 .lines()
2349 .map(|line| {
2350 let mut f = line.trim().split(',');
2351 let key: u32 = f.next().unwrap().parse().unwrap();
2352 let width: u32 = f.next().unwrap().parse().unwrap();
2353 let height: u32 = f.next().unwrap().parse().unwrap();
2354 (key == 1, width, height)
2355 })
2356 .collect()
2357 }
2358
2359 fn ffprobe_colour(stream: &[u8]) -> String {
2360 let path = std::env::temp_dir().join(format!(
2361 "ec-av1-facade-colour-probe-{}-{}.obu",
2362 std::process::id(),
2363 std::ptr::addr_of!(stream) as usize
2364 ));
2365 std::fs::write(&path, stream).expect("writing the probe stream");
2366 let out = Command::new("ffprobe")
2367 .args([
2368 "-v",
2369 "error",
2370 "-f",
2371 "obu",
2372 "-select_streams",
2373 "v:0",
2374 "-show_entries",
2375 "stream=color_primaries,color_transfer,color_space,color_range",
2376 "-of",
2377 "csv=p=0",
2378 ])
2379 .arg(&path)
2380 .output()
2381 .expect("ffprobe failed to run");
2382 let _ = std::fs::remove_file(&path);
2383 assert!(
2384 out.status.success(),
2385 "ffprobe refused the stream: {}",
2386 String::from_utf8_lossy(&out.stderr)
2387 );
2388 String::from_utf8_lossy(&out.stdout).trim().to_string()
2389 }
2390
2391 /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)
2392 /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that
2393 /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and
2394 /// coded size confirm what the facade already reported.
2395 #[test]
2396 fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
2397 let _knobs = crate::speed::knob_read();
2398 if !have_ffmpeg() {
2399 eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg");
2400 return;
2401 }
2402 let (width, height) = (96usize, 96usize);
2403 let config = EncoderConfig {
2404 width,
2405 height,
2406 base_q_idx: 120,
2407 gop: 15,
2408 colour: Colour::Bt709Limited,
2409 tile_cols_log2: 0,
2410 tile_rows_log2: 0,
2411 };
2412 let mut enc = Av1Encoder::new(config).unwrap();
2413 assert_eq!(enc.display_size(), (width, height));
2414 let (coded_w, coded_h) = enc.coded_size();
2415 assert_eq!(
2416 (coded_w, coded_h),
2417 (
2418 width.next_multiple_of(SUPERBLOCK),
2419 height.next_multiple_of(SUPERBLOCK)
2420 )
2421 );
2422
2423 let pictures: Vec<Picture> = (0..30).map(|t| test_card(width, height, t)).collect();
2424 let packets: Vec<Packet> = encode_all(&mut enc, &pictures);
2425 let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect();
2426 assert_eq!(
2427 packets.iter().map(|p| p.key).collect::<Vec<_>>(),
2428 expect_key,
2429 "facade's own key/inter flags"
2430 );
2431
2432 let stream = concat(&packets);
2433 let frames = ffprobe_frames(&stream);
2434 assert_eq!(frames.len(), 30, "ffprobe frame count");
2435 for (t, (key, w, h)) in frames.iter().enumerate() {
2436 assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag");
2437 assert_eq!(
2438 (*w, *h),
2439 (width as u32, height as u32),
2440 "picture {t}: ffprobe reports the true (display) size, not the padded coded one"
2441 );
2442 }
2443 }
2444
2445 /// The configured colour properties are what `ffprobe` reports back,
2446 /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it
2447 /// is the default a player assumes and the one this test would silently
2448 /// pass without wiring for (`ffprobe` reports "unknown" for the
2449 /// hardcoded "unspecified" this crate wrote before the facade existed,
2450 /// which is a visibly different string).
2451 #[test]
2452 fn bt709_limited_colour_is_reported_by_ffprobe() {
2453 let _knobs = crate::speed::knob_read();
2454 if !have_ffmpeg() {
2455 eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg");
2456 return;
2457 }
2458 let config = EncoderConfig {
2459 width: 64,
2460 height: 64,
2461 base_q_idx: 100,
2462 gop: 4,
2463 colour: Colour::Bt709Limited,
2464 tile_cols_log2: 0,
2465 tile_rows_log2: 0,
2466 };
2467 let mut enc = Av1Encoder::new(config).unwrap();
2468 let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]);
2469 let colour = ffprobe_colour(&packets[0].data);
2470 assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields");
2471 }
2472
2473 /// The same, for BT.601: a different set of CICP integers must produce a
2474 /// different string, or the wiring could be a no-op that happens to read
2475 /// as BT.709 for every input.
2476 #[test]
2477 fn bt601_limited_colour_is_reported_by_ffprobe() {
2478 let _knobs = crate::speed::knob_read();
2479 if !have_ffmpeg() {
2480 eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg");
2481 return;
2482 }
2483 let config = EncoderConfig {
2484 width: 64,
2485 height: 64,
2486 base_q_idx: 100,
2487 gop: 4,
2488 colour: Colour::Bt601Limited,
2489 tile_cols_log2: 0,
2490 tile_rows_log2: 0,
2491 };
2492 let mut enc = Av1Encoder::new(config).unwrap();
2493 let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]);
2494 let colour = ffprobe_colour(&packets[0].data);
2495 assert_eq!(
2496 colour, "tv,smpte170m,smpte170m,smpte170m",
2497 "ffprobe colour fields"
2498 );
2499 }
2500
2501 /// A frame whose size does not match the encoder's configured geometry
2502 /// is refused by name.
2503 #[test]
2504 fn geometry_mismatch_is_refused() {
2505 let _knobs = crate::speed::knob_read();
2506 let config = EncoderConfig {
2507 width: 64,
2508 height: 64,
2509 base_q_idx: 100,
2510 gop: 4,
2511 colour: Colour::Bt709Limited,
2512 tile_cols_log2: 0,
2513 tile_rows_log2: 0,
2514 };
2515 let mut enc = Av1Encoder::new(config).unwrap();
2516 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
2517 assert!(err.to_string().contains("64x64"), "{err}");
2518 }
2519
2520 /// `gop == 0` is refused at construction, not the first `encode()` call.
2521 #[test]
2522 fn zero_gop_is_refused() {
2523 let _knobs = crate::speed::knob_read();
2524 let config = EncoderConfig {
2525 width: 64,
2526 height: 64,
2527 base_q_idx: 100,
2528 gop: 0,
2529 colour: Colour::Bt709Limited,
2530 tile_cols_log2: 0,
2531 tile_rows_log2: 0,
2532 };
2533 let err = Av1Encoder::new(config).unwrap_err();
2534 assert!(err.to_string().contains("gop"), "{err}");
2535 }
2536
2537 /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget`
2538 /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down
2539 /// to this facade's own input size, and re-coded through the facade so the
2540 /// rate-target surface is exercised at the entry point a caller actually
2541 /// drives.
2542 fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> {
2543 if !have_ffmpeg() {
2544 return None;
2545 }
2546 // lane-av1speed3: the wall tables below are read on REAL film as
2547 // well as on the colour-bar fixture (`bars` vs `film` in the BD
2548 // gate's own vocabulary), and the film crop lives outside the repo --
2549 // `EC_AV1_WALL_CLIP` names it. Unset everywhere else, so every other
2550 // caller still gets the fixture.
2551 let clip = match std::env::var("EC_AV1_WALL_CLIP") {
2552 Ok(p) => std::path::PathBuf::from(p),
2553 Err(_) => std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2554 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"),
2555 };
2556 if !clip.exists() {
2557 return None;
2558 }
2559 let out = Command::new("ffmpeg")
2560 .args(["-v", "error", "-i", clip.to_str().unwrap()])
2561 .args(["-frames:v", &frames.to_string()])
2562 .args(["-vf", &format!("scale={width}:{height}")])
2563 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
2564 .output()
2565 .expect("ffmpeg failed to run");
2566 assert!(
2567 out.status.success(),
2568 "{}",
2569 String::from_utf8_lossy(&out.stderr)
2570 );
2571 let (luma, chroma) = (width * height, width * height / 4);
2572 let frame_len = luma + 2 * chroma;
2573 assert_eq!(
2574 out.stdout.len(),
2575 frame_len * frames,
2576 "expected {frames} 4:2:0 frames"
2577 );
2578 Some(
2579 (0..frames)
2580 .map(|i| {
2581 let bytes = &out.stdout[i * frame_len..][..frame_len];
2582 Picture {
2583 width,
2584 height,
2585 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
2586 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
2587 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
2588 }
2589 })
2590 .collect(),
2591 )
2592 }
2593
2594 /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total
2595 /// coded size within ±20% of `frames * target` once the first few
2596 /// frames' settling has been discarded (the key frame's own reference
2597 /// state and the controller's first couple of steps).
2598 #[test]
2599 fn bytes_per_frame_target_settles_within_20_percent() {
2600 let _knobs = crate::speed::knob_read();
2601 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
2602 eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture");
2603 return;
2604 };
2605 let target_bytes = 4_000u32;
2606 let config = EncoderConfig {
2607 width: 640,
2608 height: 384,
2609 base_q_idx: 100,
2610 gop: 24,
2611 colour: Colour::Bt709Limited,
2612 tile_cols_log2: 0,
2613 tile_rows_log2: 0,
2614 };
2615 let mut enc =
2616 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
2617 let sizes: Vec<usize> = encode_all(&mut enc, &pictures)
2618 .iter()
2619 .map(|p| p.data.len())
2620 .collect();
2621 // Discard the key frame (always far larger than an inter target) and
2622 // the next 4 inter frames the loop needs to step toward it.
2623 let settled = &sizes[5..];
2624 let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64;
2625 let low = f64::from(target_bytes) * 0.8;
2626 let high = f64::from(target_bytes) * 1.2;
2627 assert!(
2628 mean >= low && mean <= high,
2629 "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}"
2630 );
2631 }
2632
2633 /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±5% of the
2634 /// target over 48 frames of a real clip, flat and under a pyramid alike,
2635 /// across a 5x span of bitrates. This is the accuracy claim of the
2636 /// target-bitrate mode: no two-pass, no lookahead, just each frame's size
2637 /// predicted from the previous frame of its own level, one clamped
2638 /// proportional step, and the level model
2639 /// ([`WEIGHT_LEVEL_GAIN`]) that says how the run's budget splits.
2640 ///
2641 /// The tolerance was ±10% and every arm was inside ±3.0% when it was cut
2642 /// to ±5%; the worst arm is the 2 Mbit/s pyramid at -4.4%, which is the
2643 /// ENCODER'S OWN CEILING showing through, not the loop's aim: at that
2644 /// rate the hidden slot already codes at `q_idx` 1 (its 22863 bytes a
2645 /// frame are the same at 1.5 and 2 Mbit/s) and the leaves sit at 1 + 12
2646 /// `leaf_q_offset`, so this clip cannot be made to spend much past
2647 /// 2.4 Mbit/s under the default pyramid however the budget is split.
2648 #[test]
2649 fn bitrate_target_lands_within_5_percent_over_48_frames() {
2650 let _knobs = crate::speed::knob_read();
2651 let (width, height, frames) = (640usize, 384usize, 48usize);
2652 let Some(pictures) = h264_clip_frames(width, height, frames) else {
2653 eprintln!("SKIP bitrate_target_lands_within_5_percent_over_48_frames: no ffmpeg/fixture");
2654 return;
2655 };
2656 let fps = 24.0;
2657 for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] {
2658 let config = EncoderConfig {
2659 width,
2660 height,
2661 base_q_idx: 100,
2662 gop: frames,
2663 colour: Colour::Bt709Limited,
2664 tile_cols_log2: 0,
2665 tile_rows_log2: 0,
2666 };
2667 let rate = RateTarget::Bitrate {
2668 bits_per_second,
2669 frames_per_second: fps,
2670 };
2671 for pyramid in [None, Some(Pyramid::default())] {
2672 let mut enc = match pyramid {
2673 None => Av1Encoder::with_rate_target(config, rate).unwrap(),
2674 Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(),
2675 };
2676 let targets = enc.rate_loop.as_ref().unwrap().target;
2677 let mut coded = 0usize;
2678 // Per level, so a miss reads as WHICH level's model is off
2679 // rather than as one aggregate percentage.
2680 let (mut bytes, mut count) = ([0usize; 4], [0usize; 4]);
2681 let mut take = |packets: Vec<Packet>| {
2682 for packet in packets {
2683 coded += packet.data.len();
2684 let i = match packet.level {
2685 Level::Key => 0,
2686 Level::Arf => 1,
2687 Level::Leaf => 2,
2688 Level::ShowExisting => 3,
2689 };
2690 bytes[i] += packet.data.len();
2691 count[i] += 1;
2692 }
2693 };
2694 for picture in &pictures {
2695 take(enc.encode_frames(picture).unwrap());
2696 }
2697 take(enc.flush().unwrap());
2698 let seconds = frames as f64 / fps;
2699 let achieved = coded as f64 * 8.0 / seconds;
2700 let error = achieved / f64::from(bits_per_second) - 1.0;
2701 let per = |i: usize| match count[i] {
2702 0 => "-".to_string(),
2703 n => format!("{n}x{}", bytes[i] / n),
2704 };
2705 eprintln!(
2706 "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \
2707 = {achieved:.0} bps ({:+.1}%) | targets {:.0}/{:.0}/{:.0} \
2708 coded key {} arf {} leaf {}",
2709 pyramid.is_some(),
2710 100.0 * error,
2711 targets[0],
2712 targets[1],
2713 targets[2],
2714 per(0),
2715 per(1),
2716 per(2),
2717 );
2718 assert!(
2719 error.abs() <= 0.05,
2720 "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \
2721 (pyramid {})",
2722 100.0 * error,
2723 pyramid.is_some(),
2724 );
2725 }
2726 }
2727 }
2728
2729 /// The `BytesPerFrame` controller's own windup bound: no frame's coded
2730 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
2731 /// clip's full range of content (so a scene cut can't be the one frame
2732 /// that breaks the bound).
2733 ///
2734 /// The SEEDING frame is the one exemption ([`RateLoop::update`]): a slot
2735 /// that has coded nothing yet is still sitting on the caller's
2736 /// `base_q_idx` guess, and its first step is the acquisition jump, not
2737 /// windup. Exactly one frame is exempt -- the loop below asserts the
2738 /// bound on every frame after it, which is where a scene cut would
2739 /// break it.
2740 #[test]
2741 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
2742 let _knobs = crate::speed::knob_read();
2743 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
2744 eprintln!(
2745 "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture"
2746 );
2747 return;
2748 };
2749 let config = EncoderConfig {
2750 width: 640,
2751 height: 384,
2752 base_q_idx: 100,
2753 gop: 24,
2754 colour: Colour::Bt709Limited,
2755 tile_cols_log2: 0,
2756 tile_rows_log2: 0,
2757 };
2758 let mut enc =
2759 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
2760 let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
2761 // The first frame this encoder EMITS is several `encode_frames` calls
2762 // in (the lookahead queue holds the earlier ones), so the seeding
2763 // step is not frame zero -- it is the first frame `q` moves at all.
2764 let mut seeded = false;
2765 let mut seed_frame = None;
2766 for (frame, picture) in pictures.iter().enumerate() {
2767 enc.encode_frames(picture).unwrap();
2768 let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
2769 let step = (i32::from(q) - i32::from(prev_q)).abs();
2770 if step > 0 && !seeded {
2771 seeded = true;
2772 seed_frame = Some(frame);
2773 } else {
2774 assert!(
2775 f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
2776 "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp",
2777 RateLoop::STEP_CLAMP
2778 );
2779 }
2780 prev_q = q;
2781 }
2782 assert!(
2783 seed_frame.is_some(),
2784 "the controller never steered at all -- the bound below is vacuous"
2785 );
2786 }
2787
2788 fn psnr(a: &[u16], b: &[u16]) -> f64 {
2789 let squared: f64 = a
2790 .iter()
2791 .zip(b)
2792 .map(|(&x, &y)| {
2793 let d = f64::from(x) - f64::from(y);
2794 d * d
2795 })
2796 .sum();
2797 if squared == 0.0 {
2798 return f64::INFINITY;
2799 }
2800 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
2801 }
2802
2803 /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one
2804 /// entry per coded frame, in order — this facade's own equivalent of
2805 /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
2806 /// PSNR check needs the decoded pixels, not just the coded byte count.
2807 fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
2808 let path = std::env::temp_dir().join(format!(
2809 "ec-av1-facade-rate-decode-{}-{}.obu",
2810 std::process::id(),
2811 std::ptr::addr_of!(stream) as usize
2812 ));
2813 std::fs::write(&path, stream).expect("writing the decode probe stream");
2814 let out = Command::new("ffmpeg")
2815 .args(["-v", "error", "-f", "obu", "-i"])
2816 .arg(&path)
2817 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
2818 .output()
2819 .expect("ffmpeg failed to run");
2820 let _ = std::fs::remove_file(&path);
2821 assert!(
2822 out.status.success(),
2823 "{}",
2824 String::from_utf8_lossy(&out.stderr)
2825 );
2826 let (luma, chroma) = (width * height, width * height / 4);
2827 let frame_len = luma + 2 * chroma;
2828 out.stdout
2829 .chunks_exact(frame_len)
2830 .map(|f| f[..luma].to_vec())
2831 .collect()
2832 }
2833
2834 /// A pyramid stream reorders pictures: the hidden `ALTREF` of each
2835 /// mini-GOP is coded before the leaves that precede it in display order,
2836 /// and a `show_existing_frame` header puts it back. This pins the shape
2837 /// (one packet per source picture plus one `show_existing_frame` per
2838 /// group, `dts` monotone, `order` NOT monotone) and then decodes the
2839 /// whole stream through OUR decoder and through ffmpeg/dav1d and requires
2840 /// the two display-order outputs to agree sample for sample — the
2841 /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never
2842 /// output, or output twice, or output in the wrong position, changes the
2843 /// display-order list and fails here.
2844 #[test]
2845 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
2846 // `take_ref_frame_hits` is a process-global counter: a reader-locked
2847 // sibling encoding at the same time zeroes it between our encode and
2848 // our read (seen once: LAST 0 GOLDEN 0 ALTREF 0), so this takes the
2849 // exclusive lock.
2850 let _knobs = crate::speed::knob_write();
2851 pyramid_round_trip(Pyramid { mini_gop: 4, mid_q_offset: None, ..Pyramid::default() }, 2);
2852 }
2853
2854 /// The same round trip over a THREE-level group (`mid_q_offset`): each
2855 /// mini-GOP now codes two hidden frames -- the top ARF at the group's
2856 /// last picture and the mid ARF at the middle of the leaf run -- and
2857 /// re-outputs both with `show_existing_frame`, so a mid frame emitted in
2858 /// the wrong display position, or twice, fails the display-order compare
2859 /// against ffmpeg exactly as a top ARF does.
2860 #[test]
2861 fn a_three_level_pyramid_stream_decodes_in_display_order() {
2862 let _knobs = crate::speed::knob_write();
2863 pyramid_round_trip(
2864 Pyramid { mini_gop: 8, mid_q_offset: Some(-8), ..Pyramid::default() },
2865 2,
2866 );
2867 }
2868
2869 /// The same round trip over a FOUR-level group
2870 /// ([`Pyramid::quarter_q_offset`]): a mini-GOP of eight now codes four
2871 /// hidden frames -- the top ARF at picture 8, the mid at 4 and the two
2872 /// quarters at 2 and 6 -- each re-output by its own
2873 /// `show_existing_frame`. Every leaf reads a different pair of DPB slots
2874 /// than it did at three levels, so a slot map that lets one level
2875 /// overwrite a picture another is still reading shows up here as a
2876 /// display-order mismatch against ffmpeg.
2877 #[test]
2878 fn a_four_level_pyramid_stream_decodes_in_display_order() {
2879 let _knobs = crate::speed::knob_write();
2880 pyramid_round_trip(
2881 Pyramid {
2882 mini_gop: 8,
2883 mid_q_offset: Some(-8),
2884 quarter_q_offset: Some(4),
2885 ..Pyramid::default()
2886 },
2887 4,
2888 );
2889 }
2890
2891 /// [`Pyramid::key_q_offset`] reaches the key frame: the whole run reads
2892 /// the key, so an offset that never arrived would be invisible in the BD
2893 /// table except as "no change" (class symbol-consumption-gap). A finer
2894 /// key must cost strictly more bytes than the same picture at base q.
2895 #[test]
2896 fn the_key_q_offset_reaches_the_key_frame() {
2897 let _knobs = crate::speed::knob_read();
2898 crate::encode::force_screen(Some(false));
2899 let key_bytes = |offset: i16| {
2900 let config = EncoderConfig {
2901 width: 128,
2902 height: 128,
2903 base_q_idx: 120,
2904 gop: 32,
2905 colour: Colour::Bt709Limited,
2906 tile_cols_log2: 0,
2907 tile_rows_log2: 0,
2908 };
2909 let pyramid = Pyramid { key_q_offset: offset, ..Pyramid::default() };
2910 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
2911 let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap();
2912 let key = packets.iter().find(|p| p.level == Level::Key).expect("key frame");
2913 key.data.len()
2914 };
2915 let (base, finer) = (key_bytes(0), key_bytes(-48));
2916 eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes");
2917 assert!(finer > base, "key_q_offset -48 did not reach the key frame ({finer} <= {base})");
2918 }
2919
2920 fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) {
2921 let (width, height) = (128usize, 128usize);
2922 let config = EncoderConfig {
2923 width,
2924 height,
2925 base_q_idx: 120,
2926 gop: 32,
2927 colour: Colour::Bt709Limited,
2928 tile_cols_log2: 0,
2929 tile_rows_log2: 0,
2930 };
2931 // The content gate ([`Av1Encoder::encode_frames`]) would drop a
2932 // screen-content stream to the flat path, and a synthetic test card
2933 // is exactly the few-colour picture the detector fires on: this gate
2934 // is about the reordering, so it asks for camera content explicitly.
2935 crate::encode::force_screen(Some(false));
2936 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
2937 let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect();
2938 let _ = crate::encode::take_ref_frame_hits();
2939 let mut packets = Vec::new();
2940 for picture in &sources {
2941 packets.extend(enc.encode_frames(picture).unwrap());
2942 }
2943 packets.extend(enc.flush().unwrap());
2944
2945 // Shape: every source picture is coded exactly once, and each closed
2946 // group adds one `show_existing_frame` packet.
2947 let coded: Vec<u64> = packets
2948 .iter()
2949 .filter(|p| p.level != Level::ShowExisting)
2950 .map(|p| p.order)
2951 .collect();
2952 let mut sorted = coded.clone();
2953 sorted.sort_unstable();
2954 assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture");
2955 assert_ne!(coded, sorted, "the pyramid never reordered anything");
2956 let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count();
2957 assert_eq!(shown, hidden, "one show_existing_frame per hidden frame");
2958 for (i, p) in packets.iter().enumerate() {
2959 assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position");
2960 }
2961 let hist = |l: Level| packets.iter().filter(|p| p.level == l).count();
2962 eprintln!(
2963 "pyramid levels: key {} arf {} leaf {} show_existing {}",
2964 hist(Level::Key),
2965 hist(Level::Arf),
2966 hist(Level::Leaf),
2967 hist(Level::ShowExisting),
2968 );
2969 assert_eq!(hist(Level::Arf), hidden, "hidden frames");
2970 let refs = crate::encode::take_ref_frame_hits();
2971 eprintln!(
2972 "blocks per reference: LAST {} GOLDEN {} ALTREF {}",
2973 refs[crate::mvstack::LAST_FRAME as usize],
2974 refs[crate::mvstack::GOLDEN_FRAME as usize],
2975 refs[crate::mvstack::ALTREF_FRAME as usize],
2976 );
2977 // [[gate-blind-to-feature]]: the whole point of the hidden frame is
2978 // that the leaves predict BACKWARD off it, which is also the only
2979 // thing that exercises `ref_frame_sign_bias` in the MV stack. A green
2980 // round trip in which `ALTREF_FRAME` never won a block would prove
2981 // only that a hidden frame can be written and re-output.
2982 assert!(
2983 refs[crate::mvstack::ALTREF_FRAME as usize] > 0,
2984 "no block predicted off the hidden ALTREF"
2985 );
2986
2987 let stream = concat(&packets);
2988 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2989 assert_eq!(ours.len(), sources.len(), "our decoder's display-order count");
2990 if !have_ffmpeg() {
2991 eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg");
2992 return;
2993 }
2994 let theirs = ffmpeg_decode_luma(&stream, width, height);
2995 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
2996 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2997 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
2998 assert_eq!(got.len(), b.len(), "frame {i}: luma size");
2999 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3000 panic!(
3001 "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3002 at % width,
3003 at / width,
3004 got[at],
3005 b[at],
3006 );
3007 }
3008 }
3009 }
3010
3011 /// Every tile layout this encoder can write decodes SAMPLE-EXACT
3012 /// through both decoders -- ours and ffmpeg's -- and the frames really
3013 /// carry the tiles the header claims (the OBU parser locates one payload
3014 /// per tile, so a stream that quietly stayed single-tile fails here
3015 /// rather than passing on a green round trip).
3016 ///
3017 /// The bytes are what the gate is on: an encoder that clipped its
3018 /// neighbour availability wrong writes a stream whose two decoders agree
3019 /// with each other and disagree with nothing -- so the ffmpeg half is
3020 /// the one that catches a tile boundary the writer respected and the
3021 /// spec does not, and the parser half catches the reverse.
3022
3023 /// A STATIC clip: every inter frame predicts perfectly from the last, so
3024 /// the search takes the 64x64 root ([`crate::encode::B64_ROOT`]) instead
3025 /// of coding four 32x32 quadrants, and the stream both decoders
3026 /// reconstruct is still sample-exact against the encoder's own
3027 /// reconstruction. The counter is the point (class
3028 /// `gate-blind-to-feature`): without it a green three-way compare says
3029 /// nothing about whether a single 64x64 block was ever written.
3030 #[test]
3031 fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() {
3032 let _knobs = crate::speed::knob_write();
3033 let _gate_lock = crate::stream::tests::lock_gate_counters();
3034 let (width, height) = (256usize, 128usize);
3035 let still = test_card(width, height, 0);
3036 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
3037 let config = EncoderConfig {
3038 width,
3039 height,
3040 base_q_idx: 120,
3041 gop: 8,
3042 colour: Colour::Bt709Limited,
3043 tile_cols_log2: 0,
3044 tile_rows_log2: 0,
3045 };
3046 let mut enc = Av1Encoder::new(config).unwrap();
3047 let mut stream = Vec::new();
3048 let _ = crate::encode::take_b64_root_hits();
3049 for packet in encode_all(&mut enc, &sources) {
3050 stream.extend_from_slice(&packet.data);
3051 }
3052 let roots = crate::encode::take_b64_root_hits();
3053 // 8 superblocks per frame, two inter frames.
3054 assert!(
3055 roots > 0,
3056 "a static clip coded no 64x64 root at all (of 16 inter superblocks)"
3057 );
3058 eprintln!("64x64 roots on a static clip: {roots} of 16 inter superblocks");
3059
3060 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3061 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3062 if !have_ffmpeg() {
3063 eprintln!("SKIP the ffmpeg half: no ffmpeg");
3064 return;
3065 }
3066 let theirs = ffmpeg_decode_luma(&stream, width, height);
3067 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3068 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3069 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3070 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3071 panic!(
3072 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3073 at % width,
3074 at / width,
3075 got[at],
3076 b[at],
3077 );
3078 }
3079 }
3080 }
3081
3082 /// The same clip with a DC step between frames (lane-tx64): the 64x64
3083 /// root still predicts the whole superblock from the last frame, but the
3084 /// prediction is uniformly off, so the root's NON-skip arm -- one
3085 /// TX_64X64 luma transform and two TX_32X32 chroma ones -- prices below
3086 /// its skip arm and a 64x64 residual is really written. The counter is
3087 /// the gate (class `gate-blind-to-feature`; the static clip above cannot
3088 /// reach this arm at all because its prediction is exact), and both
3089 /// decoders have to reconstruct those coefficients sample-exact -- a
3090 /// writer that names the wrong coefficient set or the wrong `txfm_split`
3091 /// desyncs the whole tile here.
3092 #[test]
3093 fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() {
3094 let _knobs = crate::speed::knob_write();
3095 let _gate_lock = crate::stream::tests::lock_gate_counters();
3096 let (width, height) = (256usize, 128usize);
3097 let still = test_card(width, height, 0);
3098 let sources: Vec<Picture> = (0..3)
3099 .map(|t| {
3100 let mut p = still.clone();
3101 let step = (t * 6) as u16;
3102 for v in &mut p.y {
3103 *v = (*v + step).min(255);
3104 }
3105 p
3106 })
3107 .collect();
3108 let config = EncoderConfig {
3109 width,
3110 height,
3111 base_q_idx: 120,
3112 gop: 8,
3113 colour: Colour::Bt709Limited,
3114 tile_cols_log2: 0,
3115 tile_rows_log2: 0,
3116 };
3117 let mut enc = Av1Encoder::new(config).unwrap();
3118 let mut stream = Vec::new();
3119 let _ = crate::encode::take_b64_residual_hits();
3120 for packet in encode_all(&mut enc, &sources) {
3121 stream.extend_from_slice(&packet.data);
3122 }
3123 let residuals = crate::encode::take_b64_residual_hits();
3124 assert!(
3125 residuals > 0,
3126 "a DC-stepped clip coded no 64x64 root with a residual at all"
3127 );
3128 eprintln!("64x64 roots with a residual: {residuals} of 16 inter superblocks");
3129
3130 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3131 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3132 if !have_ffmpeg() {
3133 eprintln!("SKIP the ffmpeg half: no ffmpeg");
3134 return;
3135 }
3136 let theirs = ffmpeg_decode_luma(&stream, width, height);
3137 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3138 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3139 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3140 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3141 panic!(
3142 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3143 at % width,
3144 at / width,
3145 got[at],
3146 b[at],
3147 );
3148 }
3149 }
3150 }
3151
3152 /// A frame whose size is NOT a multiple of a superblock (lane-b64b):
3153 /// 232x168 leaves the last superblock column and row cut by the true
3154 /// frame edge, with more than half of each inside -- which is exactly
3155 /// what AV1's `has_cols`/`has_rows` allow to stay whole. Both gate films
3156 /// are superblock-aligned, so nothing but a synthetic size reaches this
3157 /// path at all (class `gate-blind-to-feature`), and the user's own
3158 /// exports are arbitrary sizes.
3159 #[test]
3160 fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() {
3161 let _knobs = crate::speed::knob_write();
3162 let _gate_lock = crate::stream::tests::lock_gate_counters();
3163 let (width, height) = (232usize, 168usize);
3164 let still = test_card(width, height, 0);
3165 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
3166 let config = EncoderConfig {
3167 width,
3168 height,
3169 base_q_idx: 120,
3170 gop: 8,
3171 colour: Colour::Bt709Limited,
3172 tile_cols_log2: 0,
3173 tile_rows_log2: 0,
3174 };
3175 let mut enc = Av1Encoder::new(config).unwrap();
3176 let mut stream = Vec::new();
3177 let _ = crate::encode::take_b64_edge_hits();
3178 for packet in encode_all(&mut enc, &sources) {
3179 stream.extend_from_slice(&packet.data);
3180 }
3181 let edges = crate::encode::take_b64_edge_hits();
3182 assert!(edges > 0, "no 64x64 root was taken at a superblock the frame edge cuts");
3183 eprintln!("edge 64x64 roots: {edges}");
3184
3185 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3186 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3187 if !have_ffmpeg() {
3188 eprintln!("SKIP the ffmpeg half: no ffmpeg");
3189 return;
3190 }
3191 let theirs = ffmpeg_decode_luma(&stream, width, height);
3192 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3193 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
3194 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
3195 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
3196 panic!(
3197 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3198 at % width,
3199 at / width,
3200 got[at],
3201 theirs_i[at],
3202 );
3203 }
3204 }
3205 }
3206
3207 /// The 1080p SHAPE at a fifth of its size (lane-sse): 384x216 is three
3208 /// whole superblock columns and 1.6875 superblock rows, so the bottom
3209 /// 88-pixel band straddles at EVERY level -- the 64x64 root lane-b64b
3210 /// already clipped, and the 32x32 (216 = 6*32 + 24) and 16x16 (13*16 + 8)
3211 /// leaves it did not. Every one of them is now scored over its inside
3212 /// part alone, and a distortion change that moved a partition or a
3213 /// transform decision the writer did not follow would desync the tile, so
3214 /// both decoders reconstruct it sample-exact.
3215 #[test]
3216 fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() {
3217 let _knobs = crate::speed::knob_write();
3218 let _gate_lock = crate::stream::tests::lock_gate_counters();
3219 let (width, height) = (384usize, 216usize);
3220 let sources: Vec<Picture> = (0..3).map(|i| test_card(width, height, i)).collect();
3221 let config = EncoderConfig {
3222 width,
3223 height,
3224 base_q_idx: 120,
3225 gop: 8,
3226 colour: Colour::Bt709Limited,
3227 tile_cols_log2: 0,
3228 tile_rows_log2: 0,
3229 };
3230 let mut enc = Av1Encoder::new(config).unwrap();
3231 let mut stream = Vec::new();
3232 for packet in encode_all(&mut enc, &sources) {
3233 stream.extend_from_slice(&packet.data);
3234 }
3235 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3236 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3237 if !have_ffmpeg() {
3238 eprintln!("SKIP the ffmpeg half: no ffmpeg");
3239 return;
3240 }
3241 let theirs = ffmpeg_decode_luma(&stream, width, height);
3242 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3243 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
3244 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
3245 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
3246 panic!(
3247 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3248 at % width,
3249 at / width,
3250 got[at],
3251 theirs_i[at],
3252 );
3253 }
3254 }
3255 }
3256
3257 /// A clip whose inter residual is HIGH-FREQUENCY (lane-b64b): every
3258 /// frame adds a 4-pixel checkerboard, so the 64x64 root's prediction is
3259 /// off by exactly the detail a TX_64X64 throws away (it codes only the
3260 /// top-left 32x32 corner of its coefficient space) and the root's var-tx
3261 /// arm splits its luma into four TX_32X32 units instead. The counter is
3262 /// the gate (class `gate-blind-to-feature`), and a `txfm_split` the
3263 /// reader does not expect desyncs the whole tile, so both decoders have
3264 /// to reconstruct it sample-exact.
3265 #[test]
3266 fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() {
3267 let _knobs = crate::speed::knob_write();
3268 let _gate_lock = crate::stream::tests::lock_gate_counters();
3269 let (width, height) = (256usize, 128usize);
3270 let still = test_card(width, height, 0);
3271 let sources: Vec<Picture> = (0..4)
3272 .map(|t| {
3273 let mut p = still.clone();
3274 for (i, v) in p.y.iter_mut().enumerate() {
3275 let checker = ((i % width) / 4 + (i / width) / 4) % 2;
3276 let bump = (t * 5 * (checker + 1)) as u16;
3277 *v = (*v + bump).min(255);
3278 }
3279 p
3280 })
3281 .collect();
3282 let config = EncoderConfig {
3283 width,
3284 height,
3285 base_q_idx: 90,
3286 gop: 8,
3287 colour: Colour::Bt709Limited,
3288 tile_cols_log2: 0,
3289 tile_rows_log2: 0,
3290 };
3291 let mut enc = Av1Encoder::new(config).unwrap();
3292 let mut stream = Vec::new();
3293 let _ = crate::encode::take_b64_var_tx_hits();
3294 for packet in encode_all(&mut enc, &sources) {
3295 stream.extend_from_slice(&packet.data);
3296 }
3297 let split = crate::encode::take_b64_var_tx_hits();
3298 assert!(split > 0, "no 64x64 root split its luma transform at all");
3299 eprintln!("64x64 roots with a SPLIT luma transform: {split}");
3300
3301 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3302 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3303 if !have_ffmpeg() {
3304 eprintln!("SKIP the ffmpeg half: no ffmpeg");
3305 return;
3306 }
3307 let theirs = ffmpeg_decode_luma(&stream, width, height);
3308 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3309 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
3310 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
3311 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
3312 panic!(
3313 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3314 at % width,
3315 at / width,
3316 got[at],
3317 theirs_i[at],
3318 );
3319 }
3320 }
3321 }
3322
3323 /// A CROSSFADE clip (lane-b64b): each picture is a linear blend of two
3324 /// stills, so on a leaf frame the average of its past (`LAST`) and future
3325 /// (`ALTREF`) references IS the source and neither reference alone is --
3326 /// exactly the content a COMPOUND 64x64 root pays on. The counter is the
3327 /// gate (class `gate-blind-to-feature`): without it a green three-way
3328 /// compare says nothing about whether one compound root was written, and
3329 /// the writer's compound arm (`write_compound_block` at `SB_MI` 16, no
3330 /// `motion_mode` symbol) desyncs the whole tile if it is wrong.
3331 #[test]
3332 fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() {
3333 let _knobs = crate::speed::knob_write();
3334 let _gate_lock = crate::stream::tests::lock_gate_counters();
3335 let (width, height) = (256usize, 128usize);
3336 let (a, b) = (test_card(width, height, 0), test_card(width, height, 24));
3337 let sources: Vec<Picture> = (0..9)
3338 .map(|t| {
3339 let mut p = a.clone();
3340 let w = t as u32;
3341 for (v, &other) in p.y.iter_mut().zip(&b.y) {
3342 *v = ((u32::from(*v) * (8 - w) + u32::from(other) * w) / 8) as u16;
3343 }
3344 p
3345 })
3346 .collect();
3347 let config = EncoderConfig {
3348 width,
3349 height,
3350 base_q_idx: 120,
3351 gop: 9,
3352 colour: Colour::Bt709Limited,
3353 tile_cols_log2: 0,
3354 tile_rows_log2: 0,
3355 };
3356 let mut enc = Av1Encoder::new(config).unwrap();
3357 let mut stream = Vec::new();
3358 let _ = crate::encode::take_b64_compound_hits();
3359 for packet in encode_all(&mut enc, &sources) {
3360 stream.extend_from_slice(&packet.data);
3361 }
3362 let compound = crate::encode::take_b64_compound_hits();
3363 assert!(compound > 0, "a crossfade clip coded no COMPOUND 64x64 root at all");
3364 eprintln!("compound 64x64 roots on a crossfade clip: {compound}");
3365
3366 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3367 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
3368 if !have_ffmpeg() {
3369 eprintln!("SKIP the ffmpeg half: no ffmpeg");
3370 return;
3371 }
3372 let theirs = ffmpeg_decode_luma(&stream, width, height);
3373 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
3374 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
3375 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
3376 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
3377 panic!(
3378 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3379 at % width,
3380 at / width,
3381 got[at],
3382 theirs_i[at],
3383 );
3384 }
3385 }
3386 }
3387
3388 #[test]
3389 fn every_tile_layout_decodes_sample_exact_through_both_decoders() {
3390 let _knobs = crate::speed::knob_read();
3391 let (width, height) = (640usize, 384usize);
3392 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
3393 let mut sizes = Vec::new();
3394 for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] {
3395 let config = EncoderConfig {
3396 width,
3397 height,
3398 base_q_idx: 120,
3399 gop: 4,
3400 colour: Colour::Bt709Limited,
3401 tile_cols_log2: cols_log2,
3402 tile_rows_log2: rows_log2,
3403 };
3404 let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
3405 let mut enc = Av1Encoder::new(config).unwrap();
3406 let mut stream = Vec::new();
3407 for packet in encode_all(&mut enc, &sources) {
3408 stream.extend_from_slice(&packet.data);
3409 }
3410 sizes.push((layout.clone(), stream.len()));
3411
3412 // The frames carry the tiles their headers claim.
3413 let mut parser = ec_av1_syntax::Av1Parser::new();
3414 let mut frames = 0usize;
3415 let mut offset = 0usize;
3416 while offset < stream.len() {
3417 let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap();
3418 let unit: usize = obus.iter().map(|o| o.total_size).sum();
3419 for obu in &obus {
3420 if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind {
3421 assert_eq!(
3422 (parsed.tile_info.cols, parsed.tile_info.rows),
3423 (1 << cols_log2, 1 << rows_log2),
3424 "{layout}: the header's own tile grid"
3425 );
3426 assert_eq!(
3427 tiles.len(),
3428 1 << (cols_log2 + rows_log2),
3429 "{layout}: tile payloads located in the tile group"
3430 );
3431 frames += 1;
3432 }
3433 }
3434 offset += unit;
3435 }
3436 assert_eq!(frames, sources.len(), "{layout}: coded frames");
3437
3438 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3439 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
3440 if !have_ffmpeg() {
3441 eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg");
3442 continue;
3443 }
3444 let theirs = ffmpeg_decode_luma(&stream, width, height);
3445 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
3446 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3447 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3448 assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size");
3449 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3450 panic!(
3451 "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3452 at % width,
3453 at / width,
3454 got[at],
3455 b[at],
3456 );
3457 }
3458 }
3459 }
3460 let base = sizes[0].1 as f64;
3461 for (layout, bytes) in &sizes {
3462 eprintln!(
3463 "{layout}: {bytes} bytes ({:+.2}% vs one tile)",
3464 (*bytes as f64 / base - 1.0) * 100.0
3465 );
3466 }
3467 }
3468
3469 /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct
3470 /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from
3471 /// its neighbour (a preset that changes no byte is a preset that buys no
3472 /// wall: class `gate-blind-to-feature`). Preset 0's bytes are the
3473 /// full-search ones, which is the cheap in-suite statement of the byte
3474 /// pins' rule.
3475 ///
3476 /// Ignored by default because the preset is PROCESS-GLOBAL
3477 /// ([`crate::speed`]): flipping it while the suite's other tests encode
3478 /// in parallel would move their bytes under them. Run it on its own:
3479 /// `cargo test -p ec-av1 --release -- --ignored every_speed_preset`.
3480 #[test]
3481 #[ignore = "sets the process-global speed preset: run it alone"]
3482 fn every_speed_preset_decodes_sample_exact_through_both_decoders() {
3483 let _knobs = crate::speed::knob_write();
3484 let _gate_lock = crate::stream::tests::lock_gate_counters();
3485 let (width, height) = (640usize, 384usize);
3486 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
3487 let mut sizes: Vec<(u8, usize)> = Vec::new();
3488 for speed in [0u8, 3, 6, 10] {
3489 let config = EncoderConfig {
3490 width,
3491 height,
3492 base_q_idx: 120,
3493 gop: 4,
3494 colour: Colour::Bt709Limited,
3495 tile_cols_log2: 1,
3496 tile_rows_log2: 0,
3497 };
3498 let mut enc = Av1Encoder::with_speed(config, speed).unwrap();
3499 let mut stream = Vec::new();
3500 for packet in encode_all(&mut enc, &sources) {
3501 stream.extend_from_slice(&packet.data);
3502 }
3503 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3504 assert_eq!(ours.len(), sources.len(), "speed {speed}: our decoder's frames");
3505 if have_ffmpeg() {
3506 let theirs = ffmpeg_decode_luma(&stream, width, height);
3507 assert_eq!(theirs.len(), sources.len(), "speed {speed}: ffmpeg's frames");
3508 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3509 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3510 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3511 panic!(
3512 "speed {speed} frame {i}: luma differs first at ({}, {}): \
3513 ours {} vs ffmpeg {}",
3514 at % width,
3515 at / width,
3516 got[at],
3517 b[at],
3518 );
3519 }
3520 }
3521 } else {
3522 eprintln!("SKIP the ffmpeg half of speed {speed}: no ffmpeg");
3523 }
3524 eprintln!(
3525 "speed {speed}: {} bytes [{}]",
3526 stream.len(),
3527 crate::speed::levers(speed).join(", ")
3528 );
3529 sizes.push((speed, stream.len()));
3530 }
3531 crate::speed::set_speed(0);
3532 for w in sizes.windows(2) {
3533 assert_ne!(
3534 w[0].1, w[1].1,
3535 "speed {} and {} coded the same bytes: the preset changed no decision",
3536 w[0].0, w[1].0
3537 );
3538 }
3539 }
3540
3541 /// What tiles and tile threads are worth at the size the editor exports
3542 /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall
3543 /// per cell. Ignored by default (minutes).
3544 #[test]
3545 #[ignore = "1080p wall table: minutes, run it with --ignored"]
3546 fn tile_wall_table_at_1080p() {
3547 let _knobs = crate::speed::knob_write();
3548 let _gate_lock = crate::stream::tests::lock_gate_counters();
3549 let (width, height) = (1920usize, 1080usize);
3550 let Some(sources) = h264_clip_frames(width, height, 8) else {
3551 eprintln!("SKIP tile_wall_table_at_1080p: no fixture");
3552 return;
3553 };
3554 let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)];
3555 let threadings = [1usize, 2, 4, 8];
3556 let mut table: Vec<(String, usize, f64, usize)> = Vec::new();
3557 for pass in 0..2 {
3558 for &(cols_log2, rows_log2) in &layouts {
3559 for &threads in &threadings {
3560 crate::par::set_tile_threads(threads);
3561 let config = EncoderConfig {
3562 width,
3563 height,
3564 base_q_idx: 120,
3565 gop: 8,
3566 colour: Colour::Bt709Limited,
3567 tile_cols_log2: cols_log2,
3568 tile_rows_log2: rows_log2,
3569 };
3570 let mut enc = Av1Encoder::new(config).unwrap();
3571 let start = std::time::Instant::now();
3572 let mut bytes = 0usize;
3573 for packet in encode_all(&mut enc, &sources) {
3574 bytes += packet.data.len();
3575 }
3576 let wall = start.elapsed().as_secs_f64();
3577 let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2);
3578 match table.iter_mut().find(|r| r.0 == name && r.1 == threads) {
3579 Some(row) => row.2 = row.2.min(wall),
3580 None => table.push((name, threads, wall, bytes)),
3581 }
3582 let _ = pass;
3583 }
3584 }
3585 }
3586 crate::par::set_tile_threads(1);
3587 eprintln!("| tiles | threads | wall (s, best of 2) | bytes |");
3588 for (name, threads, wall, bytes) in &table {
3589 eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |");
3590 }
3591 }
3592
3593 /// The tiles of a frame are entropy-independent, so the bytes must not
3594 /// depend on how many workers wrote them: the same stream at one tile
3595 /// thread and at four, per layout.
3596 #[test]
3597 fn tile_bytes_do_not_depend_on_the_thread_count() {
3598 let _knobs = crate::speed::knob_write();
3599 let _gate_lock = crate::stream::tests::lock_gate_counters();
3600 let (width, height) = (320usize, 192usize);
3601 let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect();
3602 let coded = |threads: usize, cols_log2: u32, rows_log2: u32| {
3603 crate::par::set_tile_threads(threads);
3604 let config = EncoderConfig {
3605 width,
3606 height,
3607 base_q_idx: 120,
3608 gop: 3,
3609 colour: Colour::Bt709Limited,
3610 tile_cols_log2: cols_log2,
3611 tile_rows_log2: rows_log2,
3612 };
3613 let mut enc = Av1Encoder::new(config).unwrap();
3614 let mut stream = Vec::new();
3615 for packet in encode_all(&mut enc, &sources) {
3616 stream.extend_from_slice(&packet.data);
3617 }
3618 stream
3619 };
3620 for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] {
3621 let one = coded(1, cols_log2, rows_log2);
3622 let four = coded(4, cols_log2, rows_log2);
3623 assert_eq!(
3624 one,
3625 four,
3626 "{}x{} tiles: {} bytes at one thread, {} at four",
3627 1 << cols_log2,
3628 1 << rows_log2,
3629 one.len(),
3630 four.len()
3631 );
3632 }
3633 crate::par::set_tile_threads(1);
3634 }
3635
3636 /// What the per-tile search (lane-av1tsearch) is worth in wall and in
3637 /// frames per second at the editor's own export sizes: every tile layout
3638 /// crossed with every tile-thread count, plus librav1e at the matching
3639 /// `tile_cols`/`tile_rows`/`threads` as the reference point. Two passes
3640 /// over the whole table (A,B,A,B... rather than AA,BB) with the best of
3641 /// the two kept, so a thermal drift cannot order the rows.
3642 ///
3643 /// Measurement, not a pass/fail gate: it asserts only that every cell
3644 /// produced a stream.
3645 #[test]
3646 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
3647 fn tile_search_wall_1080p() {
3648 let _knobs = crate::speed::knob_write();
3649 tile_search_wall(1920, 1080, 12, &[(0, 0), (1, 0), (1, 1), (2, 1)], &[1, 2, 4, 8]);
3650 }
3651
3652 /// The same table at the 4K frame size the editor exports (3840x1608),
3653 /// at the two layouts with enough tiles to fill this box.
3654 #[test]
3655 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
3656 fn tile_search_wall_4k() {
3657 let _knobs = crate::speed::knob_write();
3658 tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]);
3659 }
3660
3661 /// lane-av1fpar: the frame-level FILTER stage is banded across the same
3662 /// workers the tile search uses (`par::override_filter_threads`), so the
3663 /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in
3664 /// pieces. Every piece is a disjoint band of the same integers, so the
3665 /// stream must not move -- at a size that crops and is several superblock
3666 /// rows tall, which is what makes the bands non-trivial.
3667 #[test]
3668 fn filter_stage_bytes_do_not_depend_on_the_thread_count() {
3669 let _knobs = crate::speed::knob_write();
3670 let _gate_lock = crate::stream::tests::lock_gate_counters();
3671 let (width, height) = (384usize, 288usize);
3672 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
3673 let coded = |threads: usize| {
3674 crate::par::set_tile_threads(threads);
3675 let config = EncoderConfig {
3676 width,
3677 height,
3678 base_q_idx: 120,
3679 gop: 2,
3680 colour: Colour::Bt709Limited,
3681 tile_cols_log2: 0,
3682 tile_rows_log2: 0,
3683 };
3684 let mut enc = Av1Encoder::new(config).unwrap();
3685 let mut stream = Vec::new();
3686 for packet in encode_all(&mut enc, &sources) {
3687 stream.extend_from_slice(&packet.data);
3688 }
3689 stream
3690 };
3691 // One tile, so only the filter stage can differ between these.
3692 let one = coded(1);
3693 for threads in [2usize, 4, 8] {
3694 assert_eq!(one, coded(threads), "the filter stage moved at {threads} threads");
3695 }
3696 crate::par::set_tile_threads(1);
3697 }
3698
3699 /// lane-av1fpar: the filter search scores its ~30 candidates by replaying
3700 /// the loop filters on one captured reconstruction instead of decoding
3701 /// the coded tile again per candidate. The replay must be that decode,
3702 /// byte for byte -- including at a size that CROPS (1080 and 1608 both
3703 /// pad to a superblock row, i.e. every export size the editor uses),
3704 /// which is the arm this lane opened.
3705 #[test]
3706 fn filter_replay_codes_the_same_stream_as_a_full_decode() {
3707 let _knobs = crate::speed::knob_read();
3708 let _gate_lock = crate::stream::tests::lock_gate_counters();
3709 let run = |width: usize, height: usize, off: bool| {
3710 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
3711 crate::decode::set_filter_replay_disabled(off);
3712 let config = EncoderConfig {
3713 width,
3714 height,
3715 base_q_idx: 120,
3716 gop: 2,
3717 colour: Colour::Bt709Limited,
3718 tile_cols_log2: 0,
3719 tile_rows_log2: 0,
3720 };
3721 let mut enc = Av1Encoder::new(config).unwrap();
3722 let mut stream = Vec::new();
3723 for packet in encode_all(&mut enc, &sources) {
3724 stream.extend_from_slice(&packet.data);
3725 }
3726 crate::decode::set_filter_replay_disabled(false);
3727 stream
3728 };
3729 // 320x160 crops (the coding surface is 320x192, one superblock row
3730 // taller); 320x192 is a whole number of superblocks, the shape the
3731 // replay already covered.
3732 for (width, height) in [(320usize, 160usize), (320, 192)] {
3733 let replayed = run(width, height, false);
3734 let decoded = run(width, height, true);
3735 assert_eq!(
3736 replayed,
3737 decoded,
3738 "{width}x{height}: the filter replay is not the decode it stands in for \
3739 ({} bytes replayed, {} decoded)",
3740 replayed.len(),
3741 decoded.len(),
3742 );
3743 }
3744 }
3745
3746 /// lane-av1cap: the filter stage's FINAL replay -- the one that replaced
3747 /// the capture decode -- against that decode. `set_verify_final_replay`
3748 /// makes `encode::pick_and_apply_filters` run both on every frame and
3749 /// assert, per frame, that the spliced picture and the two filter stages
3750 /// the loop-restoration search reads are bit-identical.
3751 #[test]
3752 fn filter_replay_final_matches_the_capture_decode() {
3753 let _knobs = crate::speed::knob_read();
3754 let _gate_lock = crate::stream::tests::lock_gate_counters();
3755 let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| {
3756 let config = EncoderConfig {
3757 width,
3758 height,
3759 base_q_idx: 120,
3760 gop: 2,
3761 colour: Colour::Bt709Limited,
3762 tile_cols_log2: tiles.0,
3763 tile_rows_log2: tiles.1,
3764 };
3765 let mut enc = Av1Encoder::new(config).unwrap();
3766 for packet in encode_all(&mut enc, sources) {
3767 assert!(!packet.data.is_empty());
3768 }
3769 };
3770 crate::decode::set_verify_final_replay(true);
3771 // 320x160 crops (its coding surface is one superblock row taller);
3772 // 320x192 is a whole number of superblocks.
3773 for (width, height) in [(320usize, 160usize), (320, 192)] {
3774 let sources: Vec<Picture> =
3775 (0..4).map(|t| test_card(width, height, t * 3)).collect();
3776 run(&sources, width, height, (0, 0));
3777 }
3778 // Real gate content, where the CDEF preset search actually chooses
3779 // `bits > 0` and the tile is re-coded, one tile and four.
3780 if let Some(sources) = h264_clip_frames(640, 384, 3) {
3781 run(&sources, 640, 384, (0, 0));
3782 run(&sources, 640, 384, (1, 1));
3783 } else {
3784 eprintln!("SKIP the gate-clip arm: no fixture or no ffmpeg");
3785 }
3786 crate::decode::set_verify_final_replay(false);
3787 }
3788
3789 /// lane-av1fpar: where a frame's wall actually goes, stage by stage --
3790 /// the per-tile search, the tile write, the frame-level filter search
3791 /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture
3792 /// decode the loop-restoration search rides on, and that search itself.
3793 /// Measurement, not a pass/fail gate.
3794 #[test]
3795 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
3796 fn filter_stage_wall_1080p() {
3797 let _knobs = crate::speed::knob_write();
3798 filter_stage_wall(1920, 1080, 8, (2, 1), &[8]);
3799 }
3800
3801 #[test]
3802 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
3803 fn filter_stage_wall_4k() {
3804 let _knobs = crate::speed::knob_write();
3805 filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]);
3806 }
3807
3808 /// The same breakdown at the real films' own crop size. With
3809 /// `EC_AV1_WALL_CLIP` pointing at a film window this is the film row; with
3810 /// it unset it is the colour-bar fixture at the same size, which is what
3811 /// makes the pair a comparison rather than a number.
3812 #[test]
3813 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
3814 fn filter_stage_wall_film() {
3815 let _knobs = crate::speed::knob_write();
3816 filter_stage_wall(1920, 768, 4, (2, 1), &[8]);
3817 }
3818
3819 fn filter_stage_wall(
3820 width: usize,
3821 height: usize,
3822 frames: usize,
3823 (cols_log2, rows_log2): (u32, u32),
3824 threads: &[usize],
3825 ) {
3826 let _gate_lock = crate::stream::tests::lock_gate_counters();
3827 let Some(sources) = h264_clip_frames(width, height, frames) else {
3828 eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg");
3829 return;
3830 };
3831 crate::par::set_stage_times(true);
3832 for &t in threads {
3833 crate::par::set_tile_threads(t);
3834 let config = EncoderConfig {
3835 width,
3836 height,
3837 base_q_idx: 120,
3838 gop: frames,
3839 colour: Colour::Bt709Limited,
3840 tile_cols_log2: cols_log2,
3841 tile_rows_log2: rows_log2,
3842 };
3843 let mut enc = Av1Encoder::new(config).unwrap();
3844 let _ = crate::par::take_stage_ns();
3845 let start = std::time::Instant::now();
3846 for packet in encode_all(&mut enc, &sources) {
3847 assert!(!packet.data.is_empty());
3848 }
3849 let wall = start.elapsed().as_secs_f64();
3850 let ns = crate::par::take_stage_ns();
3851 let ms = |i: usize| ns[i] as f64 / 1e6;
3852 eprintln!(
3853 "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \
3854 {wall:.2}s wall, {:.2} fps",
3855 1 << cols_log2,
3856 1 << rows_log2,
3857 frames as f64 / wall,
3858 );
3859 eprintln!("| stage | ms | ms/frame | % of wall |");
3860 for (i, name) in crate::par::STAGES.iter().enumerate() {
3861 eprintln!(
3862 "| {name} | {:.0} | {:.1} | {:.1}% |",
3863 ms(i),
3864 ms(i) / frames as f64,
3865 100.0 * ms(i) / (wall * 1e3),
3866 );
3867 }
3868 // Top-level stages only (the deblock/CDEF/SSE rows are inside
3869 // the filter-search total); the rest is per-frame setup, the
3870 // source conversion and the splice.
3871 let top: f64 = [
3872 crate::par::S_TILE_SEARCH,
3873 crate::par::S_TILE_WRITE,
3874 crate::par::S_FILTER,
3875 crate::par::S_CAPTURE,
3876 crate::par::S_LR,
3877 ]
3878 .iter()
3879 .map(|&i| ms(i))
3880 .sum();
3881 eprintln!(
3882 "accounted {:.1}% of wall; outside the tile search {:.1}%",
3883 100.0 * top / (wall * 1e3),
3884 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)),
3885 );
3886 }
3887 crate::par::set_stage_times(false);
3888 crate::par::set_tile_threads(1);
3889 }
3890
3891 fn tile_search_wall(
3892 width: usize,
3893 height: usize,
3894 frames: usize,
3895 layouts: &[(u32, u32)],
3896 threads: &[usize],
3897 ) {
3898 let _gate_lock = crate::stream::tests::lock_gate_counters();
3899 let Some(sources) = h264_clip_frames(width, height, frames) else {
3900 eprintln!("SKIP the tile-search wall table: no fixture or no ffmpeg");
3901 return;
3902 };
3903 let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) {
3904 crate::par::set_tile_threads(t);
3905 let config = EncoderConfig {
3906 width,
3907 height,
3908 base_q_idx: 120,
3909 gop: frames,
3910 colour: Colour::Bt709Limited,
3911 tile_cols_log2: cols_log2,
3912 tile_rows_log2: rows_log2,
3913 };
3914 let mut enc = Av1Encoder::new(config).unwrap();
3915 let start = std::time::Instant::now();
3916 let mut bytes = 0usize;
3917 for packet in encode_all(&mut enc, &sources) {
3918 bytes += packet.data.len();
3919 }
3920 (start.elapsed(), bytes)
3921 };
3922 let cells: Vec<((u32, u32), usize)> = layouts
3923 .iter()
3924 .flat_map(|&l| threads.iter().map(move |&t| (l, t)))
3925 .collect();
3926 let mut best: Vec<Option<(std::time::Duration, usize)>> = vec![None; cells.len()];
3927 for _pass in 0..2 {
3928 for (i, &((c, r), t)) in cells.iter().enumerate() {
3929 let got = run(c, r, t);
3930 assert!(got.1 > 0, "{}x{} tiles at {t} threads: empty stream", 1 << c, 1 << r);
3931 if best[i].is_none_or(|(w, _)| got.0 < w) {
3932 best[i] = Some(got);
3933 }
3934 }
3935 }
3936 crate::par::set_tile_threads(1);
3937 eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes");
3938 eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |");
3939 let base = best[0].expect("the first cell ran").0.as_secs_f64();
3940 for (i, &((c, r), t)) in cells.iter().enumerate() {
3941 let (wall, bytes) = best[i].expect("every cell ran");
3942 let secs = wall.as_secs_f64();
3943 eprintln!(
3944 "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |",
3945 1 << c,
3946 1 << r,
3947 1 << (c + r),
3948 frames as f64 / secs,
3949 base / secs,
3950 );
3951 }
3952 // Parallel efficiency per layout: what the extra threads actually
3953 // took off that layout's own single-threaded wall, and so what share
3954 // of the added cores sat idle.
3955 for &(c, r) in layouts {
3956 let one = cells
3957 .iter()
3958 .position(|&(l, t)| l == (c, r) && t == threads[0])
3959 .map(|i| best[i].expect("cell").0.as_secs_f64());
3960 let Some(one) = one else { continue };
3961 for &t in &threads[1..] {
3962 let i = cells.iter().position(|&(l, tt)| l == (c, r) && tt == t).expect("cell");
3963 let secs = best[i].expect("cell").0.as_secs_f64();
3964 let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64;
3965 let speedup = one / secs;
3966 eprintln!(
3967 "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \
3968 idle share {:.0}%",
3969 1 << c,
3970 1 << r,
3971 threads[0],
3972 100.0 * (1.0 - speedup / workers).max(0.0),
3973 );
3974 }
3975 }
3976 rav1e_wall_reference(width, height, frames, layouts, threads);
3977 }
3978
3979 /// librav1e at the same sizes, layouts and thread counts, through ffmpeg
3980 /// -- the reference the wall table is read against.
3981 fn rav1e_wall_reference(
3982 width: usize,
3983 height: usize,
3984 frames: usize,
3985 layouts: &[(u32, u32)],
3986 threads: &[usize],
3987 ) {
3988 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3989 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
3990 let listed = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output();
3991 let has_rav1e = listed
3992 .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e"))
3993 .unwrap_or(false);
3994 if !has_rav1e || !clip.exists() {
3995 eprintln!("SKIP the rav1e reference: no librav1e or no fixture");
3996 return;
3997 }
3998 eprintln!("| rav1e layout | threads | wall | fps | bytes |");
3999 for &(c, r) in layouts {
4000 for &t in threads {
4001 let out = std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id()));
4002 let params = format!(
4003 "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}",
4004 1 << c,
4005 1 << r
4006 );
4007 let start = std::time::Instant::now();
4008 let status = Command::new("ffmpeg")
4009 .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()])
4010 .args(["-frames:v", &frames.to_string()])
4011 .args(["-vf", &format!("scale={width}:{height}")])
4012 .args(["-c:v", "librav1e", "-rav1e-params", &params])
4013 .arg(out.to_str().unwrap())
4014 .output()
4015 .expect("ffmpeg failed to run");
4016 let secs = start.elapsed().as_secs_f64();
4017 if !status.status.success() {
4018 eprintln!("| {}x{} | {t} | FAILED: {} |", 1 << c, 1 << r, String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or(""));
4019 continue;
4020 }
4021 let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
4022 let _ = std::fs::remove_file(&out);
4023 eprintln!(
4024 "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |",
4025 1 << c,
4026 1 << r,
4027 frames as f64 / secs
4028 );
4029 }
4030 }
4031 }
4032
4033 /// The same round trip at a real 1920x1080 crop of the gate's own clip
4034 /// -- the size the editor's export actually runs at, where a tile grid
4035 /// is worth having. Ignored by default only for its wall (a 1080p
4036 /// encode of three pictures), not for any weakness in the check.
4037 #[test]
4038 #[ignore = "1080p encode: minutes, run it with --ignored"]
4039 fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() {
4040 let _knobs = crate::speed::knob_read();
4041 let (width, height) = (1920usize, 1080usize);
4042 let Some(sources) = h264_clip_frames(width, height, 3) else {
4043 eprintln!("SKIP the 1080p tile round trip: no fixture");
4044 return;
4045 };
4046 for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] {
4047 let config = EncoderConfig {
4048 width,
4049 height,
4050 base_q_idx: 120,
4051 gop: 3,
4052 colour: Colour::Bt709Limited,
4053 tile_cols_log2: cols_log2,
4054 tile_rows_log2: rows_log2,
4055 };
4056 let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
4057 let mut enc = Av1Encoder::new(config).unwrap();
4058 let mut stream = Vec::new();
4059 for packet in encode_all(&mut enc, &sources) {
4060 stream.extend_from_slice(&packet.data);
4061 }
4062 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4063 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
4064 if !have_ffmpeg() {
4065 eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg");
4066 continue;
4067 }
4068 let theirs = ffmpeg_decode_luma(&stream, width, height);
4069 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
4070 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4071 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4072 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
4073 panic!(
4074 "1080p {layout} frame {i}: luma differs first at ({}, {})",
4075 at % width,
4076 at / width
4077 );
4078 }
4079 }
4080 eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len());
4081 }
4082 }
4083
4084 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
4085 /// produces a smaller stream or a worse mean PSNR than a lower one, on
4086 /// the same real clip.
4087 #[test]
4088 fn quality_target_is_monotone_in_bytes_and_psnr() {
4089 let _knobs = crate::speed::knob_read();
4090 if !have_ffmpeg() {
4091 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg");
4092 return;
4093 }
4094 let (width, height) = (640, 384);
4095 let Some(pictures) = h264_clip_frames(width, height, 8) else {
4096 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture");
4097 return;
4098 };
4099 let mut prev_bytes = 0usize;
4100 let mut prev_psnr = 0.0f64;
4101 for quality in [20u8, 50, 80] {
4102 let config = EncoderConfig {
4103 width,
4104 height,
4105 base_q_idx: 100,
4106 gop: 8,
4107 colour: Colour::Bt709Limited,
4108 tile_cols_log2: 0,
4109 tile_rows_log2: 0,
4110 };
4111 let mut enc =
4112 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
4113 let mut stream = Vec::new();
4114 let mut total_bytes = 0usize;
4115 for packet in encode_all(&mut enc, &pictures) {
4116 total_bytes += packet.data.len();
4117 stream.extend_from_slice(&packet.data);
4118 }
4119 let decoded = ffmpeg_decode_luma(&stream, width, height);
4120 assert_eq!(
4121 decoded.len(),
4122 pictures.len(),
4123 "quality {quality}: dav1d frame count"
4124 );
4125 let mean_psnr: f64 = decoded
4126 .iter()
4127 .zip(&pictures)
4128 .map(|(d, p)| {
4129 let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect();
4130 psnr(&d16, &p.y)
4131 })
4132 .sum::<f64>()
4133 / decoded.len() as f64;
4134 assert!(
4135 total_bytes >= prev_bytes,
4136 "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}"
4137 );
4138 assert!(
4139 mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours
4140 "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB"
4141 );
4142 prev_bytes = total_bytes;
4143 prev_psnr = mean_psnr;
4144 }
4145 }
4146}