forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiBa7e1d4cTahinli2 months ago3424 commits

encoder.rs6207 lines, 275.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/// `EC_AV1_RL_CENSUS=1` — one stderr line per frame the rate loop steers.
185fn census_on() -> bool {
186 std::env::var("EC_AV1_RL_CENSUS").is_ok_and(|v| v == "1")
187}
188
189/// One level of a run, as the re-plan sees it: how much of the run's weight
190/// it carries, how much of that is still to be coded, and -- once its
191/// effective quantizer has hit the coder's 1..=255 bound -- the leaf-
192/// equivalent bytes it actually spends there.
193#[derive(Debug, Clone, Copy)]
194struct LevelPlan {
195 /// The controller slot this level shares ([`RateLoop::slot`]).
196 slot: usize,
197 /// The level's own `base_q_idx` offset: what tells two hidden levels
198 /// apart inside slot 1.
199 offset: i16,
200 weight: f64,
201 left: f64,
202 bound: bool,
203 rate: f64,
204}
205
206impl LevelPlan {
207 fn new(slot: usize, offset: i16, weight: f64) -> Self {
208 Self {
209 slot,
210 offset,
211 weight,
212 left: weight,
213 bound: false,
214 rate: 0.0,
215 }
216 }
217}
218
219/// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and
220/// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from
221/// the calibration sweep's own log-linear slope (bytes roughly halve every
222/// ~45 `q_idx` steps there, i.e. `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped
223/// per frame. Pure proportional — no accumulated error term — is the windup
224/// bound itself ([[vorbis-rate-loop-windup]]'s class): the only state carried
225/// between frames is `q`, already clamped to `0..=255`, so a quiet lead-in
226/// cannot build a debt a later transient has to repay; each frame's step is
227/// bounded by `STEP_CLAMP` regardless of history.
228///
229/// In pyramid mode the state is kept PER LEVEL: each frame's size is
230/// predicted from the previous frame of its own level, against that level's
231/// own share of the budget, which is the whole "two-pass-free model" this
232/// encoder carries.
233#[derive(Debug, Clone, Copy)]
234struct RateLoop {
235 /// Byte target per level, indexed by [`RateLoop::slot`].
236 target: [f64; 3],
237 /// Quantizer per level, same index.
238 q: [f64; 3],
239 /// Whether the three slots are actually distinct (pyramid mode) or all
240 /// one shared controller (the flat path, unchanged from before levels
241 /// existed).
242 per_level: bool,
243 /// Whether each slot has already steered off a real coded frame. The
244 /// FIRST update of a slot is the seeding one and takes the model's whole
245 /// step ([`RateLoop::update`]); every later one is clamped.
246 seeded: [bool; 3],
247 /// The leaf's own q offset: the zero of the level weight
248 /// ([`WEIGHT_LEVEL_GAIN`]), so slot 1's target can be read in
249 /// LEAF-EQUIVALENT bytes and scaled per frame by that frame's offset.
250 leaf_q_offset: i16,
251 /// The key frame's own leaf-equivalent weight ([`KEY_WEIGHT`]).
252 key_weight: f64,
253 /// The leaf-equivalent weight of a whole run (key included), and the
254 /// run's whole byte budget (`gop` frame targets): what a run RE-PLANS
255 /// from, and what a key frame resets the re-plan to.
256 run_weight: f64,
257 run_bytes: f64,
258 /// What is left of both, ahead of the next frame.
259 left_weight: f64,
260 left_bytes: f64,
261 /// The run's shape, ONE ENTRY PER LEVEL: the key, each distinct hidden
262 /// offset, the leaves. A level whose effective quantizer has hit a bound
263 /// cannot follow the plan, so [`RateLoop::replan`] prices its remaining
264 /// weight at what it MEASURABLY spends and re-solves the run's budget
265 /// over the levels that can still move. Per LEVEL and not per slot: the
266 /// hidden slot mixes the top and mid ARFs, whose leaf-equivalent rates
267 /// differ by 4x at the floor (both code the same bytes at `q_idx` 1, at
268 /// weights that differ by that much), and projecting one onto the other's
269 /// remaining weight drove the whole plan negative.
270 plans: [Option<LevelPlan>; 5],
271 /// The plan's scale at construction — the WINDUP BOUND on the re-plan:
272 /// a level held at its bound hands its unspent bytes to the others, but
273 /// no level's target may exceed this many times its own opening share.
274 scale0: f64,
275 /// `EC_AV1_RL_CENSUS=1`: one line per coded frame on stderr.
276 census: bool,
277 coded: usize,
278}
279
280impl RateLoop {
281 /// The steepest a single frame is allowed to move `base_q_idx`, in
282 /// either direction — chosen so one wildly over/under-sized frame
283 /// (a scene cut, a black lead-in) nudges the next frame's quantizer
284 /// rather than slamming it to an extreme.
285 const STEP_CLAMP: f64 = 12.0;
286 /// The calibration sweep's own slope (see the struct doc), inverted to
287 /// convert a bytes ratio into a `q_idx` step.
288 const GAIN: f64 = 1.0 / 0.0154;
289 /// The windup bound on [`RateLoop::replan`]: however much a bound level
290 /// fails to spend, no other level's target may grow past this multiple of
291 /// its opening share. Without it a run whose hidden levels are all at the
292 /// floor would keep piling the whole run's budget onto the leaves.
293 const REPLAN_CLAMP: f64 = 4.0;
294 /// The same bound the other way: a re-plan may not drive a level's target
295 /// below this multiple of its opening share. A target of zero would STOP
296 /// the loop outright ([`RateLoop::update`] returns on a non-positive
297 /// target), which is how the first cut of this fix froze every level of a
298 /// run at whatever quantizer it had reached.
299 const REPLAN_FLOOR: f64 = 0.25;
300
301 fn new(target_bytes: f64, start_q: f64, pyramid: Option<Pyramid>, gop: usize) -> Self {
302 let Some(p) = pyramid else {
303 return Self {
304 target: [target_bytes; 3],
305 q: [start_q; 3],
306 per_level: false,
307 seeded: [false; 3],
308 leaf_q_offset: 0,
309 key_weight: 1.0,
310 run_weight: 0.0,
311 run_bytes: 0.0,
312 left_weight: 0.0,
313 left_bytes: 0.0,
314 plans: [None; 5],
315 scale0: target_bytes,
316 census: census_on(),
317 coded: 0,
318 };
319 };
320 // THE LEVEL MODEL. Every coded frame of the run is priced by its own
321 // q offset through `WEIGHT_LEVEL_GAIN`, in units of one leaf, and the
322 // run's `gop` frame targets are shared out in those units. The old
323 // model priced a group as "one hidden frame worth `ARF_WEIGHT` = 2
324 // leaves plus `m - 1` leaves", which was wrong twice over and the two
325 // errors cancelled (lane-pyr6): the group has coded TWO hidden frames
326 // since the mid level landed (four with
327 // [`Pyramid::quarter_q_offset`]), and a hidden frame is worth far
328 // more than two leaves -- the census reads the top ARF at 24x a leaf
329 // and the mid at 5x. Both are fixed here, in one diff.
330 let w = |offset: i16| {
331 ((f64::from(p.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp()
332 };
333 let (hidden, leaves) = gop_shape(p, gop);
334 let key = KEY_WEIGHT * w(p.key_q_offset);
335 let total: f64 =
336 key + leaves as f64 + hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum::<f64>();
337 // One leaf's byte target: the run is worth `gop` frame targets and
338 // `total` leaves.
339 let scale = target_bytes * gop.max(1) as f64 / total.max(f64::EPSILON);
340 // THE HIDDEN SLOT holds every hidden level at once (`Level::Arf` is
341 // the top ARF, the mid and the quarters alike -- one controller,
342 // different q offsets), so its target is kept in LEAF-EQUIVALENT
343 // bytes and [`RateLoop::update`] scales it by the coded frame's own
344 // `w(offset)`. Measuring each hidden frame against its OWN predicted
345 // size is what keeps the shared slot from oscillating between the
346 // levels it mixes.
347 // One plan per level, in coding order: key, hidden levels (at most
348 // three distinct offsets -- top, mid, quarters), leaves.
349 let mut plans = [None; 5];
350 plans[0] = Some(LevelPlan::new(0, p.key_q_offset, key));
351 let mut i = 1;
352 for &(o, n) in hidden.iter().take(3) {
353 plans[i] = Some(LevelPlan::new(1, o, n as f64 * w(o)));
354 i += 1;
355 }
356 plans[i] = Some(LevelPlan::new(2, p.leaf_q_offset, leaves as f64));
357 Self {
358 target: [scale * key, scale, scale],
359 q: [start_q; 3],
360 per_level: true,
361 seeded: [false; 3],
362 leaf_q_offset: p.leaf_q_offset,
363 key_weight: key,
364 run_weight: total,
365 run_bytes: target_bytes * gop.max(1) as f64,
366 left_weight: total,
367 left_bytes: target_bytes * gop.max(1) as f64,
368 plans,
369 scale0: scale,
370 census: census_on(),
371 coded: 0,
372 }
373 }
374
375 /// What a frame coded `offset` steps off `base_q_idx` is worth in
376 /// leaf-equivalent bytes ([`WEIGHT_LEVEL_GAIN`]).
377 fn weight(&self, offset: i16) -> f64 {
378 ((f64::from(self.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp()
379 }
380
381 /// Which [`LevelPlan`] a coded frame belongs to. Only the hidden slot
382 /// holds more than one level, so only there does the offset decide.
383 fn plan_of(&self, slot: usize, offset: i16) -> Option<usize> {
384 self.plans
385 .iter()
386 .position(|p| p.is_some_and(|p| p.slot == slot && (slot != 1 || p.offset == offset)))
387 }
388
389 /// Which controller a level uses: one shared slot on the flat path, three
390 /// separate ones under a pyramid.
391 fn slot(&self, level: Level) -> usize {
392 if !self.per_level {
393 return 0;
394 }
395 match level {
396 Level::Key => 0,
397 Level::Arf => 1,
398 // A `show_existing_frame` packet codes no pixels and never
399 // reaches `update`; it shares the leaf slot so `q_idx` is total.
400 Level::Leaf | Level::ShowExisting => 2,
401 }
402 }
403
404 fn q_idx(&self, level: Level) -> u8 {
405 self.q[self.slot(level)].round().clamp(0.0, 255.0) as u8
406 }
407
408 /// Steers this level's `q` toward its own target from the frame's actual
409 /// coded size.
410 ///
411 /// `raw_q` is the quantizer the frame WANTED (`base_q_idx + offset`,
412 /// before the coder's own 1..=255 clamp): outside that range the level is
413 /// at its bound and its share of the budget has to move elsewhere.
414 fn update(&mut self, level: Level, offset: i16, raw_q: i16, actual_bytes: usize) {
415 let slot = self.slot(level);
416 if self.target[slot] <= 0.0 || actual_bytes == 0 {
417 return;
418 }
419 // A hidden frame is measured against ITS OWN level's predicted size:
420 // slot 1's target is in leaf-equivalent bytes.
421 let frame_weight = match slot {
422 0 => self.key_weight,
423 1 => self.weight(offset),
424 _ => 1.0,
425 };
426 let target = match self.per_level && slot == 1 {
427 true => self.target[slot] * frame_weight,
428 false => self.target[slot],
429 };
430 let ratio = actual_bytes as f64 / target;
431 // `STEP_CLAMP` protects an operating point this slot has not found
432 // yet: its `q` is still the caller's `base_q_idx` guess, and the
433 // clamp makes the loop WALK to the right quantizer at twelve steps a
434 // frame. Measured on the 48-frame bitrate gate, the pyramid's ARF
435 // slot spent five of its twelve frames pinned at `-STEP_CLAMP` and
436 // the stream landed -10.2% under target -- convergence lag, not a
437 // steady-state offset (the fixed point of this loop is `actual ==
438 // target` exactly). So a slot's FIRST frame takes the model's whole
439 // step and seeds `q` where the log-linear slope says it belongs; from
440 // the second frame on the clamp is back, and nothing is accumulated
441 // between frames, so [[vorbis-rate-loop-windup]]'s bound still holds.
442 let raw = ratio.ln() * Self::GAIN;
443 let step = if std::mem::replace(&mut self.seeded[slot], true) {
444 raw.clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP)
445 } else {
446 raw
447 };
448 self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0);
449 let bound = !(1..=255).contains(&raw_q);
450 if let Some(plan) = self
451 .plan_of(slot, offset)
452 .and_then(|i| self.plans[i].as_mut())
453 {
454 plan.bound = bound;
455 plan.rate = actual_bytes as f64 / frame_weight.max(f64::EPSILON);
456 }
457 if self.census {
458 eprintln!(
459 "RLCENSUS n={} level={level:?} slot={slot} target={target:.0} actual={actual_bytes} \
460 base_q={:.1} raw_q={raw_q} eff_q={} bound={} left_bytes={:.0} left_w={:.1}",
461 self.coded,
462 self.q[slot],
463 raw_q.clamp(1, 255),
464 bound,
465 self.left_bytes,
466 self.left_weight,
467 );
468 self.coded += 1;
469 }
470 self.replan(level, slot, offset, frame_weight, actual_bytes as f64);
471 }
472
473 /// Re-plans the REST OF THE RUN from what it has actually spent: the
474 /// level model says how the budget SPLITS, and nothing but a measurement
475 /// says what a frame of this content costs at all.
476 ///
477 /// Two frames of a run cannot be steered by the loop and both are pure
478 /// model error without this: the KEY, coded once at the caller's seed `q`
479 /// before anything has been measured (the census's key frames run 0.5x to
480 /// 2.7x the model across the two films), and any level whose `q` has hit
481 /// the floor -- at 3 Mbit/s on the gate's clip the hidden slot codes at
482 /// `q_idx` 1 and physically cannot spend its share, which the leaves must
483 /// then absorb or the stream lands a third under target.
484 ///
485 /// It is NOT an accumulated error term in `q` ([[vorbis-rate-loop-windup]]
486 /// is about exactly that): `q` still moves only by this frame's own
487 /// clamped proportional step, the re-plan only moves the TARGET the next
488 /// frame is measured against, and every key frame resets the whole plan,
489 /// so no debt outlives one run.
490 fn replan(
491 &mut self,
492 level: Level,
493 slot: usize,
494 offset: i16,
495 frame_weight: f64,
496 actual_bytes: f64,
497 ) {
498 if !self.per_level {
499 return;
500 }
501 if level == Level::Key {
502 self.left_weight = self.run_weight;
503 self.left_bytes = self.run_bytes;
504 for plan in self.plans.iter_mut().flatten() {
505 plan.left = plan.weight;
506 }
507 }
508 self.left_weight -= frame_weight;
509 self.left_bytes -= actual_bytes;
510 if let Some(plan) = self
511 .plan_of(slot, offset)
512 .and_then(|i| self.plans[i].as_mut())
513 {
514 plan.left = (plan.left - frame_weight).max(0.0);
515 }
516 // The tail of a run is not re-planned: under a leaf's worth of weight
517 // left, the division is noise.
518 if self.left_weight <= 1.0 {
519 return;
520 }
521 // A BOUND level is held at what it measurably spends and its weight
522 // is taken out of the division, so the bytes it cannot spend land on
523 // the levels that can (and, at the ceiling, the other way round). The
524 // old code divided the whole remainder by the whole remaining weight,
525 // which handed the biggest share of the shortfall straight back to
526 // the level that had just failed to spend it -- at the default
527 // pyramid the hidden levels carry most of the run's weight, so most
528 // of the surplus evaporated there every frame.
529 // ABLATION (`EC_AV1_RL_NOREDIST=1`, this lane's before/after arm):
530 // the old division, whole remainder over whole remaining weight.
531 if std::env::var("EC_AV1_RL_NOREDIST").is_ok_and(|v| v == "1") {
532 let scale = (self.left_bytes / self.left_weight).max(0.0);
533 self.target = [scale * self.key_weight, scale, scale];
534 return;
535 }
536 let (mut bytes, mut weight) = (self.left_bytes, 0.0);
537 for plan in self.plans.iter().flatten() {
538 if plan.bound {
539 bytes -= plan.rate * plan.left;
540 } else {
541 weight += plan.left;
542 }
543 }
544 if weight <= 1.0 {
545 // Every movable level is spent: nothing left to re-solve over.
546 return;
547 }
548 let scale = (bytes / weight).clamp(
549 self.scale0 * Self::REPLAN_FLOOR,
550 self.scale0 * Self::REPLAN_CLAMP,
551 );
552 self.target = [scale * self.key_weight, scale, scale];
553 }
554}
555
556/// What [`Av1Encoder::new`] takes: geometry, rate, key-frame cadence and
557/// colour. `base_q_idx` is picked directly (0..=255, `crate::encode`'s own
558/// unit) rather than a bitrate — a bitrate control loop is not part of this
559/// lane's charter, and a caller that wants one can still derive a
560/// `base_q_idx` from its own target and set that field. A caller who wants
561/// [`RateTarget`]'s quality/size dials instead of picking `base_q_idx`
562/// itself uses [`Av1Encoder::with_rate_target`], which still starts from an
563/// `EncoderConfig` (its `base_q_idx` is the loop's seed/fallback for
564/// [`RateTarget::BytesPerFrame`], and is overwritten outright for the other
565/// two variants).
566#[derive(Debug, Clone, Copy)]
567pub struct EncoderConfig {
568 /// The picture's width in luma samples; must be even and nonzero.
569 pub width: usize,
570 /// The picture's height in luma samples; must be even and nonzero.
571 pub height: usize,
572 /// The quantizer index every frame is coded at (0..=255).
573 pub base_q_idx: u8,
574 /// Pictures between key frames, inclusive of the key frame itself: `1`
575 /// codes every picture as a key frame, `gop` codes picture `gop` (and
576 /// `2*gop`, ...) as a key frame and every other picture inter.
577 pub gop: usize,
578 /// The colour the sequence header signals.
579 pub colour: Colour,
580 /// `TileColsLog2` (spec 5.9.15): the frame is split into `1 <<
581 /// tile_cols_log2` uniformly spaced tile columns, each coded and
582 /// decodable on its own. `0` -- one tile column -- is the default and
583 /// is byte for byte the stream this encoder wrote before tiles existed.
584 pub tile_cols_log2: u32,
585 /// `TileRowsLog2`, the same down the rows.
586 pub tile_rows_log2: u32,
587}
588
589impl EncoderConfig {
590 /// A config at `width`x`height` with one tile, `gop` pictures between
591 /// key frames and no colour signalling -- what every caller that does
592 /// not care about tiles writes, so that adding a field here does not
593 /// rewrite them.
594 #[must_use]
595 pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self {
596 Self {
597 width,
598 height,
599 base_q_idx,
600 gop,
601 colour,
602 tile_cols_log2: 0,
603 tile_rows_log2: 0,
604 }
605 }
606}
607
608/// One coded picture: its OBUs, in the order a demuxer that just wants bytes
609/// on the wire can concatenate them, and the two things a muxer needs to
610/// know without parsing them back out.
611#[derive(Debug, Clone)]
612pub struct Packet {
613 /// A temporal delimiter, a sequence header and the frame OBU for a key
614 /// frame; a temporal delimiter and the frame OBU alone for an inter
615 /// frame (the sequence header is identical across a stream's key
616 /// frames, since only [`EncoderConfig`]'s own fields feed it, so it is
617 /// simplest to let every key frame carry its own copy rather than have
618 /// the facade special-case the first one).
619 pub data: Vec<u8>,
620 /// Whether this picture was coded as a key frame.
621 pub key: bool,
622 /// This picture's position in DISPLAY (presentation) order, starting at
623 /// 0 — a muxer's `pts` in picture units. Without a [`Pyramid`] this is
624 /// also the coding order and equals `dts`.
625 pub order: u64,
626 /// This packet's position in CODING (decode) order, starting at 0 — a
627 /// muxer's `dts` in packet units. With a [`Pyramid`] the hidden frame of
628 /// each mini-GOP is coded before the leaves it precedes in display order,
629 /// so `dts` and `order` diverge, and the `show_existing_frame` packet
630 /// that re-outputs the hidden frame carries the hidden frame's own
631 /// `order` with its own later `dts`.
632 pub dts: u64,
633 /// Which pyramid level this packet is.
634 pub level: Level,
635}
636
637/// One mini-GOP of a two-level coding pyramid, and the quantizer offsets its
638/// two levels are coded at. libaom's `gf_group` shape, cut down to the two
639/// levels this encoder's reference set can carry: the last picture of each
640/// mini-GOP is coded FIRST, hidden (`show_frame == 0`), as the group's
641/// `ALTREF_FRAME`, then the pictures before it are coded as shown leaves that
642/// may predict backward off it, and finally a `show_existing_frame` header
643/// re-outputs the hidden frame in its own display position.
644#[derive(Debug, Clone, Copy, PartialEq, Eq)]
645pub struct Pyramid {
646 /// Pictures per mini-GOP: the hidden frame is `mini_gop` pictures ahead
647 /// of the group's anchor, and `mini_gop - 1` leaves sit between them.
648 /// `1` would leave no leaf at all and is refused. It is the group size a
649 /// long run takes; the last group of a run is up to 1.5x it, since
650 /// [`group_target`] absorbs a tail shorter than half a group rather than
651 /// leaving one behind.
652 pub mini_gop: usize,
653 /// Added to `base_q_idx` for the hidden `ALTREF_FRAME` — negative, since
654 /// every leaf of the group predicts off it.
655 pub arf_q_offset: i16,
656 /// Added to `base_q_idx` for each shown leaf — positive, since nothing
657 /// predicts off a leaf but the next leaf.
658 pub leaf_q_offset: i16,
659 /// THE THIRD LEVEL, or `None` for the two-level pyramid: the offset a
660 /// second hidden frame, at the middle of the mini-GOP, is coded at
661 /// (between [`Pyramid::arf_q_offset`] and [`Pyramid::leaf_q_offset`], so
662 /// the group reads key -> top ARF -> mid ARF -> leaves). The leaves
663 /// before it name it as their `ALTREF_FRAME` and the leaves after it
664 /// start their chain from it, which halves every leaf's distance to its
665 /// nearest good reference. Ignored by a group of fewer than four
666 /// pictures, where there is no leaf on both sides of a midpoint.
667 pub mid_q_offset: Option<i16>,
668 /// THE FOURTH LEVEL, or `None` for the three-level pyramid: the offset
669 /// the two hidden QUARTER-POINT ARFs are coded at (between
670 /// [`Pyramid::mid_q_offset`] and [`Pyramid::leaf_q_offset`], so the group
671 /// reads key -> top ARF -> mid ARF -> quarter ARFs -> leaves). In a group
672 /// of eight they sit at pictures 2 and 6, halving again the distance from
673 /// a leaf to its nearest good reference; every leaf then names the
674 /// nearest hidden frame on each side. Ignored by a group with fewer than
675 /// seven leaves, where a quarter point has no leaf on both sides, and --
676 /// like the mid level -- by a run no longer than one mini-GOP.
677 pub quarter_q_offset: Option<i16>,
678 /// Added to `base_q_idx` for the GOP's KEY FRAME — negative, since every
679 /// frame of the run reads it, directly or through an ARF. The 48-frame
680 /// census (`lanes/census-longgop.md`) found ours coded at base q while
681 /// its own ARFs sat 32 steps finer, where rav1e (key 100 / arf 120 /
682 /// leaf 153) and libaom (63 / 95 / 163) both make the key the best frame
683 /// of the run and spend 22--37% of the stream on it against our 10--11%.
684 pub key_q_offset: i16,
685}
686
687/// How many pictures the mini-GOP now being collected takes, given how many
688/// are left in this run (the pictures before the next key frame) and the
689/// [`Pyramid::mini_gop`] shape.
690///
691/// A fixed `mini_gop` leaves a SHORT TAIL group whenever the run is not a
692/// multiple of it: a 12-picture GOP under `mini_gop` 8 codes 8 + 3, and that
693/// 3-picture tail is the expensive part -- the 12-frame gate preferred one
694/// group of 11 by 7.0 / 20.5 BD points while the 48-frame gate picked 8
695/// (lane-pyr4). The rule here ABSORBS a tail shorter than half a group into
696/// the group before it, so a run takes groups of `mini_gop` until at most
697/// 1.5 x `mini_gop` is left and then one final group of all of it:
698/// remaining 11 under 8 -> 11 (was 8 + 3)
699/// remaining 47 under 8 -> 8, 8, 8, 8, 8, 7 -- what the fixed rule already
700/// coded, so a long GOP is byte-identical
701/// (`the_mini_gop_layout_leaves_no_short_tail`; sweep `lanes/gopad.sweep.txt`).
702///
703/// `EC_AV1_GOP_LAYOUT=fixed` restores the old fixed-size rule for an A/B.
704fn group_target(remaining: usize, mini_gop: usize, absorb_tail: bool) -> usize {
705 match absorb_tail && remaining <= mini_gop + mini_gop / 2 {
706 true => remaining.max(1),
707 false => mini_gop,
708 }
709}
710
711/// How one GOP of `gop` pictures is actually coded, as [`Av1Encoder::encode_frames`]
712/// and [`Av1Encoder::drain_pending`] lay it out: the HIDDEN frames as
713/// `(q offset, count)` (the group's top `ALTREF`, the mid level and the two
714/// quarter-point ARFs, each at its own offset) and the number of shown
715/// leaves. The key frame is the remaining picture and is not listed.
716///
717/// This is what [`RateLoop::new`] prices the run by, so the two must agree on
718/// the gating rules -- a mid level needs three leaves and a run longer than
719/// 1.5 mini-GOPs, quarters need seven leaves and a mid -- which
720/// `the_rate_loop_prices_the_frames_the_pyramid_codes` pins against the real
721/// packet stream.
722fn gop_shape(p: Pyramid, gop: usize) -> (Vec<(i16, usize)>, usize) {
723 let (mut hidden, mut leaves) = (Vec::<(i16, usize)>::new(), 0usize);
724 let mut add = |offset: i16, n: usize| match hidden.iter_mut().find(|(o, _)| *o == offset) {
725 Some((_, c)) => *c += n,
726 None => hidden.push((offset, n)),
727 };
728 let long_run = gop > p.mini_gop + p.mini_gop / 2;
729 let mut left = gop.saturating_sub(1);
730 while left > 0 {
731 let g = group_target(left, p.mini_gop, absorb_tail()).min(left);
732 left -= g;
733 if g == 1 {
734 leaves += 1;
735 continue;
736 }
737 let inner = g - 1;
738 add(p.arf_q_offset, 1);
739 let mid = p.mid_q_offset.filter(|_| inner >= 3 && long_run);
740 let quarters = mid.and(p.quarter_q_offset).filter(|_| inner >= 7);
741 if let Some(o) = mid {
742 add(o, 1);
743 }
744 if let Some(o) = quarters {
745 add(o, 2);
746 }
747 leaves += inner - usize::from(mid.is_some()) - 2 * usize::from(quarters.is_some());
748 }
749 (hidden, leaves)
750}
751
752/// Whether this run absorbs a short tail group (the default) or cuts every
753/// mini-GOP at `mini_gop`: `EC_AV1_GOP_LAYOUT=fixed`, read once.
754fn absorb_tail() -> bool {
755 static ABSORB: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
756 std::env::var("EC_AV1_GOP_LAYOUT").ok().as_deref() != Some("fixed")
757 });
758 *ABSORB
759}
760
761impl Pyramid {
762 /// The pyramid a run asks for through the environment:
763 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>[:<mid>[:<key>]]]`,
764 /// where `<mid>` is the third level's offset or `off` for none, with
765 /// `0` (or anything that is not a mini-GOP of at least 2, e.g. `flat`)
766 /// meaning the flat one-picture-one-frame path. UNSET is
767 /// [`Pyramid::default`]: the pyramid is what
768 /// [`crate::encode::encode_sequence`], the BD gate and `ec-bench` code
769 /// under unless a run turns it off for an A/B.
770 #[must_use]
771 pub fn from_env() -> Option<Self> {
772 let d = Self::default();
773 let Some(spec) = std::env::var("EC_AV1_PYRAMID").ok() else {
774 return Some(d);
775 };
776 let mut f = spec.split(':');
777 let mini_gop: usize = f.next().and_then(|v| v.parse().ok()).unwrap_or(0);
778 if mini_gop < 2 {
779 return None;
780 }
781 Some(Self {
782 mini_gop,
783 arf_q_offset: f
784 .next()
785 .and_then(|v| v.parse().ok())
786 .unwrap_or(d.arf_q_offset),
787 leaf_q_offset: f
788 .next()
789 .and_then(|v| v.parse().ok())
790 .unwrap_or(d.leaf_q_offset),
791 // A fourth field is the mid-level offset; the literal `off` asks
792 // for the two-level pyramid at the same shape (the A/B arm the
793 // sweep needs), and no field at all keeps the default's.
794 mid_q_offset: match f.next() {
795 None => d.mid_q_offset,
796 Some("off") => None,
797 Some(v) => v.parse().ok().or(d.mid_q_offset),
798 },
799 // A fifth field is the key frame's own offset.
800 key_q_offset: f
801 .next()
802 .and_then(|v| v.parse().ok())
803 .unwrap_or(d.key_q_offset),
804 // A sixth field is the quarter level's offset, `off` for none.
805 quarter_q_offset: match f.next() {
806 None => d.quarter_q_offset,
807 Some("off") => None,
808 Some(v) => v.parse().ok().or(d.quarter_q_offset),
809 },
810 })
811 }
812}
813
814impl Default for Pyramid {
815 /// The best point of the offset sweep run through the BD gate's own
816 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` knob
817 /// (`encode::tests::bd_rate_vs_libaom_and_rav1e`, 12 frames of each of
818 /// the three gate clips, BD-rate vs libaom / vs rav1e, wall = the four
819 /// encodes of the ladder together).
820 ///
821 /// First sweep, before the motion-search lane merged (its extra-reference
822 /// `NEWMV` is exactly what a pyramid leaf needs to reach its hidden
823 /// frame), so read it for the OFFSETS, not for the verdict:
824 ///
825 /// | mini_gop:arf:leaf | 1080p | 2160p | screen |
826 /// |---|---|---|---|
827 /// | flat (no pyramid) | +122.7 / +73.4 | +147.3 / +98.5 | +79.4 / +17.2 |
828 /// | 4:0:0 | +152.2 / +97.9 | +214.7 / +158.1 | +91.4 / +26.2 |
829 /// | 4:-16:8 | +139.9 / +87.1 | +201.5 / +143.7 | +78.5 / +19.5 |
830 /// | 4:-24:12 | +141.3 / +85.0 | +190.0 / +132.9 | +84.5 / +22.8 |
831 /// | 2:0:0 | +149.3 / +93.1 | +203.0 / +149.4 | +88.3 / +23.6 |
832 /// | 2:-8:4 | +143.1 / +89.1 | +196.2 / +141.6 | +82.5 / +20.4 |
833 /// | 2:-16:8 | +137.6 / +84.5 | +187.2 / +130.6 | +84.9 / +23.1 |
834 ///
835 /// `0:0` is the worst row at both mini-GOP sizes and `-16/+8` buys 12-16
836 /// BD points over it, in the direction libaom's `gf_group` spends them
837 /// (lowest quantizer on the frame everything else predicts from). Those
838 /// are these defaults.
839 ///
840 /// Re-measured after that lane merged (wall ours, 1080p/2160p/screen):
841 ///
842 /// | arm | 1080p | 2160p | screen | wall |
843 /// |---|---|---|---|---|
844 /// | flat (no pyramid) | +121.1 / +71.8 | +146.1 / +97.5 | +79.3 / +17.2 | 6.3 / 5.8 / 6.2 s |
845 /// | 4:-16:8 | +131.9 / +81.1 | +178.7 / +123.6 | +78.4 / +19.5 | 6.2 / 5.6 / 5.5 s |
846 /// | 2:-16:8 | +125.4 / +76.2 | +173.0 / +119.5 | +84.9 / +23.1 | 6.2 / 5.6 / 6.2 s |
847 ///
848 /// So the pyramid still does NOT pay, and ships OFF: it wins 0.9 points
849 /// on screen capture at `4:-16:8` and loses 11 on 1080p and 33 on 2160p.
850 /// What keeps it from paying, in the order the numbers point at it:
851 ///
852 /// * The hidden frame predicts `mini_gop` pictures ahead of its own
853 /// reference with the SAME forward search a neighbouring frame gets,
854 /// and it is the largest frame in the group (73.8 kB of the 1080p
855 /// ladder's 184 kB at `4:-16:8`). On the 2160p clip, whose motion the
856 /// search only just reaches at distance 1, distance 4 is where it
857 /// falls off — that clip loses twice what 1080p does, and shrinking
858 /// the mini-GOP to 2 recovers most of the gap (+178.7 -> +173.0,
859 /// +131.9 -> +125.4). A distance-scaled search range is the fix, and
860 /// it lives in the motion-search lane, not here.
861 /// * The leaves reach the hidden frame through the extra-reference
862 /// modes only: `ALTREF_FRAME` wins about 13% of blocks
863 /// (`encode::take_ref_frame_hits`, printed by the round-trip test),
864 /// up from 4% before the motion lane merged. A compound
865 /// (`LAST` + `ALTREF`) prediction mode is the other half of what a
866 /// real B frame buys, and this crate codes no compound blocks at all.
867 ///
868 /// Neither is a defect in the pyramid itself: the reordering is exact
869 /// (`encoder::tests::a_pyramid_stream_decodes_in_display_order_through_both_decoders`
870 /// checks every shown frame in display order against ffmpeg AND our own
871 /// decoder, with the hidden frame proven to win blocks), and the
872 /// Re-measured a third time at NATIVE resolution (`encode::tests::
873 /// bd_rate_screen_native`, 1920x1024 crops, 12 frames, four quantizers,
874 /// BD-rate vs libaom / vs rav1e), because every earlier verdict was taken
875 /// on the 4x-downscaled gate (class `gate-recipe-confound`) and because
876 /// leaf compound and the distance-scaled search have landed since:
877 ///
878 /// | arm | film 1080p | film 2160p | screen |
879 /// |---|---|---|---|
880 /// | flat (no pyramid) | +18.7 / +1.4 | +48.1 / +19.8 | +59.4 / -10.0 |
881 /// | 4:-16:8 | +23.2 / +5.3 | +48.1 / +19.7 | +62.7 / -6.5 |
882 /// | 2:-16:8 | +24.9 / +6.9 | +46.9 / +19.5 | +69.0 / -3.8 |
883 /// | 8:-16:8 | +22.6 / +4.6 | +48.7 / +19.8 | +59.3 / -8.2 |
884 /// | 4:-24:12 (before the leaf-compound merge) | +24.3 / +6.3 | +48.5 / +20.2 | +67.2 / -3.7 |
885 ///
886 /// The confound was real -- at native the gap is 5 BD points, not 30 --
887 /// but the sign is not: no arm beats flat on both films, every arm costs
888 /// 4-6 points on 1080p, and the best 2160p arm (`2:-16:8`, -1.1 vs
889 /// libaom) pays +10 on screen. So the pyramid still ships OFF.
890 ///
891 /// A native offset sweep on the 2160p clip alone (mini-GOP 4) says the
892 /// offsets are not what is missing -- the whole 3x3 grid spans 2.9 BD
893 /// points and none of it reaches flat's +48.1:
894 ///
895 /// | arf \ leaf | +4 | +8 | +12 |
896 /// |---|---|---|---|
897 /// | -8 | +48.9 / +20.4 | +49.2 / +20.1 | +50.2 / +20.5 |
898 /// | -16 | +47.8 / +20.0 | +48.1 / +19.7 | +49.2 / +20.2 |
899 /// | -24 | +47.3 / +20.0 | +47.6 / +19.7 | +48.5 / +20.2 |
900 ///
901 /// The gradient is monotone in both knobs (deeper ARF better, shallower
902 /// leaf better), which is the shape of a group whose leaves cannot cash
903 /// in the ARF's extra quality: what the leaves reach the hidden frame
904 /// with is still one forward search per reference. Shrinking the mini-GOP
905 /// helps for the same reason (2:-16:8 is the only arm that beats flat on
906 /// any clip, and it beats it on the clip with the fastest motion).
907 ///
908 /// RE-SWEPT on lane-av1pyrgate, once the content gate below existed and
909 /// on the current defaults (`LAMBDA_SCALE` 0.0275, the 32x32 tx-depth
910 /// search and compound var-tx on): the earlier verdicts were taken with
911 /// the screen capture inside the arm, and it is the one clip a pyramid
912 /// never helps. With the gate, the screen row is the flat row by
913 /// construction, so the sweep is decided on the two real films
914 /// (`encode::tests::bd_rate_screen_native`, BD-rate vs libaom / vs
915 /// rav1e; bars are fixtures, recorded only):
916 ///
917 /// | arm | film A | film B | screen | bars 1080p | bars 2160p |
918 /// |---|---|---|---|---|---|
919 /// | flat (no pyramid) | +62.8 / +32.5 | +86.3 / +50.5 | +50.1 / -15.4 | +16.4 / -1.1 | +48.2 / +20.4 |
920 /// | 2:-16:8 | +60.3 / +29.1 | +83.6 / +50.2 | +50.1 / -15.4 | +24.0 / +5.9 | +47.2 / +20.2 |
921 /// | **4:-16:8** | **+54.1 / +24.2** | **+82.6 / +47.4** | +50.1 / -15.4 | +21.5 / +3.7 | +48.3 / +20.4 |
922 /// | 8:-16:8 | +55.9 / +25.8 | +83.6 / +47.3 | +50.1 / -15.4 | +19.8 / +2.0 | +48.7 / +20.4 |
923 /// | 4:-24:12 | +51.5 / +22.3 | +84.9 / +50.3 | +50.1 / -15.4 | +21.9 / +4.0 | +48.4 / +20.7 |
924 /// | 4:-12:6 | +57.6 / +27.1 | +84.8 / +49.3 | +50.1 / -15.4 | +21.7 / +3.9 | +48.8 / +20.9 |
925 ///
926 /// `4:-16:8` is the only arm that improves BOTH films on BOTH columns by
927 /// several points (-8.7 / -8.3 on film A, -3.7 / -3.1 on film B) and it
928 /// stays these defaults. `4:-24:12` buys another 2.6 on film A and gives
929 /// 2.3 back on film B (where it barely beats flat vs rav1e, -0.2), which
930 /// is the same "leaves cannot cash in the ARF's quality" shape as before,
931 /// now content-dependent rather than uniform. The screen column is
932 /// IDENTICAL in every arm -- that is the content gate, measured, not
933 /// asserted. `EC_AV1_LAMBDA=0.035` on top of `4:-16:8` was re-judged once
934 /// (the pyramid changes the reference structure): +54.5 / +24.5 and
935 /// +85.2 / +49.4, worse on both films, so 0.0275 stands.
936 ///
937 /// SHIPPED AS THE DEFAULT on lane-av1pyrdef. `4:-16:8` is what
938 /// [`crate::encode::encode_sequence`] (through
939 /// [`Av1Encoder::encode_sequence_pyramid`], the one mini-GOP driver both
940 /// paths run), the BD gates and `ec-bench` code a non-screen stream
941 /// under; a screen stream still codes flat, decided once per stream by
942 /// the content gate in [`Av1Encoder::encode_frames`]. `EC_AV1_PYRAMID=0`
943 /// restores the flat path everywhere for an A/B, and
944 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf>:<leaf>]` another shape of it
945 /// ([`Pyramid::from_env`]).
946 ///
947 /// [`Av1Encoder::new`] is unchanged: the one-picture-one-packet facade
948 /// entry point still codes flat, since a picture no longer maps to a
949 /// packet under a pyramid — [`Av1Encoder::with_pyramid`] plus
950 /// [`Av1Encoder::encode_frames`] is the streaming surface that reorders.
951 /// RE-SWEPT on lane-pyr3, on main 503d7aa9 -- `4:-16:8` was chosen when
952 /// the gate's "film" rows were still colour bars, and CfL, the luma
953 /// angle deltas, filter intra, the propagating tpl map and the rate-loop
954 /// step have all landed since (class `unswept decision constants`). The
955 /// axes were swept in the order mini-GOP first at the shipped offsets,
956 /// then both offset axes at the best mini-GOP, then the joint corners
957 /// (`encode::tests::bd_rate_screen_native`, BD-rate vs libaom / vs
958 /// rav1e; the bars rows move by at most 4 points across the WHOLE sweep
959 /// and decide nothing, the screen row is byte-identical in every arm
960 /// because the content gate codes it flat):
961 ///
962 /// | arm | film A | film B |
963 /// |---|---|---|
964 /// | flat (no pyramid) | +61.4 / +31.3 | +85.3 / +49.7 |
965 /// | 2:-16:8 | +59.2 / +28.1 | +82.3 / +49.1 |
966 /// | 4:-16:8 (was shipped) | +52.8 / +23.3 | +81.0 / +46.1 |
967 /// | 8:-16:8 | +54.3 / +24.4 | +81.8 / +45.8 |
968 /// | 16:-16:8 | +50.8 / +21.4 | +73.8 / +38.7 |
969 /// | 8:-8:8 | +58.0 / +27.5 | +83.3 / +46.5 |
970 /// | 8:-24:8 | +52.7 / +23.4 | +83.7 / +48.4 |
971 /// | 8:-32:8 | +52.3 / +23.1 | +86.8 / +51.9 |
972 /// | 8:-16:0 | +60.7 / +30.7 | +85.3 / +51.2 |
973 /// | 8:-16:4 | +57.6 / +27.4 | +84.1 / +48.6 |
974 /// | 8:-16:12 | +51.8 / +22.2 | +80.4 / +43.9 |
975 /// | 8:-16:16 | +50.1 / +20.5 | +80.6 / +43.4 |
976 /// | 16:-24:8 | +47.8 / +19.0 | +71.5 / +37.4 |
977 /// | 16:-16:12 | +48.0 / +18.9 | +71.1 / +35.7 |
978 /// | 16:-16:16 | +45.9 / +17.0 | +69.3 / +34.0 |
979 /// | 16:-24:12 | +45.6 / +17.0 | +70.2 / +35.6 |
980 /// | **16:-24:16** | **+44.2 / +15.7** | **+70.5 / +35.2** |
981 /// | 16:-32:16 | +43.6 / +15.2 | +71.2 / +36.2 |
982 /// | 16:-24:20 (past the swept range) | +42.9 / +14.5 | +70.8 / +34.9 |
983 /// | 16:-24:24 (past the swept range) | +42.6 / +14.1 | +71.3 / +35.7 |
984 ///
985 /// `16:-24:16` ships: it takes 8.6 / 7.6 points off film A and 10.5 /
986 /// 10.9 off film B against the old defaults, and every axis through it
987 /// is at or next to its own minimum. The two arms past the swept leaf
988 /// range were run because leaf `+16` was the range's edge and still
989 /// improving (class `instrument at bound`): film A keeps falling to
990 /// `+24` but film B turns back up at `+20`, so `+16` is where BOTH films
991 /// are minimal and the bound is not the answer. Deeper ARF is the same
992 /// shape -- `-32` buys 0.6 on film A and gives 0.7 back on film B.
993 ///
994 /// WHAT THAT SWEEP COULD NOT SAY, and the LONG-GOP sweep that answers it
995 /// (lane-pyr4, `lanes/pyr4.sweep.txt`). The table above is measured
996 /// against a gate that codes 12 frames with `gop = 12`, and a group is
997 /// cut at every key frame (`encode_frames`), so `16` there is really
998 /// "one hidden ARF per GOP" and ANY mini-GOP over 12 codes the same
999 /// stream (class `instrument at bound`). The user's exports are long
1000 /// GOPs, so the shape is decided on
1001 /// [`crate::encode::tests::bd_rate_film_long_gop`] -- 48 pictures, `gop
1002 /// = 48`, the two real films, four quantizers, vs libaom `cpu-used 6`
1003 /// and rav1e `speed=6` at the same key interval:
1004 ///
1005 /// | mini_gop:arf:leaf | film A vs libaom / rav1e | film B vs libaom / rav1e |
1006 /// |---|---|---|
1007 /// | 32:-24:16 | +79.0 / +29.8 | +164.4 / +58.8 |
1008 /// | 16:-24:16 (was the default) | +67.4 / +21.0 | +165.5 / +57.6 |
1009 /// | 8:-16:16 | +63.7 / +19.0 | +167.6 / +58.6 |
1010 /// | 4:-24:16 | +61.9 / +19.5 | +160.8 / +56.7 |
1011 /// | 8:-24:16 | +58.5 / +15.5 | +166.1 / +56.8 |
1012 /// | 8:-24:12 | +60.2 / +17.3 | +166.8 / +58.0 |
1013 /// | 8:-24:20 | +57.1 / +14.0 | +166.2 / +56.6 |
1014 /// | 8:-40:16 | +56.1 / +13.3 | +167.6 / +57.3 |
1015 /// | 8:-32:12 | +56.5 / +14.7 | +163.0 / +56.3 |
1016 /// | 8:-32:20 | +55.4 / +12.9 | +167.9 / +57.4 |
1017 /// | **8:-32:16** | **+55.7 / +13.5** | **+165.1 / +56.6** |
1018 ///
1019 /// `8:-32:16` ships: against the old `16:-24:16` it takes 11.7 / 7.5
1020 /// points off film A and 0.4 / 1.0 off film B -- all four columns down.
1021 /// A real 16- or 32-picture group is WORSE than an 8-picture one on film
1022 /// A once the GOP is long enough for the distinction to exist, which the
1023 /// 12-frame gate could not see; `4` was probed below the swept edge and
1024 /// turns back up on film A. ARF `-32` is an interior optimum (`-40`
1025 /// turns back on both films). The leaf axis has content-opposite optima
1026 /// (film A wants `20`, film B wants `12`, within 1.1 and 4.9 points) so
1027 /// `16` stays, being the only value down on all four columns.
1028 ///
1029 /// THE PRICE THAT WAS, and how it was paid (lane-gopad): on the
1030 /// SHORT-GOP gate (12 frames, `gop = 12`) a fixed mini-GOP of 8 split the
1031 /// run into 8 + 3 and read film A +51.2 / +21.4, film B +91.0 / +53.5,
1032 /// against `16:-24:16`'s +44.2 / +15.7 and +70.5 / +35.2 -- the tail
1033 /// group, not the shape, was the cost. [`group_target`] now absorbs a
1034 /// short tail, so the same 12 pictures code as ONE group of 11 and read
1035 /// film A +43.9 / +15.6 and film B +68.4 / +38.2 (three of the four
1036 /// columns better than `16:-24:16` ever was, film B vs rav1e 3.0 short),
1037 /// while 47 inter pictures still take 8 x 5 + 7 -- the long-GOP table
1038 /// above is coded byte for byte as it was measured.
1039 /// THE THIRD LEVEL (lane-pyr5, `lanes/pyr5.sweep.txt`), swept on the
1040 /// long-GOP gate against a control arm on this very head:
1041 ///
1042 /// | mini_gop:arf:leaf:mid | film A vs libaom / rav1e | film B vs libaom / rav1e |
1043 /// |---|---|---|
1044 /// | 8:-32:16 (control, 2-level) | +55.2 / +12.8 | +151.3 / +47.4 |
1045 /// | 8:-32:16:-4 | +51.8 / +11.4 | +146.2 / +45.4 |
1046 /// | **8:-32:16:-8** | **+52.1 / +11.7** | **+145.3 / +45.0** |
1047 /// | 8:-32:16:-16 | +53.4 / +13.0 | +146.0 / +46.1 |
1048 /// | 8:-32:20:-8 | +52.4 / +11.5 | +148.0 / +46.1 |
1049 /// | 16:-32:16:-8 | +55.0 / +12.3 | +146.0 / +44.3 |
1050 /// | 16:-32:16:-16 | +54.6 / +12.1 | +148.7 / +46.0 |
1051 /// | 4:-32:16:-8 | +61.7 / +20.4 | +147.5 / +51.3 |
1052 ///
1053 /// `-4` and `-8` are within a point of each other and split the two
1054 /// films; `-8` ships because film B is the wider gap. A mini-GOP of 4
1055 /// with a mid level -- rav1e's own shape at speed 6 -- is far worse here,
1056 /// so the third level is worth more than a shorter group, and the census
1057 /// (`lanes/census-longgop.md`) says why: at 8 pictures our leaves are
1058 /// already cheap and the bytes sit in the ARFs.
1059 ///
1060 /// The 12-frame gate keeps its numbers exactly (+43.9 / +15.6 and +68.4 /
1061 /// +38.2, byte-identical streams): a GOP that is one single mini-GOP does
1062 /// not code the third level at all (see `drain_pending`).
1063 /// THE LEAF OFFSET, RE-SWEPT ONCE THE ANCHORS MOVED (lane-arfq,
1064 /// `lanes/arfq.sweep.txt`). The table above chose `16` when the key frame
1065 /// still sat at the base quantizer; with [`Pyramid::key_q_offset`] at
1066 /// `-48` the whole run predicts off a much finer anchor and the leaves
1067 /// want to be finer with it. Long-GOP gate, control arm on the same head:
1068 ///
1069 /// | mini_gop:arf:leaf:mid:key | film A vs libaom / rav1e | film B vs libaom / rav1e |
1070 /// |---|---|---|
1071 /// | 8:-32:8:-8:-48 | +43.4 / +5.1 | +127.6 / +34.1 |
1072 /// | **8:-32:12:-8:-48** | **+43.1 / +4.6** | **+129.0 / +34.3** |
1073 /// | 8:-32:16:-8:-48 (control) | +43.5 / +4.6 | +131.3 / +35.0 |
1074 /// | 8:-32:24:-8:-48 | +45.6 / +5.6 | +138.8 / +38.4 |
1075 /// | 8:-32:12:-12:-48 | +43.4 / +5.0 | +128.1 / +33.8 |
1076 /// | 8:-32:12:-16:-48 | +44.0 / +5.6 | +127.7 / +34.1 |
1077 /// | 8:-24:12:-8:-48 | +44.5 / +5.2 | +128.6 / +33.3 |
1078 /// | 16:-32:12:-8:-48 | +47.2 / +6.3 | +134.7 / +35.6 |
1079 ///
1080 /// `12` ships: film B 2.3 / 0.7 down, film A 0.4 down against libaom and
1081 /// flat against rav1e. `8` is past the optimum (it buys film B and gives
1082 /// film A back), `24` is worse on all four. The other two axes were
1083 /// re-swept at `12` and did not move: a deeper mid (`-12`, `-16`) and a
1084 /// shallower ARF (`-24`) both trade film A away for film B, so the top
1085 /// ARF keeps its `-32` and the mid its `-8`. A 16-picture mini-GOP is
1086 /// worse on all four -- the pyramid has exactly three levels, so one mid
1087 /// frame cannot carry fifteen leaves.
1088 ///
1089 /// Unlike the third level this is NOT gated on GOP length: the 12-frame
1090 /// gate improves on every row too (film A +38.5 / +8.2 -> +37.5 / +7.6,
1091 /// film B +58.2 / +26.5 -> +54.1 / +23.9, both bars rows down, the screen
1092 /// capture byte-identical).
1093 fn default() -> Self {
1094 Self {
1095 mini_gop: 8,
1096 arf_q_offset: -32,
1097 leaf_q_offset: 12,
1098 mid_q_offset: MID_DEFAULT,
1099 key_q_offset: KEY_DEFAULT,
1100 quarter_q_offset: QUARTER_DEFAULT,
1101 }
1102 }
1103}
1104
1105/// Which level of the pyramid a coded frame sits at, reported on every
1106/// [`Packet`] so a caller (and the BD gate's histogram) can tell them apart
1107/// without parsing the frame headers back out.
1108#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1109pub enum Level {
1110 /// A key frame.
1111 Key,
1112 /// A hidden `ALTREF_FRAME`, coded ahead of its display position.
1113 Arf,
1114 /// A shown leaf.
1115 Leaf,
1116 /// A `show_existing_frame` header re-outputting a hidden frame: no coded
1117 /// pixels at all, four bits of header.
1118 ShowExisting,
1119}
1120
1121/// The DPB slot the group anchors alternate between (see
1122/// [`Av1Encoder::encode_frames`]): the hidden frame of group `g` refreshes
1123/// `ANCHOR_SLOTS[(g + 1) % 2]`, which is the slot the leaves of group `g`
1124/// name as `ALTREF_FRAME` and which group `g + 1` reads as its own anchor.
1125/// Two slots alternate because a group's leaves must still be able to read
1126/// the previous anchor while the new one is already written.
1127const ANCHOR_SLOTS: [u8; 2] = [3, 4];
1128
1129/// The slot the leaf chain refreshes and reads as `LAST_FRAME`.
1130const LEAF_SLOT: u8 = 0;
1131
1132/// lane-last2: the two slots the leaf chain alternates its refresh between
1133/// once [`last2`] is on, so that the shown frame BEFORE `LAST_FRAME` is still
1134/// in the DPB and can be named `LAST2_FRAME`. Slot 7 is the one the key frame
1135/// writes and nothing has ever read back, so this costs no other level a slot;
1136/// leaf `k` refreshes `LEAF_SLOTS[k % 2]`, which is the slot leaf `k - 2`
1137/// wrote -- read before write, spec 7.20's decode order.
1138const LEAF_SLOTS: [u8; 2] = [LEAF_SLOT, 7];
1139
1140/// Whether the leaf chain retains that second past picture and offers it to
1141/// the block search as `LAST2_FRAME` (`EC_AV1_LAST2=0` / `=1`). The census
1142/// that priced the lever is `lanes/refs.report.md` §1; what it buys on the
1143/// gate is `lanes/last2.report.md`.
1144fn last2() -> bool {
1145 match LAST2_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
1146 0 => return false,
1147 1 => return true,
1148 _ => {}
1149 }
1150 match std::env::var("EC_AV1_LAST2").ok() {
1151 Some(v) => v != "0",
1152 None => LAST2,
1153 }
1154}
1155
1156/// A PROCESS-GLOBAL [`last2`] override that wins over the environment
1157/// (`u8::MAX` = unset), the shape `crate::encode::set_frame_interp` has --
1158/// this crate's tests never call `set_var` (`crate::envflags`), so the
1159/// witness turns the lever on through this while holding
1160/// [`crate::speed::knob_write`].
1161static LAST2_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
1162
1163/// Sets [`LAST2_OVERRIDE`]; `None` clears it.
1164#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
1165pub(crate) fn set_last2(on: Option<bool>) {
1166 LAST2_OVERRIDE.store(
1167 on.map_or(u8::MAX, u8::from),
1168 std::sync::atomic::Ordering::Relaxed,
1169 );
1170}
1171
1172/// [`last2`]'s default.
1173const LAST2: bool = false;
1174
1175/// The slot the mid-level hidden frame of a three-level group refreshes
1176/// ([`Pyramid::mid_q_offset`]): free of the two anchors (3, 4), of the leaf
1177/// chain (0) and of `GOLDEN_SLOT` (1), so all four levels are live at once.
1178const MID_SLOT: u8 = 2;
1179
1180/// The two slots the QUARTER-POINT hidden frames refresh
1181/// ([`Pyramid::quarter_q_offset`]). THE WHOLE SLOT MAP, with all four levels
1182/// live at once:
1183///
1184/// | slot | holds | written by | read as |
1185/// |---|---|---|---|
1186/// | 0 (`LEAF_SLOT`) | the previous shown leaf | every leaf | `LAST_FRAME` of the next leaf |
1187/// | 1 (`GOLDEN_SLOT`) | the key frame | the key | `GOLDEN_FRAME` everywhere |
1188/// | 2 (`MID_SLOT`) | the mid ARF | the mid ARF | `LAST_FRAME` / `ALTREF_FRAME` of the leaves and quarters around it |
1189/// | 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` |
1190/// | 5, 6 (`QUARTER_SLOTS`) | the first and second quarter ARF | the quarter ARFs | `LAST_FRAME` / `ALTREF_FRAME` of the leaves beside them |
1191/// | 7 | unused (the key's copy is never read back) | the key | -- |
1192///
1193/// A frame names exactly two of them plus `GOLDEN_SLOT`
1194/// ([`Av1Encoder::encode_pyramid_inter`] fills all seven `ref_frame_idx`
1195/// entries from `last_slot`/`altref_slot`), and `refresh_frame_flags` is the
1196/// single `self_slot` bit, so no level ever overwrites a slot another level
1197/// is still reading.
1198const QUARTER_SLOTS: [u8; 2] = [5, 6];
1199
1200/// [`Pyramid::default`]'s fourth level (`None` = the three-level pyramid).
1201/// The long-GOP sweep's winner (`lanes/pyr6.sweep.txt`).
1202const QUARTER_DEFAULT: Option<i16> = None;
1203
1204/// [`Pyramid::default`]'s third level (`None` = the two-level pyramid), the
1205/// long-GOP sweep's winner (`lanes/pyr5.sweep.txt`): every one of the four
1206/// long-GOP columns improves against the two-level shape, film B (the wider
1207/// gap) by 6.0 / 2.4 BD points.
1208const MID_DEFAULT: Option<i16> = Some(-8);
1209
1210/// [`Pyramid::default`]'s key-frame offset: the long-GOP sweep's winner
1211/// (`lanes/keyq.sweep.txt`, 48 pictures, gop 48, BD-rate vs libaom cpu-used 6
1212/// / vs rav1e speed 6), which the 12-frame gate agrees with, so it is NOT
1213/// gated on GOP length the way the third level is:
1214///
1215/// | key offset | film A (48) | film B (48) | film A (12) | film B (12) |
1216/// |---|---|---|---|---|
1217/// | 0 (base q) | +52.0 / +11.7 | +144.5 / +44.3 | +43.3 / +15.0 | +66.9 / +35.1 |
1218/// | -16 | +48.8 / +9.4 | +138.0 / +40.2 | | |
1219/// | -32 | +45.3 / +6.7 | +132.8 / +36.8 | | |
1220/// | -48 | +43.5 / +4.6 | +131.3 / +35.0 | +38.5 / +8.2 | +58.2 / +26.5 |
1221/// | -64 | +44.9 / +3.8 | +140.7 / +37.5 | | |
1222///
1223/// `-64` overshoots on film B, and a deeper ARF (`-40`) under the same key
1224/// gives bytes back on both films (+44.4 / +5.1, +137.4 / +38.6), so what the
1225/// group was short of is the ANCHOR, not more ARF. The bars rows move by
1226/// 0.3 / 0.6 BD points and the screen capture is byte-identical (its pyramid
1227/// is gated off).
1228const KEY_DEFAULT: i16 = -48;
1229
1230/// Whether the pyramid path hands each frame a lookahead window, i.e.
1231/// whether the temporal lambda map (`encode::tpl_lambda_factors`) runs on
1232/// the DEFAULT stream at all. It did not until lane-arfcen: the pyramid
1233/// reorders pictures, so this path passed `&[]` and the map -- measured and
1234/// shipped on the flat path -- was inert on every frame of every pyramid
1235/// stream, including the ARFs that carry 54% of a long-GOP stream's bytes
1236/// (class `tool disabled in every gate recipe`).
1237/// lane-arfpred: the top ARF source temporal filter's strength
1238/// ([`crate::speed::ARF_TF`]), `EC_AV1_ARF_TF=<strength>` overriding it;
1239/// `0` is off.
1240fn arf_tf_strength() -> f64 {
1241 std::env::var("EC_AV1_ARF_TF")
1242 .ok()
1243 .and_then(|v| v.parse().ok())
1244 .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF))
1245}
1246
1247/// lane-arftf: the same filter's strength on the MID ARF, whose own window
1248/// is the display-FUTURE leaves of its group (`tpl_window(at, false)`).
1249/// `EC_AV1_ARF_TF_MID=<strength>` overrides [`crate::speed::ARF_TF_MID`];
1250/// `0` is off.
1251fn arf_tf_mid_strength() -> f64 {
1252 std::env::var("EC_AV1_ARF_TF_MID")
1253 .ok()
1254 .and_then(|v| v.parse().ok())
1255 .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_MID))
1256}
1257
1258/// lane-arftf: how many of the window's pictures the filter averages in
1259/// ([`crate::speed::ARF_TF_WIN`], `EC_AV1_ARF_TF_WIN=<n>`). The top ARF's
1260/// window holds only DISPLAY-PAST neighbours -- it is the group's last
1261/// picture and the next group's sources are not buffered when it is coded --
1262/// so this widens the filter backwards only.
1263pub(crate) fn arf_tf_window() -> usize {
1264 std::env::var("EC_AV1_ARF_TF_WIN")
1265 .ok()
1266 .and_then(|v| v.parse().ok())
1267 .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_WIN))
1268}
1269
1270/// lane-lookahead: how many DISPLAY-FUTURE neighbours the top ARF's filter
1271/// takes out of the buffered next group ([`crate::speed::ARF_TF_WIN_FUT`],
1272/// `EC_AV1_ARF_TF_WIN_FUT=<n>`). Inert without [`lookahead`].
1273pub(crate) fn arf_tf_window_future() -> usize {
1274 match ARF_TF_FUT_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
1275 usize::MAX => {}
1276 n => return n,
1277 }
1278 std::env::var("EC_AV1_ARF_TF_WIN_FUT")
1279 .ok()
1280 .and_then(|v| v.parse().ok())
1281 .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_WIN_FUT))
1282}
1283
1284/// PROCESS-GLOBAL overrides of the two lane-lookahead knobs, the shape
1285/// [`set_last2`] has (this crate's tests never call `set_var`); `u8::MAX` /
1286/// `usize::MAX` is unset, and a witness holds [`crate::speed::knob_write`]
1287/// while it uses them.
1288static LOOKAHEAD_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
1289static ARF_TF_FUT_OVERRIDE: std::sync::atomic::AtomicUsize =
1290 std::sync::atomic::AtomicUsize::new(usize::MAX);
1291static TPL_FUT_OVERRIDE: std::sync::atomic::AtomicUsize =
1292 std::sync::atomic::AtomicUsize::new(usize::MAX);
1293
1294/// Sets [`LOOKAHEAD_OVERRIDE`]; `None` clears it.
1295#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
1296pub(crate) fn set_lookahead(on: Option<bool>) {
1297 LOOKAHEAD_OVERRIDE.store(
1298 on.map_or(u8::MAX, u8::from),
1299 std::sync::atomic::Ordering::Relaxed,
1300 );
1301}
1302
1303/// Sets [`ARF_TF_FUT_OVERRIDE`]; `None` clears it.
1304#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
1305pub(crate) fn set_arf_tf_future(n: Option<usize>) {
1306 ARF_TF_FUT_OVERRIDE.store(
1307 n.unwrap_or(usize::MAX),
1308 std::sync::atomic::Ordering::Relaxed,
1309 );
1310}
1311
1312/// Sets [`TPL_FUT_OVERRIDE`]; `None` clears it.
1313#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
1314pub(crate) fn set_tpl_fut(n: Option<usize>) {
1315 TPL_FUT_OVERRIDE.store(
1316 n.unwrap_or(usize::MAX),
1317 std::sync::atomic::Ordering::Relaxed,
1318 );
1319}
1320
1321/// lane-tplfut: which window the TOP ARF's temporal lambda map propagates
1322/// back through ([`crate::speed::TPL_FUT`], `EC_AV1_TPL_FUT=<n>`). Inert
1323/// without [`lookahead`] -- mode 0 is the shipped past window.
1324pub(crate) fn tpl_fut() -> usize {
1325 match TPL_FUT_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
1326 usize::MAX => {}
1327 n => return n,
1328 }
1329 std::env::var("EC_AV1_TPL_FUT")
1330 .ok()
1331 .and_then(|v| v.parse().ok())
1332 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_FUT))
1333}
1334
1335/// lane-tplhalf: mode 2's split -- how many display-PAST neighbours the top
1336/// ARF's window opens with, the rest of the budget coming from the buffered
1337/// future ([`crate::speed::TPL_FUT_HALF`], `EC_AV1_TPL_FUT_HALF=<n>`).
1338pub(crate) fn tpl_fut_half() -> usize {
1339 std::env::var("EC_AV1_TPL_FUT_HALF")
1340 .ok()
1341 .and_then(|v| v.parse().ok())
1342 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_FUT_HALF))
1343}
1344
1345/// lane-tplhalf: how many entries mode 2's window holds in total, `0` meaning
1346/// `tpl_depth() - 1` -- the ARF window's budget alone, so raising it does not
1347/// deepen every other frame's lambda pass the way `EC_AV1_TPL_D` does
1348/// ([`crate::speed::TPL_FUT_WIN`], `EC_AV1_TPL_FUT_WIN=<n>`).
1349pub(crate) fn tpl_fut_win(depth: usize) -> usize {
1350 match std::env::var("EC_AV1_TPL_FUT_WIN")
1351 .ok()
1352 .and_then(|v| v.parse().ok())
1353 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_FUT_WIN))
1354 {
1355 0 => depth - 1,
1356 n => n,
1357 }
1358}
1359
1360/// lane-lookahead: whether the pyramid path holds one group of lookahead
1361/// ([`crate::speed::LOOKAHEAD`], `EC_AV1_LOOKAHEAD=0|1`).
1362fn lookahead() -> bool {
1363 match LOOKAHEAD_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
1364 0 => return false,
1365 1 => return true,
1366 _ => {}
1367 }
1368 match std::env::var("EC_AV1_LOOKAHEAD").ok() {
1369 Some(v) => v != "0",
1370 None => crate::speed::LOOKAHEAD,
1371 }
1372}
1373
1374fn tpl_pyramid() -> bool {
1375 match std::env::var("EC_AV1_TPL_PYRAMID").ok() {
1376 Some(v) => v != "0",
1377 None => TPL_PYRAMID,
1378 }
1379}
1380
1381/// [`tpl_pyramid`]'s default.
1382const TPL_PYRAMID: bool = true;
1383
1384/// Whether a group's TOP ARF names the ARF from TWO groups back as its own
1385/// `ALTREF_FRAME` (lane-arfcen). It has always named `GOLDEN_SLOT` there,
1386/// which for a top ARF is the key frame it already reads as `GOLDEN`, i.e.
1387/// its second reference is the same picture as its first for the first group
1388/// and adds nothing after: the ARF-vs-ARF census reads
1389/// `LAST@-8 GOLDEN@-8` on our first ARF where rav1e's reads two DISTINCT
1390/// anchors. The slot the ARF is about to refresh still holds that older
1391/// anchor while this frame is coded, so naming it costs no extra DPB slot.
1392fn arf_altref() -> bool {
1393 match std::env::var("EC_AV1_ARF_ALTREF").ok() {
1394 Some(v) => v != "0",
1395 None => ARF_ALTREF,
1396 }
1397}
1398
1399/// [`arf_altref`]'s default. ON since its long-GOP arm: film A
1400/// +42.8%/+4.5% -> +40.9%/+3.1% and film B +127.3%/+32.9% -> +125.6%/+32.0%
1401/// (BD vs libaom cpu-used 6 / vs rav1e speed 6), i.e. both films down on both
1402/// columns.
1403const ARF_ALTREF: bool = true;
1404
1405/// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per
1406/// [`Av1Encoder::encode`] call — or, with a [`Pyramid`] configured, a
1407/// coding-order burst of them per [`Av1Encoder::encode_frames`] call plus a
1408/// [`Av1Encoder::flush`] at the end of the stream.
1409#[derive(Debug)]
1410pub struct Av1Encoder {
1411 config: EncoderConfig,
1412 color_config: ColorConfig,
1413 /// The previous picture's own (padded, uncropped) reconstruction — what
1414 /// the next inter frame predicts from — or `None` right after a key
1415 /// frame's turn comes up again, where it is about to be replaced rather
1416 /// than read.
1417 reference: Option<Picture>,
1418 next_index: u64,
1419 /// `Some` only when constructed via
1420 /// [`Av1Encoder::with_rate_target`]`(_, RateTarget::BytesPerFrame(_))`;
1421 /// otherwise every picture is coded at `config.base_q_idx`, unchanged
1422 /// from before this field existed.
1423 rate_loop: Option<RateLoop>,
1424 /// This stream's decode-side per-frame state, owned here so `encode`
1425 /// keeps the public signature it had before the state stopped being
1426 /// thread-local. One per encoder, never per frame: several of its fields
1427 /// (the inter-frame inheritance guards) carry state ACROSS frames.
1428 fctx: crate::decode::FrameCtx,
1429 /// What the last coded frame stored into the reference slot the next
1430 /// inter frame reads (spec 7.20): the tables that frame's tile writer
1431 /// must start from, since the header leaves
1432 /// `disable_frame_end_update_cdf` off. `None` before the first frame.
1433 carried_cdfs: Option<crate::encode::CdfSnapshot>,
1434 /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`,
1435 /// which stays in DPB slot 1 until the next key frame refreshes it.
1436 golden: Option<Picture>,
1437 /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is
1438 /// about to refresh (`encode_inter_frame`'s 0/2 alternation).
1439 prev2: Option<Picture>,
1440 /// `Some` puts the encoder in pyramid mode: [`Av1Encoder::encode`] then
1441 /// refuses (a picture no longer maps to one packet) and the state below
1442 /// drives coding order.
1443 pyramid: Option<Pyramid>,
1444 /// The eight DPB slots, modelled exactly as the decoder does (spec 7.20):
1445 /// what picture each holds, the order hint it was coded at, and the CDF
1446 /// tables it stored. Only pyramid mode reads these; the flat path keeps
1447 /// `reference`/`golden`/`prev2` so its bytes are unchanged.
1448 dpb: [Option<DpbSlot>; 8],
1449 /// Pictures held back waiting for their mini-GOP's hidden frame.
1450 pending: Vec<(u64, Picture)>,
1451 /// lane-lookahead: the CLOSED group waiting for the next group's sources
1452 /// before it is coded, so its top ARF -- the group's last picture in
1453 /// display order -- has display-future neighbours available. Always empty
1454 /// with [`lookahead`] off.
1455 ready: Vec<(u64, Picture)>,
1456 /// The flat path's delay queue: pictures whose packets later calls
1457 /// return, each coded with the ones behind it as its lookahead window
1458 /// (lane-av1facade, deepened to [`crate::encode::tpl_depth`] - 1 on
1459 /// lane-av1tpl2). Unused in pyramid mode, which buffers in `pending`.
1460 held: std::collections::VecDeque<Picture>,
1461 /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its
1462 /// anchor.
1463 anchor: usize,
1464 /// lane-last2: the [`LEAF_SLOTS`] the last two SHOWN leaves refreshed,
1465 /// most recent first, across mini-GOP boundaries (the first leaf of a
1466 /// group reads the anchor as `LAST_FRAME`, so its `LAST2_FRAME` is the
1467 /// previous group's last leaf). Cleared by every key frame.
1468 leaf_hist: Vec<u8>,
1469 /// Coding-order position of the next packet — a packet's `dts`.
1470 next_dts: u64,
1471 /// Set by [`Av1Encoder::encode_sequence_pyramid`]: every coded frame's
1472 /// own cropped [`Encoded`] (its display position and its reconstruction),
1473 /// which is what [`crate::encode::EncodedSequence`] carries and a packet
1474 /// does not. `None` for every other caller, which pays nothing for it.
1475 collected: Option<Vec<(u64, Encoded)>>,
1476}
1477
1478/// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores
1479/// and what a `ref_frame_idx` entry reads back.
1480#[derive(Debug, Clone)]
1481struct DpbSlot {
1482 picture: Picture,
1483 order_hint: u32,
1484 cdfs: crate::encode::CdfSnapshot,
1485}
1486
1487/// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are
1488/// `Send` but `!Sync`): it can move to another thread, it just cannot be
1489/// shared by reference across threads.
1490const _: fn() = || {
1491 fn assert_send<T: Send>() {}
1492 assert_send::<Av1Encoder>();
1493};
1494
1495impl Av1Encoder {
1496 /// [`Av1Encoder::new`] at a SPEED PRESET (`speed` 0..=10, rav1e's scale:
1497 /// 0 is the full search this encoder has always run and is byte for byte
1498 /// identical to [`Av1Encoder::new`]; higher presets switch search levers
1499 /// off, [`crate::speed::levers`] naming which).
1500 ///
1501 /// The preset is process-global (the tile search reads it from worker
1502 /// threads -- see [`crate::speed`]), so it is set here for every encode
1503 /// that follows on this process, and two encoders at different speeds
1504 /// must not run concurrently. `EC_AV1_SPEED=<n>` is the same knob for a
1505 /// caller that does not construct the encoder itself.
1506 ///
1507 /// # Errors
1508 /// [`Av1Encoder::new`]'s.
1509 pub fn with_speed(config: EncoderConfig, speed: u8) -> Result<Self> {
1510 crate::speed::set_speed(speed);
1511 Self::new(config)
1512 }
1513
1514 /// # Errors
1515 /// Returns an error when `config.width`/`config.height` are zero, odd,
1516 /// or larger than the 16-bit frame size an AV1 sequence header carries,
1517 /// or when `config.gop` is zero (there would be no picture to code the
1518 /// next key frame from a cadence of).
1519 pub fn new(config: EncoderConfig) -> Result<Self> {
1520 if config.gop == 0 {
1521 return Err(Error::unsupported("AV1 encode", "gop must be at least 1"));
1522 }
1523 // Validate the geometry the same way the picture-level entry points
1524 // do, before the first `encode()` call rather than only surfacing it
1525 // then.
1526 Picture::grey(config.width, config.height).check_even()?;
1527 // A tile is a whole number of superblocks, so a frame cannot carry
1528 // more tile columns (rows) than it has 64x64 superblocks across
1529 // (down) -- the header's own `max_log2_tile_cols` bound (spec
1530 // 5.9.15), refused here rather than at the first `encode()` call.
1531 let sb_cols = config.width.div_ceil(64) as u32;
1532 let sb_rows = config.height.div_ceil(64) as u32;
1533 if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows {
1534 return Err(Error::unsupported(
1535 "AV1 encode",
1536 format!(
1537 "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has",
1538 1 << config.tile_cols_log2,
1539 1 << config.tile_rows_log2
1540 ),
1541 ));
1542 }
1543 Ok(Self {
1544 carried_cdfs: None,
1545 golden: None,
1546 prev2: None,
1547 color_config: config.colour.color_config(),
1548 config,
1549 reference: None,
1550 next_index: 0,
1551 rate_loop: None,
1552 fctx: crate::decode::FrameCtx::for_encoder(),
1553 pyramid: None,
1554 dpb: [const { None }; 8],
1555 pending: Vec::new(),
1556 ready: Vec::new(),
1557 held: std::collections::VecDeque::new(),
1558 anchor: 0,
1559 leaf_hist: Vec::new(),
1560 next_dts: 0,
1561 collected: None,
1562 })
1563 }
1564
1565 /// [`Av1Encoder::new`] in pyramid mode: pictures are coded out of display
1566 /// order, so a call to [`Av1Encoder::encode_frames`] returns zero, one or
1567 /// several packets and [`Av1Encoder::flush`] drains whatever is still
1568 /// held at the end of the stream. [`Av1Encoder::encode`]'s one-in-one-out
1569 /// contract cannot hold here and it returns an error instead; a caller
1570 /// that wants the old shape simply does not call this constructor.
1571 ///
1572 /// # Errors
1573 /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be
1574 /// left between the anchor and the hidden frame) or above `config.gop`
1575 /// (the group would straddle a key frame).
1576 pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> {
1577 if pyramid.mini_gop < 2 {
1578 return Err(Error::unsupported(
1579 "AV1 encode",
1580 "a pyramid mini-GOP is at least 2 pictures",
1581 ));
1582 }
1583 let mut encoder = Self::new(config)?;
1584 encoder.pyramid = Some(pyramid);
1585 Ok(encoder)
1586 }
1587
1588 /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it,
1589 /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of
1590 /// `config.base_q_idx` being used as-is.
1591 ///
1592 /// # Errors
1593 /// Same as [`Av1Encoder::new`].
1594 pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> {
1595 let rate_loop = rate.into_loop(&mut config, None);
1596 let mut encoder = Self::new(config)?;
1597 encoder.rate_loop = rate_loop;
1598 Ok(encoder)
1599 }
1600
1601 /// [`Av1Encoder::with_pyramid`] and [`Av1Encoder::with_rate_target`] at
1602 /// once: the rate loop then keeps a separate quantizer per pyramid level,
1603 /// predicting each frame's size from the previous frame of its OWN level
1604 /// (a leaf and a hidden `ALTREF` differ by several times in size, so one
1605 /// shared predictor would swing the quantizer every frame).
1606 ///
1607 /// # Errors
1608 /// As both.
1609 pub fn with_pyramid_and_rate_target(
1610 mut config: EncoderConfig,
1611 pyramid: Pyramid,
1612 rate: RateTarget,
1613 ) -> Result<Self> {
1614 let rate_loop = rate.into_loop(&mut config, Some(pyramid));
1615 let mut encoder = Self::with_pyramid(config, pyramid)?;
1616 encoder.rate_loop = rate_loop;
1617 Ok(encoder)
1618 }
1619
1620 /// The [`Pyramid`] this stream is actually coding under: what
1621 /// [`Av1Encoder::with_pyramid`] asked for, or `None` once the content gate
1622 /// in [`Av1Encoder::encode_frames`] has dropped a screen-content stream
1623 /// back to the flat path. Meaningful after the first picture has been
1624 /// handed in.
1625 #[must_use]
1626 pub fn pyramid(&self) -> Option<Pyramid> {
1627 self.pyramid
1628 }
1629
1630 /// The coded (padded-to-64) frame size every picture in this stream is
1631 /// coded at — what a decoder allocates and what `ffprobe` reports.
1632 #[must_use]
1633 pub fn coded_size(&self) -> (usize, usize) {
1634 (
1635 self.config.width.next_multiple_of(SUPERBLOCK),
1636 self.config.height.next_multiple_of(SUPERBLOCK),
1637 )
1638 }
1639
1640 /// The display (render) size every frame header signals — [`EncoderConfig`]'s
1641 /// own `width`/`height`, always, whatever the coded size pads it to.
1642 #[must_use]
1643 pub fn display_size(&self) -> (usize, usize) {
1644 (self.config.width, self.config.height)
1645 }
1646
1647 /// Takes one picture and returns the PREVIOUS picture's packet, key or
1648 /// inter by this stream's `gop` cadence — the facade's one frame of
1649 /// latency (the picture just handed in is what the previous one is coded
1650 /// against as its lookahead). The FIRST call has no previous picture and
1651 /// returns a packet with an EMPTY `data` (its other fields are
1652 /// placeholders; test `data.is_empty()`), and the last picture's packet
1653 /// comes out of [`Av1Encoder::flush`] — so a caller that concatenates
1654 /// `data` in call order still gets the whole stream, provided it flushes
1655 /// at the end.
1656 ///
1657 /// # Errors
1658 /// Returns an error when `picture`'s size does not match
1659 /// [`EncoderConfig::width`]/[`EncoderConfig::height`], when the encoder
1660 /// was built by [`Av1Encoder::with_pyramid`] (which reorders pictures, so
1661 /// one call cannot return one packet), or under the same conditions
1662 /// [`crate::encode::encode_key_frame`]/[`crate::encode::encode_sequence`]
1663 /// do.
1664 pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {
1665 if self.pyramid.is_some() {
1666 return Err(Error::unsupported(
1667 "AV1 encode",
1668 "a pyramid stream reorders pictures -- use encode_frames()/flush()",
1669 ));
1670 }
1671 let mut packets = self.encode_frames(picture)?;
1672 Ok(packets.pop().unwrap_or(Packet {
1673 data: Vec::new(),
1674 key: false,
1675 order: 0,
1676 dts: 0,
1677 level: Level::Leaf,
1678 }))
1679 }
1680
1681 /// Takes one picture and returns every packet it completed, in coding
1682 /// order. Without a [`Pyramid`] that is one packet — the PREVIOUS
1683 /// picture's, since this one is its lookahead — and none at all on the
1684 /// first call; with one it is
1685 /// empty for most pictures and a whole mini-GOP's worth (the hidden
1686 /// frame, its leaves and the `show_existing_frame` that re-outputs it)
1687 /// for the picture that closes a group.
1688 ///
1689 /// # Errors
1690 /// As [`Av1Encoder::encode`], minus the pyramid refusal.
1691 pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {
1692 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
1693 // lane-split: the split census prints on every exit of this call when
1694 // armed, so no `return` path loses it; the counters are cumulative, so
1695 // the last table a run prints is that run's total.
1696 struct SplitCensusDump;
1697 impl Drop for SplitCensusDump {
1698 fn drop(&mut self) {
1699 if crate::encode::split_census_on() {
1700 crate::encode::dump_split_census();
1701 }
1702 if crate::encode::newmv_census_on() {
1703 crate::encode::dump_newmv_census();
1704 }
1705 }
1706 }
1707 // `then_some` would CONSTRUCT the guard eagerly and drop it when the
1708 // flag is off, which runs `Drop` -- and printed the census header on
1709 // every unarmed encode. `then` builds it only when armed.
1710 let _census = (crate::encode::split_census_on() || crate::encode::newmv_census_on())
1711 .then(|| SplitCensusDump);
1712 if (picture.width, picture.height) != (self.config.width, self.config.height) {
1713 return Err(Error::unsupported(
1714 "AV1 encode",
1715 format!(
1716 "picture is {}x{}, encoder is {}x{}",
1717 picture.width, picture.height, self.config.width, self.config.height
1718 ),
1719 ));
1720 }
1721 // THE CONTENT GATE (lane-av1pyrgate): the pyramid is for camera
1722 // material. A desktop capture is the one content class every pyramid
1723 // sweep measured WORSE under it, and it is exactly the class the
1724 // screen detector separates (`encode::screen_content`: 0/48 frames on
1725 // both real films, 48/48 on the OBS capture), so a stream whose first
1726 // picture reads as screen content drops back to the flat path and
1727 // codes byte for byte what it coded before the pyramid existed.
1728 //
1729 // Decided ONCE, on the first picture, not per mini-GOP: the flat path
1730 // keeps its references in `reference`/`golden`/`prev2` and the pyramid
1731 // path in `dpb`, so a switch after the first frame would read slots
1732 // the other path never filled. Per-GOP re-decision needs the two
1733 // reference sets kept in step first; the gate's own recipe codes one
1734 // GOP per stream, where the two are the same decision.
1735 if self.pyramid.is_some()
1736 && self.next_index == 0
1737 && crate::encode::picture_is_screen(picture)
1738 {
1739 self.pyramid = None;
1740 }
1741 let Some(pyramid) = self.pyramid else {
1742 // The delay queue: the pictures behind this one are the
1743 // lookahead window the one at its head is coded with, which is
1744 // what makes the facade's bytes identical to
1745 // `encode_sequence`'s (lane-av1facade, lane-av1tpl2).
1746 self.held.push_back(picture.clone());
1747 if self.held.len() <= crate::encode::tpl_depth() - 1 {
1748 return Ok(Vec::new());
1749 }
1750 let previous = self.held.pop_front().expect("queue is over depth");
1751 let window: Vec<Picture> = self.held.iter().cloned().collect();
1752 return Ok(vec![self.encode_flat(&previous, &window)?]);
1753 };
1754 let order = self.next_index;
1755 self.next_index += 1;
1756 if order.is_multiple_of(self.config.gop as u64) {
1757 // A key frame closes whatever group is open (there is nothing for
1758 // its leaves to point forward at across the boundary) and then
1759 // restarts the pyramid from the key itself.
1760 let mut packets = self.drain_all(Some(picture))?;
1761 packets.push(self.encode_key(order, picture)?);
1762 return Ok(packets);
1763 }
1764 self.pending.push((order, picture.clone()));
1765 // The group closes on the size the LAYOUT gives it (which depends on
1766 // how many pictures are left before the next key frame, so no short
1767 // tail group is left behind), or early when the next picture would be
1768 // a key frame.
1769 let run_start = self.pending[0].0;
1770 let remaining = self.config.gop - (run_start % self.config.gop as u64) as usize;
1771 let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64);
1772 if self.pending.len() >= group_target(remaining, pyramid.mini_gop, absorb_tail())
1773 || next_is_key
1774 {
1775 return self.drain_pending();
1776 }
1777 Ok(Vec::new())
1778 }
1779
1780 /// Codes and returns every picture still held back — the last picture of
1781 /// a flat stream (which has no lookahead and is coded without one), or
1782 /// the tail of a pyramid stream whose last mini-GOP never filled up.
1783 /// Empty once there is nothing held.
1784 ///
1785 /// # Errors
1786 /// As [`Av1Encoder::encode_frames`].
1787 pub fn flush(&mut self) -> Result<Vec<Packet>> {
1788 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
1789 if !self.held.is_empty() {
1790 let mut packets = Vec::with_capacity(self.held.len());
1791 while let Some(previous) = self.held.pop_front() {
1792 let window: Vec<Picture> = self.held.iter().cloned().collect();
1793 packets.push(self.encode_flat(&previous, &window)?);
1794 }
1795 return Ok(packets);
1796 }
1797 self.drain_all(None)
1798 }
1799
1800 /// The flat path: one picture and its lookahead (the next source picture,
1801 /// `None` at the end of the stream) in, one packet out — the same inputs
1802 /// [`crate::encode::encode_sequence`] gives each of its inter frames, so
1803 /// the bytes are identical.
1804 fn encode_flat(&mut self, picture: &Picture, lookahead: &[Picture]) -> Result<Packet> {
1805 let render = (self.config.width, self.config.height);
1806 let padded = picture.padded_to(SUPERBLOCK);
1807 let is_key = self.next_index.is_multiple_of(self.config.gop as u64);
1808 let order = self.next_index;
1809 let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| {
1810 r.q_idx(if is_key { Level::Key } else { Level::Leaf })
1811 });
1812
1813 let encoded: Encoded = if is_key {
1814 encode_key_frame_inner(
1815 &padded,
1816 base_q_idx,
1817 DEADZONE,
1818 &KEY_FRAME_MODES,
1819 split_blocks(),
1820 render,
1821 self.color_config,
1822 &self.fctx,
1823 )?
1824 } else {
1825 let reference = self.reference.as_ref().ok_or_else(|| {
1826 Error::unsupported(
1827 "AV1 encode",
1828 "an inter frame needs a previous reconstruction",
1829 )
1830 })?;
1831 encode_inter_frame(
1832 &padded,
1833 reference,
1834 base_q_idx,
1835 DEADZONE,
1836 order as u32,
1837 // The flat path's own slot plan, in order hints: the key frame
1838 // of the GOP this picture sits in is what `GOLDEN_FRAME`
1839 // names, and every reference but `ALTREF_FRAME` is the frame
1840 // just coded.
1841 crate::encode::flat_order_hints(
1842 order as u32 & 0x7f,
1843 (order - order % self.config.gop as u64) as u32 & 0x7f,
1844 self.prev2.is_some(),
1845 ),
1846 render,
1847 self.carried_cdfs.as_ref().map(|c| &c.0),
1848 self.golden.as_ref(),
1849 self.prev2.as_ref(),
1850 None,
1851 &self.fctx,
1852 None,
1853 &lookahead
1854 .iter()
1855 .map(|n| n.padded_to(SUPERBLOCK))
1856 .collect::<Vec<_>>(),
1857 )?
1858 };
1859
1860 self.carried_cdfs = Some(encoded.next_cdfs.clone());
1861 if is_key {
1862 self.golden = Some(encoded.reconstruction.clone());
1863 self.prev2 = None;
1864 } else {
1865 self.prev2 = self.reference.take();
1866 }
1867 self.reference = Some(encoded.reconstruction.clone());
1868 self.next_index += 1;
1869 let cropped = crop_encoded(&encoded, render.0, render.1);
1870 let level = if is_key { Level::Key } else { Level::Leaf };
1871 if let Some(rate_loop) = self.rate_loop.as_mut() {
1872 // The flat path codes every frame at the slot's own q, no offset.
1873 rate_loop.update(level, 0, i16::from(base_q_idx), cropped.stream.len());
1874 }
1875 Ok(self.packet(cropped.stream, is_key, order, level))
1876 }
1877
1878 /// THE SHARED MINI-GOP DRIVER: codes a whole sequence — one key frame
1879 /// then all inter, which is [`crate::encode::encode_sequence`]'s only
1880 /// shape — through this very facade, under `pyramid`, and hands back what
1881 /// that path returns. The two are byte-identical BY CONSTRUCTION rather
1882 /// than by a mirrored second implementation: there is one reordering,
1883 /// one DPB/slot policy and one set of per-level quantizer offsets, here
1884 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
1885 /// still pins it, now over a pyramid sequence too).
1886 ///
1887 /// The content gate lives in [`Av1Encoder::encode_frames`] and applies
1888 /// unchanged, so a screen-content clip handed in here codes flat.
1889 ///
1890 /// `EncodedSequence::frames` comes back in DISPLAY order, one entry per
1891 /// source picture — the order the flat path's coding order happens to be,
1892 /// and the order every reader of it (the BD gate's sample-exactness
1893 /// assertions against a decoder's output) needs. `stream` stays in coding
1894 /// order, which is the order a decoder reads.
1895 ///
1896 /// # Errors
1897 /// As [`Av1Encoder::encode_frames`].
1898 pub(crate) fn encode_sequence_pyramid(
1899 pictures: &[Picture],
1900 base_q_idx: u8,
1901 pyramid: Pyramid,
1902 tiles: (u32, u32),
1903 ) -> Result<crate::encode::EncodedSequence> {
1904 let first = pictures.first().ok_or_else(|| {
1905 Error::unsupported("AV1 encode", "a sequence needs at least one picture")
1906 })?;
1907 let config = EncoderConfig {
1908 width: first.width,
1909 height: first.height,
1910 base_q_idx,
1911 // One key frame, at picture 0, and inter for the rest.
1912 gop: pictures.len().max(1),
1913 // `encode_sequence` writes an unspecified colour config.
1914 colour: Colour::Unspecified,
1915 tile_cols_log2: tiles.0,
1916 tile_rows_log2: tiles.1,
1917 };
1918 let mut encoder = Self::with_pyramid(config, pyramid)?;
1919 encoder.collected = Some(Vec::with_capacity(pictures.len()));
1920 let mut stream = Vec::new();
1921 for picture in pictures {
1922 for packet in encoder.encode_frames(picture)? {
1923 stream.extend_from_slice(&packet.data);
1924 }
1925 }
1926 for packet in encoder.flush()? {
1927 stream.extend_from_slice(&packet.data);
1928 }
1929 let mut collected = encoder.collected.take().expect("collecting");
1930 // Every source picture is coded exactly once, so a frame's display
1931 // order IS its index once the list is sorted by it.
1932 let coding_order: Vec<usize> = collected.iter().map(|(order, _)| *order as usize).collect();
1933 collected.sort_by_key(|(order, _)| *order);
1934 let frames: Vec<Encoded> = collected.into_iter().map(|(_, encoded)| encoded).collect();
1935 assert!(
1936 coding_order.iter().all(|&i| i < frames.len()),
1937 "a coded frame's display position is outside the sequence"
1938 );
1939 Ok(crate::encode::EncodedSequence {
1940 stream,
1941 frames,
1942 coding_order,
1943 })
1944 }
1945
1946 /// Stamps a packet with its display and coding positions and advances the
1947 /// coding-order clock.
1948 fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet {
1949 let dts = self.next_dts;
1950 self.next_dts += 1;
1951 Packet {
1952 data,
1953 key,
1954 order,
1955 dts,
1956 level,
1957 }
1958 }
1959
1960 /// Stores a coded frame into every DPB slot its `refresh_frame_flags`
1961 /// names (spec 7.20).
1962 fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) {
1963 let slot = DpbSlot {
1964 picture: encoded.reconstruction.clone(),
1965 order_hint,
1966 cdfs: encoded.next_cdfs.clone(),
1967 };
1968 for &s in slots {
1969 self.dpb[s as usize] = Some(slot.clone());
1970 }
1971 }
1972
1973 /// Codes a key frame in pyramid mode: it refreshes all eight slots, so it
1974 /// becomes the anchor, the `GOLDEN_FRAME` and the CDF source for the
1975 /// whole GOP at once.
1976 fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> {
1977 let render = (self.config.width, self.config.height);
1978 let base = self
1979 .rate_loop
1980 .as_ref()
1981 .map_or(i16::from(self.config.base_q_idx), |r| {
1982 i16::from(r.q_idx(Level::Key))
1983 });
1984 let offset = self.pyramid.map_or(0, |p| p.key_q_offset);
1985 let base_q_idx = (base + offset).clamp(1, 255) as u8;
1986 let encoded = encode_key_frame_inner(
1987 &picture.padded_to(SUPERBLOCK),
1988 base_q_idx,
1989 DEADZONE,
1990 &KEY_FRAME_MODES,
1991 split_blocks(),
1992 render,
1993 self.color_config,
1994 &self.fctx,
1995 )?;
1996 self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0);
1997 self.anchor = 0;
1998 // Every leaf slot now holds the key frame, which `GOLDEN_FRAME`
1999 // already names: the chain starts empty again.
2000 self.leaf_hist.clear();
2001 let cropped = crop_encoded(&encoded, render.0, render.1);
2002 if let Some(rate_loop) = self.rate_loop.as_mut() {
2003 rate_loop.update(Level::Key, 0, base + offset, cropped.stream.len());
2004 }
2005 if let Some(collected) = self.collected.as_mut() {
2006 collected.push((order, cropped.clone()));
2007 }
2008 Ok(self.packet(cropped.stream, true, order, Level::Key))
2009 }
2010
2011 /// Codes one inter frame at `order` from the DPB, in coding order.
2012 #[allow(clippy::too_many_arguments)]
2013 fn encode_pyramid_inter(
2014 &mut self,
2015 order: u64,
2016 picture: &Picture,
2017 last_slot: u8,
2018 self_slot: u8,
2019 altref_slot: u8,
2020 // lane-last2: the slot read as `LAST2_FRAME`. `None` -- and any slot
2021 // holding no picture, or the same one `LAST_FRAME` reads -- leaves
2022 // the reference set exactly as it was before this lane.
2023 last2_slot: Option<u8>,
2024 show_frame: bool,
2025 level: Level,
2026 // The quantizer offset comes from the CALLER, not from `level`: a
2027 // three-level group codes two `Level::Arf` frames (the group's top
2028 // ARF and the mid one) at different offsets, and they share the
2029 // rate-control slot but not the offset.
2030 offset: i16,
2031 // The lookahead window this frame's temporal lambda map is built
2032 // from, already padded (lane-arfcen). Empty codes the frame at one
2033 // lambda, which is what the whole pyramid path used to do.
2034 lookahead: &[Picture],
2035 // lane-lookahead: DISPLAY-FUTURE pictures for the SOURCE temporal
2036 // filter only (the top ARF's, out of the buffered next group), never
2037 // for the temporal lambda map -- keeping the filter's window and the
2038 // tpl window separate levers. Empty everywhere else.
2039 future: &[Picture],
2040 ) -> Result<Packet> {
2041 let render = (self.config.width, self.config.height);
2042 let order_hint = (order & 0x7f) as u32;
2043 let base = self
2044 .rate_loop
2045 .as_ref()
2046 .map_or(i16::from(self.config.base_q_idx), |r| {
2047 i16::from(r.q_idx(level))
2048 });
2049 let base_q_idx = (base + offset).clamp(1, 255) as u8;
2050 // lane-arfq: the top ARF of a mini-GOP is the hidden frame coded at
2051 // the pyramid's OWN `arf_q_offset` (the mid and quarter levels are
2052 // `Level::Arf` too but sit at their own offsets), and it is the level
2053 // the whole group predicts from -- so it reads its own `delta_q`
2054 // strength (`crate::speed::DQ_LEVEL_K`).
2055 let dq_level = match (show_frame, self.pyramid.map(|p| p.arf_q_offset)) {
2056 (true, _) => crate::encode::DqLevel::Leaf,
2057 (false, Some(arf)) if arf == offset => crate::encode::DqLevel::TopArf,
2058 (false, _) => crate::encode::DqLevel::MidArf,
2059 };
2060 // spec 5.9.2's `ref_frame_sign_bias`, derived from what the slots
2061 // this frame names actually hold: a reference whose order hint is
2062 // AHEAD of this frame's is backward-biased, and the MV stack scans
2063 // (writer and decoder alike) flip borrowed candidates across the
2064 // boundary. Only `ALTREF_FRAME` can be ahead here — the leaves of a
2065 // mini-GOP name the group's hidden frame there.
2066 let mut sign_bias = crate::mvstack::NO_SIGN_BIAS;
2067 let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| {
2068 dpb[slot as usize]
2069 .as_ref()
2070 .is_some_and(|s| s.order_hint > order_hint)
2071 };
2072 // A LAST2 slot only counts when it holds a picture that is not the
2073 // one `LAST_FRAME` already names; otherwise the frame codes the
2074 // reference set it always did.
2075 let last2_slot = last2_slot.filter(|&s| s != last_slot && self.dpb[s as usize].is_some());
2076 let slots = [
2077 last_slot,
2078 last2_slot.unwrap_or(last_slot),
2079 last_slot,
2080 GOLDEN_SLOT,
2081 last_slot,
2082 last_slot,
2083 altref_slot,
2084 ];
2085 for (i, slot) in slots.into_iter().enumerate() {
2086 sign_bias[i] = ahead(slot, &self.dpb);
2087 }
2088 // The same seven slots' order hints, for `skipModeAllowed` (spec
2089 // 5.9.22) in the frame-header writer.
2090 let order_hints: [u32; 7] = slots.map(|slot| {
2091 self.dpb[slot as usize]
2092 .as_ref()
2093 .map_or(0, |s| (s.order_hint & 0x7f) as u32)
2094 });
2095 let reference = self.dpb[last_slot as usize]
2096 .as_ref()
2097 .map(|s| s.picture.clone())
2098 .ok_or_else(|| {
2099 Error::unsupported(
2100 "AV1 encode",
2101 "an inter frame needs a previous reconstruction",
2102 )
2103 })?;
2104 let last2 =
2105 last2_slot.and_then(|s| self.dpb[s as usize].as_ref().map(|d| d.picture.clone()));
2106 let golden = self.dpb[GOLDEN_SLOT as usize]
2107 .as_ref()
2108 .map(|s| s.picture.clone());
2109 let altref = (altref_slot != GOLDEN_SLOT)
2110 .then(|| {
2111 self.dpb[altref_slot as usize]
2112 .as_ref()
2113 .map(|s| s.picture.clone())
2114 })
2115 .flatten();
2116 let start_cdfs = self.dpb[last_slot as usize]
2117 .as_ref()
2118 .map(|s| s.cdfs.0.clone());
2119 // lane-arfpred: the top ARF is coded from a TEMPORALLY FILTERED
2120 // source when `speed::ARF_TF` is non-zero -- the grain it would
2121 // otherwise spend its residual on is averaged out against the
2122 // group's own display neighbours (`lookahead`, already padded).
2123 let source = picture.padded_to(SUPERBLOCK);
2124 // ... and never at the very top of the quality range, where the
2125 // anchor's own quantizer has hit the rate loop's floor
2126 // ([`crate::speed::ARF_TF_QMIN`]).
2127 let tf = match dq_level {
2128 crate::encode::DqLevel::TopArf => arf_tf_strength(),
2129 // lane-arftf: the mid ARF gets its own strength -- its window is
2130 // the group's later leaves, i.e. the filter runs FORWARD there.
2131 crate::encode::DqLevel::MidArf => arf_tf_mid_strength(),
2132 crate::encode::DqLevel::Leaf => 0.0,
2133 };
2134 let tf = match base_q_idx >= crate::speed::ARF_TF_QMIN {
2135 true => tf,
2136 false => 0.0,
2137 };
2138 let source = match tf > 0.0 {
2139 true => {
2140 // lane-lookahead: the filter's window is sized HERE -- up to
2141 // `ARF_TF_WIN` display-past neighbours (nearest first) and
2142 // then the display-future ones the caller buffered.
2143 let window: Vec<Picture> = lookahead
2144 .iter()
2145 .take(arf_tf_window())
2146 .chain(future.iter())
2147 .cloned()
2148 .collect();
2149 crate::encode::arf_temporal_filter(&source, &window, tf)
2150 }
2151 false => source,
2152 };
2153 let encoded = || -> Result<Encoded> {
2154 encode_inter_frame(
2155 &source,
2156 &reference,
2157 base_q_idx,
2158 DEADZONE,
2159 order_hint,
2160 order_hints,
2161 render,
2162 start_cdfs.as_ref(),
2163 golden.as_ref(),
2164 altref.as_ref(),
2165 last2.as_ref(),
2166 &self.fctx,
2167 Some(crate::encode::PyramidFrame {
2168 last_slot,
2169 self_slot,
2170 altref_slot,
2171 last2_slot,
2172 show_frame,
2173 sign_bias,
2174 dq_level,
2175 }),
2176 // lane-arfcen: the group's own sources ARE this frame's window
2177 // (`tpl_window`); it was `&[]` here, which switched the temporal
2178 // lambda map off on every frame the default stream codes.
2179 lookahead,
2180 )
2181 }();
2182 // Name the pyramid position in any failure: an error out of the tile
2183 // writer or the filter search is otherwise indistinguishable between
2184 // the hidden frame and the leaves that read it.
2185 let encoded = encoded.map_err(|e| {
2186 Error::unsupported(
2187 "AV1 encode",
2188 format!(
2189 "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \
2190 altref {altref_slot}, last2 {last2_slot:?}, shown {show_frame}, golden {}, \
2191 altref pic {}): {e}",
2192 golden.is_some(),
2193 altref.is_some(),
2194 ),
2195 )
2196 })?;
2197 self.refresh(&[self_slot], &encoded, order_hint);
2198 let cropped = crop_encoded(&encoded, render.0, render.1);
2199 if let Some(rate_loop) = self.rate_loop.as_mut() {
2200 rate_loop.update(level, offset, base + offset, cropped.stream.len());
2201 }
2202 if let Some(collected) = self.collected.as_mut() {
2203 collected.push((order, cropped.clone()));
2204 }
2205 Ok(self.packet(cropped.stream, false, order, level))
2206 }
2207
2208 /// Closes the open mini-GOP. With the lookahead off that codes it
2209 /// straight away, which is byte for byte what this encoder did before
2210 /// lane-lookahead; with it on the open group takes the `ready` slot and
2211 /// the group ALREADY there is coded, with the open one's sources as its
2212 /// display-future window.
2213 fn drain_pending(&mut self) -> Result<Vec<Packet>> {
2214 if !lookahead() {
2215 let group = std::mem::take(&mut self.pending);
2216 return self.code_group(group, &[]);
2217 }
2218 let group = std::mem::take(&mut self.ready);
2219 let next = std::mem::take(&mut self.pending);
2220 let packets = self.code_group(group, &next);
2221 self.ready = next;
2222 packets
2223 }
2224
2225 /// Codes every group still buffered, in coding order -- what a key frame
2226 /// (`next` is the key picture, the last buffered group's own
2227 /// display-future) and the end of stream (`None`) both need. The tail
2228 /// group can be any length, down to the single picture `code_group`
2229 /// codes as one shown leaf.
2230 fn drain_all(&mut self, next: Option<&Picture>) -> Result<Vec<Packet>> {
2231 let tail: Vec<(u64, Picture)> = next
2232 .filter(|_| lookahead())
2233 .map(|p| vec![(self.next_index, p.clone())])
2234 .unwrap_or_default();
2235 let ready = std::mem::take(&mut self.ready);
2236 let pending = std::mem::take(&mut self.pending);
2237 let mut packets = self.code_group(ready, &pending)?;
2238 packets.extend(self.code_group(pending, &tail)?);
2239 Ok(packets)
2240 }
2241
2242 /// Codes one mini-GOP: its hidden frame first, then its leaves, then
2243 /// the `show_existing_frame` header that puts the hidden frame back in
2244 /// display order. `future` is the display-future sources the caller has
2245 /// buffered past this group (lane-lookahead), empty without a lookahead.
2246 fn code_group(
2247 &mut self,
2248 group: Vec<(u64, Picture)>,
2249 future: &[(u64, Picture)],
2250 ) -> Result<Vec<Packet>> {
2251 if group.is_empty() {
2252 return Ok(Vec::new());
2253 }
2254 let mut packets = Vec::with_capacity(group.len() + 1);
2255 // The lookahead window of the group's picture at index `pos`: the
2256 // display-order successors inside this group, or -- for the group's
2257 // top ARF, the last picture, whose successors are not buffered yet --
2258 // the leaves BEHIND it in reverse display order, which are exactly
2259 // the pictures that predict backward from it. Padded like the frame
2260 // itself, as `encode_inter_frame` wants it.
2261 let tpl_window = |pos: usize, back: bool| -> Vec<Picture> {
2262 let depth = crate::encode::tpl_depth();
2263 if !tpl_pyramid() || depth < 2 {
2264 return Vec::new();
2265 }
2266 let window: Vec<&Picture> = match back {
2267 false => group[pos + 1..].iter().map(|(_, p)| p).collect(),
2268 true => group[..pos].iter().rev().map(|(_, p)| p).collect(),
2269 };
2270 window
2271 .into_iter()
2272 .take(depth - 1)
2273 .map(|p| p.padded_to(SUPERBLOCK))
2274 .collect()
2275 };
2276 // lane-last2: the slot a frame reading `last_slot` as `LAST_FRAME`
2277 // names as `LAST2_FRAME` -- the most recent shown leaf that is not
2278 // the one it already reads. `None` with the lever off, or before two
2279 // distinct past pictures exist.
2280 let last2_of = |hist: &[u8], last_slot: u8| -> Option<u8> {
2281 last2()
2282 .then(|| hist.iter().copied().find(|&s| s != last_slot))
2283 .flatten()
2284 };
2285 let anchor_slot = ANCHOR_SLOTS[self.anchor];
2286 let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor];
2287 let (arf_order, arf_picture) = group.last().cloned().expect("non-empty");
2288 let pyramid = self.pyramid.expect("pyramid mode");
2289 if group.len() == 1 {
2290 // Nothing to predict backward, so no hidden frame: one shown leaf
2291 // that also becomes the next group's anchor.
2292 packets.push(self.encode_pyramid_inter(
2293 arf_order,
2294 &arf_picture,
2295 anchor_slot,
2296 next_anchor_slot,
2297 GOLDEN_SLOT,
2298 last2_of(&self.leaf_hist, anchor_slot),
2299 true,
2300 Level::Leaf,
2301 pyramid.leaf_q_offset,
2302 &tpl_window(0, false),
2303 &[],
2304 )?);
2305 self.anchor = 1 - self.anchor;
2306 return Ok(packets);
2307 }
2308 // lane-lookahead: the display-future half of the top ARF's temporal
2309 // filter window, padded like the frame itself. Empty when the
2310 // lookahead is off (`future` is then always empty) or when the filter
2311 // asks for no future neighbours, which is what keeps the default
2312 // stream byte-identical.
2313 let arf_future: Vec<Picture> = future
2314 .iter()
2315 .take(arf_tf_window_future())
2316 .map(|(_, p)| p.padded_to(SUPERBLOCK))
2317 .collect();
2318 // lane-tplfut: the top ARF's TEMPORAL LAMBDA window. Mode 0 (and any
2319 // mode with no buffered future picture) keeps the group's own
2320 // display-PAST sources, reversed -- the only window that exists
2321 // without a lookahead, and the one every measurement so far was
2322 // taken with. The other modes read the next group's sources, which
2323 // is the direction libaom's tpl looks at an ARF.
2324 // `n` of the buffered display-future sources, nearest first, padded
2325 // like the frame being coded.
2326 let arf_tpl_future = |n: usize| -> Vec<Picture> {
2327 future
2328 .iter()
2329 .take(n)
2330 .map(|(_, p)| p.padded_to(SUPERBLOCK))
2331 .collect()
2332 };
2333 let arf_tpl: Vec<Picture> = {
2334 let depth = crate::encode::tpl_depth();
2335 let past = || tpl_window(group.len() - 1, true);
2336 match (tpl_fut(), future.is_empty(), tpl_pyramid() && depth >= 2) {
2337 (_, _, false) => Vec::new(),
2338 (0, _, _) | (_, true, _) => past(),
2339 (1, _, _) => arf_tpl_future(depth - 1),
2340 // Half the budget each side (`EC_AV1_TPL_FUT_HALF=<n>`
2341 // moves the split), past first: the chain then has
2342 // ONE discontinuity in the middle (the coarse pass between
2343 // the nearest past and the nearest future neighbour spans the
2344 // whole group), which is the arm's known cost.
2345 (2, _, _) => {
2346 let budget = tpl_fut_win(depth);
2347 let mut w = past();
2348 w.truncate(tpl_fut_half().max(1));
2349 let room = budget.saturating_sub(w.len());
2350 w.extend(arf_tpl_future(room));
2351 w
2352 }
2353 // Mode 3 and anything above: the WHOLE buffered next group.
2354 (_, _, _) => arf_tpl_future(future.len()),
2355 }
2356 };
2357 // The group's top level: the last picture, hidden, off the anchor.
2358 packets.push(self.encode_pyramid_inter(
2359 arf_order,
2360 &arf_picture,
2361 anchor_slot,
2362 next_anchor_slot,
2363 // lane-arfcen: the slot this ARF refreshes still holds the ARF
2364 // from two groups back, so naming it here gives the frame a
2365 // SECOND, distinct past anchor instead of the key it already
2366 // reads as GOLDEN.
2367 match arf_altref() {
2368 true => next_anchor_slot,
2369 false => GOLDEN_SLOT,
2370 },
2371 // The ARF levels take no LAST2: the anchor pair already gives a
2372 // top ARF two distinct past anchors (`arf_altref`), and the mid
2373 // and quarter frames have only the one past anchor in the DPB.
2374 None,
2375 false,
2376 Level::Arf,
2377 pyramid.arf_q_offset,
2378 &arf_tpl,
2379 // lane-lookahead: the group's top ARF is its LAST picture in
2380 // display order, so every picture of the next group is a
2381 // display-future neighbour of it -- nearest first.
2382 &arf_future,
2383 )?);
2384 let leaves = group.len() - 1;
2385 // THE THIRD LEVEL: a second hidden frame at the middle of the leaf
2386 // run, coded off the anchor with the top ARF as its own backward
2387 // reference. It needs a leaf on both sides of it, so a group of
2388 // three or fewer stays two-level.
2389 //
2390 // AND IT NEEDS A RUN LONG ENOUGH TO AMORTISE IT: a GOP that is one
2391 // single mini-GOP (`group_target` absorbs a tail, so a 12-picture GOP
2392 // under `mini_gop` 8 is ONE group of 11) pays for the second hidden
2393 // frame out of eleven pictures and reads +2.8 BD points worse against
2394 // libaom on film B at every mid offset measured (-4: +71.1, -8:
2395 // +71.2, against the two-level +68.4), while the 48-picture GOP -- six
2396 // groups sharing the same machinery -- is 6.0 points BETTER. So the
2397 // third level is switched on by the RUN's length, not by the group's:
2398 // the same GOP-length dependence `group_target` itself was built for.
2399 let long_run = self.config.gop > pyramid.mini_gop + pyramid.mini_gop / 2;
2400 let mid = pyramid
2401 .mid_q_offset
2402 .filter(|_| leaves >= 3 && long_run)
2403 .map(|offset| {
2404 let at = (leaves - 1) / 2;
2405 (at, offset)
2406 });
2407 if let Some((at, offset)) = mid {
2408 let (order, picture) = group[at].clone();
2409 packets.push(self.encode_pyramid_inter(
2410 order,
2411 &picture,
2412 anchor_slot,
2413 MID_SLOT,
2414 next_anchor_slot,
2415 None,
2416 false,
2417 Level::Arf,
2418 offset,
2419 &tpl_window(at, false),
2420 &[],
2421 )?);
2422 }
2423 // THE FOURTH LEVEL: one hidden frame at the middle of each half of
2424 // the leaf run, so no leaf is more than one picture from a hidden
2425 // reference on either side -- the depth the references run (rav1e
2426 // speed 6 codes 23 hidden frames per 48 pictures, libaom four levels
2427 // per 16-picture group) and the lever three levels had run out of.
2428 // It hangs off the mid level, and it needs a leaf on both sides of
2429 // both quarter points, which a run of fewer than seven leaves cannot
2430 // give.
2431 let quarters = match (mid, pyramid.quarter_q_offset) {
2432 (Some((at, _)), Some(offset)) if leaves >= 7 => {
2433 Some(([(at - 1) / 2, (at + leaves) / 2], offset))
2434 }
2435 _ => None,
2436 };
2437 if let Some((at, offset)) = quarters {
2438 // The first quarter predicts forward off the group's anchor and
2439 // backward off the mid ARF; the second starts FROM the mid ARF
2440 // and reads the group's top ARF backward.
2441 for (i, &pos) in at.iter().enumerate() {
2442 let (order, picture) = group[pos].clone();
2443 let (last_slot, altref_slot) = match i {
2444 0 => (anchor_slot, MID_SLOT),
2445 _ => (MID_SLOT, next_anchor_slot),
2446 };
2447 packets.push(self.encode_pyramid_inter(
2448 order,
2449 &picture,
2450 last_slot,
2451 QUARTER_SLOTS[i],
2452 altref_slot,
2453 None,
2454 false,
2455 Level::Arf,
2456 offset,
2457 &tpl_window(pos, false),
2458 &[],
2459 )?);
2460 }
2461 }
2462 // Every hidden frame INSIDE the leaf run, by leaf index, in display
2463 // order: what a leaf reads forward (the nearest one behind it) and
2464 // backward (the nearest one ahead of it, the group's top ARF when
2465 // there is none).
2466 let mut inner: Vec<(usize, u8)> = Vec::new();
2467 if let Some((at, _)) = mid {
2468 inner.push((at, MID_SLOT));
2469 }
2470 if let Some((at, _)) = quarters {
2471 inner.extend(at.iter().zip(QUARTER_SLOTS).map(|(&at, slot)| (at, slot)));
2472 }
2473 inner.sort_unstable();
2474 let (seq, _) = crate::encode::key_frame_headers(
2475 self.config.width,
2476 self.config.height,
2477 self.config.base_q_idx,
2478 )?;
2479 let show_existing = |encoder: &mut Self, slot: u8, order: u64| -> Result<Packet> {
2480 let mut data = crate::obu::temporal_delimiter();
2481 data.extend_from_slice(&crate::frame::show_existing_frame_obu(&seq, slot)?);
2482 Ok(encoder.packet(data, false, order, Level::ShowExisting))
2483 };
2484 // The leaves, in display order, so every `show_existing_frame` lands
2485 // in its own display position. Each leaf names the nearest hidden
2486 // frame BEHIND it as `LAST_FRAME` (the group's anchor for the first
2487 // leaf, otherwise the previous leaf) and the nearest one AHEAD as
2488 // `ALTREF_FRAME` (the group's top ARF when none is closer).
2489 for (i, (order, picture)) in group[..leaves].iter().enumerate() {
2490 if let Some(&(_, slot)) = inner.iter().find(|(at, _)| *at == i) {
2491 let packet = show_existing(self, slot, *order)?;
2492 packets.push(packet);
2493 continue;
2494 }
2495 // The previous shown leaf's own slot: `LEAF_SLOT` with the
2496 // lever off, and with it on whichever of [`LEAF_SLOTS`] that leaf
2497 // refreshed.
2498 let prev_leaf = self.leaf_hist.first().copied().unwrap_or(LEAF_SLOT);
2499 let last_slot = match i {
2500 0 => anchor_slot,
2501 i => inner
2502 .iter()
2503 .find(|(at, _)| at + 1 == i)
2504 .map_or(prev_leaf, |&(_, slot)| slot),
2505 };
2506 // Alternate the refresh: this leaf takes the leaf slot the
2507 // PREVIOUS leaf did not, which is the one the leaf before that
2508 // wrote and which this frame may still read as `LAST2_FRAME`
2509 // (read before write).
2510 let self_slot = match last2() {
2511 true => LEAF_SLOTS
2512 .into_iter()
2513 .find(|&s| Some(s) != self.leaf_hist.first().copied())
2514 .unwrap_or(LEAF_SLOT),
2515 false => LEAF_SLOT,
2516 };
2517 let last2_slot = last2_of(&self.leaf_hist, last_slot);
2518 let altref_slot = inner
2519 .iter()
2520 .find(|(at, _)| *at > i)
2521 .map_or(next_anchor_slot, |&(_, slot)| slot);
2522 self.leaf_hist.insert(0, self_slot);
2523 self.leaf_hist.truncate(2);
2524 packets.push(self.encode_pyramid_inter(
2525 *order,
2526 picture,
2527 last_slot,
2528 self_slot,
2529 altref_slot,
2530 last2_slot,
2531 true,
2532 Level::Leaf,
2533 pyramid.leaf_q_offset,
2534 &tpl_window(i, false),
2535 &[],
2536 )?);
2537 }
2538 let packet = show_existing(self, next_anchor_slot, arf_order)?;
2539 packets.push(packet);
2540 self.anchor = 1 - self.anchor;
2541 Ok(packets)
2542 }
2543}
2544
2545#[cfg(test)]
2546mod tests {
2547 use super::*;
2548 use std::process::{Command, Stdio};
2549
2550 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
2551 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
2552 /// aomenc gate decodes its stream through ffmpeg and is meaningless
2553 /// without it -- turns it into a hard failure. Without this the require
2554 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
2555 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
2556 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
2557 fn have_ffmpeg() -> bool {
2558 let present = Command::new("ffmpeg")
2559 .arg("-version")
2560 .stdout(Stdio::null())
2561 .stderr(Stdio::null())
2562 .status()
2563 .is_ok_and(|s| s.success());
2564 assert!(
2565 present
2566 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
2567 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
2568 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
2569 );
2570 present
2571 }
2572
2573 fn test_card(width: usize, height: usize, shift: usize) -> Picture {
2574 let mut picture = Picture::grey(width, height);
2575 for y in 0..height {
2576 for x in 0..width {
2577 let sx = (x + shift) % width;
2578 picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16;
2579 }
2580 }
2581 for y in 0..height / 2 {
2582 for x in 0..width / 2 {
2583 let i = y * (width / 2) + x;
2584 picture.u[i] = ((100 + shift * 4) % 256) as u16;
2585 picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16;
2586 }
2587 }
2588 picture
2589 }
2590
2591 /// Drives a whole stream through the facade the way a caller must since
2592 /// it holds one picture of lookahead: every picture through
2593 /// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`].
2594 fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec<Packet> {
2595 let mut packets = Vec::with_capacity(pictures.len());
2596 for (i, picture) in pictures.iter().enumerate() {
2597 packets.extend(
2598 enc.encode_frames(picture)
2599 .unwrap_or_else(|e| panic!("picture {i}: {e}")),
2600 );
2601 }
2602 packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}")));
2603 packets
2604 }
2605
2606 /// [`gop_shape`] prices the frames the pyramid actually CODES: its hidden
2607 /// counts and leaf count match the packets a real run emits, at three
2608 /// pyramid shapes, and the plan [`RateLoop::new`] builds from it spends
2609 /// the run's budget exactly (`gop` frame targets, no more and no less).
2610 ///
2611 /// Both halves matter: a shape that misses a level (the old model priced
2612 /// ONE hidden frame per group when the mid level had made it two) splits
2613 /// the budget by weights that do not add up to the run.
2614 #[test]
2615 fn the_rate_loop_prices_the_frames_the_pyramid_codes() {
2616 let _knobs = crate::speed::knob_read();
2617 let pictures: Vec<Picture> = (0..48).map(|i| test_card(64, 64, i)).collect();
2618 let quarters = Pyramid {
2619 quarter_q_offset: Some(-20),
2620 ..Pyramid::default()
2621 };
2622 let two_level = Pyramid {
2623 mid_q_offset: None,
2624 ..Pyramid::default()
2625 };
2626 for (gop, pyramid) in [
2627 (48, Pyramid::default()),
2628 (12, Pyramid::default()),
2629 (48, quarters),
2630 (48, two_level),
2631 ] {
2632 let config = EncoderConfig {
2633 width: 64,
2634 height: 64,
2635 base_q_idx: 100,
2636 gop,
2637 colour: Colour::Bt709Limited,
2638 tile_cols_log2: 0,
2639 tile_rows_log2: 0,
2640 };
2641 let rate = RateTarget::BytesPerFrame(2_000);
2642 let mut enc = Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap();
2643 let packets = encode_all(&mut enc, &pictures[..gop]);
2644 let coded = |level: Level| packets.iter().filter(|p| p.level == level).count();
2645 let (hidden, leaves) = gop_shape(pyramid, gop);
2646 let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum();
2647 assert_eq!(
2648 (hidden_frames, leaves, 1),
2649 (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)),
2650 "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves"
2651 );
2652 assert_eq!(
2653 hidden_frames + leaves + 1,
2654 gop,
2655 "gop {gop}: every picture is coded exactly once"
2656 );
2657 // The plan adds up: one leaf's target times the run's whole
2658 // weight is the run's whole budget.
2659 let target_bytes = 2_000.0;
2660 let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
2661 let planned = loop_.target[0]
2662 + loop_.target[2]
2663 * (leaves as f64
2664 + hidden
2665 .iter()
2666 .map(|&(o, n)| n as f64 * loop_.weight(o))
2667 .sum::<f64>());
2668 assert!(
2669 (planned - target_bytes * gop as f64).abs() < 1.0,
2670 "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run",
2671 target_bytes * gop as f64
2672 );
2673 }
2674 }
2675
2676 /// A level at its quantizer BOUND hands its unspent bytes to the levels
2677 /// that can still move ([[vorbis-rate-loop-windup]]'s class in the
2678 /// small), and it does so AT ONCE, not once the bound level's frames are
2679 /// all coded: the loop is driven by a synthetic per-level model where the
2680 /// first hidden frame is coded at `raw_q` 0 (past the coder's own 1..=255
2681 /// clamp) and spends half its plan, and the leaves' target must jump to
2682 /// the run's remainder with EVERY remaining hidden frame priced at that
2683 /// measured rate. The old division -- whole remainder over whole
2684 /// remaining weight -- handed most of the shortfall straight back to the
2685 /// hidden slot (which carries most of the pyramid's weight and cannot
2686 /// spend it), so the leaves only saw the surplus at the end of the run,
2687 /// when there was nothing left to code with it.
2688 #[test]
2689 fn a_bound_level_hands_its_unspent_bytes_to_the_others() {
2690 let pyramid = Pyramid::default();
2691 let (gop, target_bytes) = (48usize, 2_000.0);
2692 let (hidden, leaves) = gop_shape(pyramid, gop);
2693 let run_bytes = target_bytes * gop as f64;
2694 let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
2695 let scale0 = rl.target[2];
2696 let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * rl.weight(o)).sum();
2697 // The key codes exactly its plan; the first hidden frame is at the
2698 // floor and spends half of its.
2699 let key_bytes = rl.target[0].round();
2700 rl.update(Level::Key, 0, 100, key_bytes as usize);
2701 let (offset, n0) = hidden[0];
2702 let arf_bytes = (0.5 * scale0 * rl.weight(offset)).round();
2703 rl.update(Level::Arf, offset, 0, arf_bytes as usize);
2704 // Every frame of THAT LEVEL still to come is priced at what the bound
2705 // one measured -- and only that level: its slot-mates (the mid ARF)
2706 // sit at their own offset and are still free to follow the plan.
2707 // Everything else shares the rest.
2708 let want = (run_bytes - key_bytes - arf_bytes * n0 as f64)
2709 / (leaves as f64 + hidden_weight - n0 as f64 * rl.weight(offset));
2710 assert!(
2711 want < scale0 * RateLoop::REPLAN_CLAMP,
2712 "this arm must not reach the windup bound: {want:.1} vs {:.1}",
2713 scale0 * RateLoop::REPLAN_CLAMP
2714 );
2715 assert!(
2716 (rl.target[2] - want).abs() < 1e-6,
2717 "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \
2718 give {:.3})",
2719 rl.target[2],
2720 (run_bytes - key_bytes - arf_bytes)
2721 / (leaves as f64 + hidden_weight - rl.weight(offset))
2722 );
2723 // And the re-plan stays BOUNDED: hidden levels that spend nothing at
2724 // all cannot run the leaves' target away.
2725 let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
2726 rl.update(Level::Key, 0, 100, key_bytes as usize);
2727 for &(offset, n) in &hidden {
2728 for _ in 0..n {
2729 rl.update(Level::Arf, offset, 0, 1);
2730 }
2731 }
2732 assert!(
2733 rl.target[2] <= scale0 * RateLoop::REPLAN_CLAMP + 1e-9,
2734 "the re-plan is unbounded: leaf target {:.1} past {:.1}",
2735 rl.target[2],
2736 scale0 * RateLoop::REPLAN_CLAMP
2737 );
2738 // ... and BOTH ways: a re-plan that reached zero would stop the loop
2739 // dead (`update` returns on a non-positive target).
2740 let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
2741 rl.update(Level::Key, 0, 100, key_bytes as usize);
2742 for &(offset, n) in &hidden {
2743 for _ in 0..n {
2744 rl.update(Level::Arf, offset, 0, 40 * key_bytes as usize);
2745 }
2746 }
2747 assert!(
2748 rl.target[2] >= scale0 * RateLoop::REPLAN_FLOOR - 1e-9,
2749 "the re-plan froze the loop: leaf target {:.1} under {:.1}",
2750 rl.target[2],
2751 scale0 * RateLoop::REPLAN_FLOOR
2752 );
2753 }
2754
2755 /// The mini-GOP layout leaves no short tail group, and leaves the long
2756 /// GOP the fixed rule already coded alone: 47 inter pictures are
2757 /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical),
2758 /// while a 12-picture GOP stops being 8 + 3 (lane-gopad).
2759 #[test]
2760 fn the_mini_gop_layout_leaves_no_short_tail() {
2761 let groups = |remaining: usize, mini_gop: usize, absorb: bool| {
2762 let (mut left, mut out) = (remaining, Vec::new());
2763 while left > 0 {
2764 let g = group_target(left, mini_gop, absorb).min(left);
2765 assert!(g > 0);
2766 out.push(g);
2767 left -= g;
2768 }
2769 out
2770 };
2771 // gop 48: what mini_gop 8 already coded, under either rule.
2772 assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]);
2773 assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]);
2774 // gop 12: 8 + 3 becomes one group of 11.
2775 assert_eq!(groups(11, 8, false), vec![8, 3]);
2776 assert_eq!(groups(11, 8, true), vec![11]);
2777 // A run shorter than a group is one group, as before (the 4-picture
2778 // pin clip).
2779 assert_eq!(groups(3, 8, true), vec![3]);
2780 // No group is ever below half the shape, and none is over 1.5x it.
2781 for mini_gop in 2..=16 {
2782 for remaining in 1..=64 {
2783 for g in groups(remaining, mini_gop, true) {
2784 assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}");
2785 assert!(
2786 g * 2 >= mini_gop || remaining < mini_gop,
2787 "{remaining}/{mini_gop}: short tail {g}"
2788 );
2789 }
2790 }
2791 }
2792 }
2793
2794 /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
2795 /// in order.
2796 fn concat(packets: &[Packet]) -> Vec<u8> {
2797 packets.iter().flat_map(|p| p.data.clone()).collect()
2798 }
2799
2800 /// The facade's latency contract (lane-av1facade, deepened on
2801 /// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold
2802 /// their picture back and return an empty packet, every later call
2803 /// returns the packet of the picture that many frames earlier, and
2804 /// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets
2805 /// exactly one non-empty packet per picture, `depth - 1` calls later.
2806 #[test]
2807 fn one_in_one_out_delayed_by_the_lookahead_depth() {
2808 let _knobs = crate::speed::knob_read();
2809 let config = EncoderConfig {
2810 width: 64,
2811 height: 64,
2812 base_q_idx: 100,
2813 gop: 2,
2814 colour: Colour::Bt709Limited,
2815 tile_cols_log2: 0,
2816 tile_rows_log2: 0,
2817 };
2818 let delay = crate::encode::tpl_depth() as u64 - 1;
2819 let pictures = delay + 5;
2820 let mut enc = Av1Encoder::new(config).unwrap();
2821 for t in 0..pictures {
2822 let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
2823 if t < delay {
2824 assert!(packet.data.is_empty(), "call {t} holds its picture back");
2825 continue;
2826 }
2827 assert!(!packet.data.is_empty(), "picture {t}: empty packet");
2828 assert_eq!(packet.order, t - delay, "picture {t}: order");
2829 }
2830 let tail = enc.flush().unwrap();
2831 assert_eq!(tail.len() as u64, delay, "flush yields the whole queue");
2832 for (i, p) in tail.iter().enumerate() {
2833 assert_eq!(
2834 p.order,
2835 pictures - delay + i as u64,
2836 "flushed packet {i}: order"
2837 );
2838 assert!(!p.data.is_empty(), "flushed packet {i}: empty");
2839 }
2840 assert!(enc.flush().unwrap().is_empty(), "nothing is held twice");
2841 }
2842
2843 /// A screen-like card: hard-edged 4-pixel bands of two flat luma values
2844 /// with a moving block over the lower half — few colours per 16x16 block
2845 /// at high variance, which is exactly what
2846 /// [`crate::encode::picture_is_screen`] separates. Used unforced, so the
2847 /// gate below runs the real detector rather than an override.
2848 fn screen_card(width: usize, height: usize, shift: usize) -> Picture {
2849 let mut picture = Picture::grey(width, height);
2850 for y in 0..height {
2851 for x in 0..width {
2852 let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 };
2853 let over = y >= height / 2 && (x + shift) % width < width / 3;
2854 picture.y[y * width + x] = if over { 128 } else { band };
2855 }
2856 }
2857 picture
2858 }
2859
2860 /// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on
2861 /// lane-av1pyrdef): the streaming facade — what the editor's export
2862 /// drives — codes byte for byte what [`crate::encode::encode_sequence`]
2863 /// codes, which is the path the BD gate measures. Both now drive ONE
2864 /// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the
2865 /// identity is by construction; this pins it anyway, over both content
2866 /// classes the content gate splits:
2867 ///
2868 /// * film-like (the gate's own clip when the fixture is there, a
2869 /// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the
2870 /// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two
2871 /// paths' whole streams are identical;
2872 /// * screen-like: the content gate drops BOTH paths back to flat, one
2873 /// packet per picture, identical frame by frame as well as whole.
2874 ///
2875 /// Never skipped, since a skipped identity gate is the defect it is meant
2876 /// to catch.
2877 #[test]
2878 fn the_facade_codes_the_same_bytes_as_encode_sequence() {
2879 let _knobs = crate::speed::knob_read();
2880 let frames = 12usize;
2881 let film = h264_clip_frames(640, 384, frames).unwrap_or_else(|| {
2882 eprintln!("no h264 clip: the facade identity gate runs on a synthetic card");
2883 (0..frames).map(|t| test_card(64, 64, t)).collect()
2884 });
2885 let screen: Vec<Picture> = (0..frames).map(|t| screen_card(64, 64, t)).collect();
2886 let pyramid = Pyramid::from_env().expect("the pyramid is this build's default");
2887 for (content, pictures, is_screen) in [("film", &film, false), ("screen", &screen, true)] {
2888 let (width, height) = (pictures[0].width, pictures[0].height);
2889 for q in [150u8, 60] {
2890 let config = EncoderConfig {
2891 width,
2892 height,
2893 base_q_idx: q,
2894 // One key frame then all inter, which is
2895 // `encode_sequence`'s only shape, and the gate's recipe.
2896 gop: frames,
2897 // `encode_sequence` writes an unspecified colour config.
2898 colour: Colour::Unspecified,
2899 tile_cols_log2: 0,
2900 tile_rows_log2: 0,
2901 };
2902 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
2903 let mut packets = Vec::new();
2904 for picture in pictures {
2905 packets.extend(enc.encode_frames(picture).unwrap());
2906 }
2907 packets.extend(enc.flush().unwrap());
2908 assert_eq!(
2909 enc.pyramid().is_none(),
2910 is_screen,
2911 "{content} q={q}: the content gate read this clip the other way round"
2912 );
2913 let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap();
2914 assert_eq!(
2915 (
2916 packets.iter().map(|p| p.data.len()).sum::<usize>(),
2917 concat(&packets)
2918 ),
2919 (sequence.stream.len(), sequence.stream.clone()),
2920 "{content} q={q}: the facade's stream is not the sequence path's"
2921 );
2922 assert_eq!(
2923 sequence.frames.len(),
2924 frames,
2925 "{content} q={q}: one entry per picture, in display order"
2926 );
2927 if is_screen {
2928 assert_eq!(
2929 packets.len(),
2930 frames,
2931 "{content} q={q}: one packet per picture"
2932 );
2933 for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() {
2934 let cropped = crate::encode::crop_encoded(coded, width, height);
2935 assert_eq!(
2936 (packet.data.len(), packet.data.clone()),
2937 (cropped.stream.len(), cropped.stream.clone()),
2938 "{content} q={q} frame {i}: the facade's bytes are not the \
2939 sequence path's"
2940 );
2941 }
2942 } else {
2943 assert!(
2944 packets.iter().any(|p| p.level == Level::Arf),
2945 "{content} q={q}: a non-screen stream coded no hidden frame"
2946 );
2947 }
2948 }
2949 }
2950 }
2951
2952 /// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by
2953 /// the caller but applied only to camera material. Over screen content
2954 /// the encoder must drop back to the flat path and code byte for byte
2955 /// what a flat encoder codes — that is what keeps the BD gate's screen
2956 /// row identical to the flat baseline — and over non-screen content the
2957 /// same request must still reorder (class `gate-blind-to-feature`: a gate
2958 /// that only checked the screen half would pass with the pyramid deleted).
2959 #[test]
2960 fn the_content_gate_keeps_screen_streams_flat() {
2961 let _knobs = crate::speed::knob_read();
2962 let frames = 8usize;
2963 let pictures: Vec<Picture> = (0..frames).map(|t| test_card(64, 64, t)).collect();
2964 let config = EncoderConfig {
2965 width: 64,
2966 height: 64,
2967 base_q_idx: 120,
2968 gop: frames,
2969 colour: Colour::Unspecified,
2970 tile_cols_log2: 0,
2971 tile_rows_log2: 0,
2972 };
2973 crate::encode::force_screen(Some(true));
2974 let mut flat = Av1Encoder::new(config).unwrap();
2975 let flat_packets = encode_all(&mut flat, &pictures);
2976 let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
2977 let gated_packets = encode_all(&mut gated, &pictures);
2978 assert_eq!(
2979 gated.pyramid(),
2980 None,
2981 "the gate left a screen stream on the pyramid"
2982 );
2983 assert_eq!(
2984 concat(&gated_packets),
2985 concat(&flat_packets),
2986 "a screen stream's bytes are not the flat path's"
2987 );
2988 crate::encode::force_screen(Some(false));
2989 let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
2990 let kept_packets = encode_all(&mut kept, &pictures);
2991 assert_eq!(
2992 kept.pyramid(),
2993 Some(Pyramid::default()),
2994 "the gate ate a film stream"
2995 );
2996 assert!(
2997 kept_packets.iter().any(|p| p.level == Level::Arf),
2998 "a non-screen stream coded no hidden frame"
2999 );
3000 crate::encode::force_screen(None);
3001 }
3002
3003 /// A key frame every `gop` pictures, inter otherwise — checked against
3004 /// what the facade itself reports, and (below) against what `ffprobe`
3005 /// reads back out of the coded bytes.
3006 #[test]
3007 fn gop_cadence_is_honored() {
3008 let _knobs = crate::speed::knob_read();
3009 let config = EncoderConfig {
3010 width: 64,
3011 height: 64,
3012 base_q_idx: 100,
3013 gop: 3,
3014 colour: Colour::Unspecified,
3015 tile_cols_log2: 0,
3016 tile_rows_log2: 0,
3017 };
3018 let mut enc = Av1Encoder::new(config).unwrap();
3019 let pictures: Vec<Picture> = (0..7).map(|t| test_card(64, 64, t)).collect();
3020 let keys: Vec<bool> = encode_all(&mut enc, &pictures)
3021 .iter()
3022 .map(|p| p.key)
3023 .collect();
3024 assert_eq!(keys, vec![true, false, false, true, false, false, true]);
3025 }
3026
3027 fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {
3028 let path = std::env::temp_dir().join(format!(
3029 "ec-av1-facade-probe-{}-{}.obu",
3030 std::process::id(),
3031 std::ptr::addr_of!(stream) as usize
3032 ));
3033 std::fs::write(&path, stream).expect("writing the probe stream");
3034 let out = Command::new("ffprobe")
3035 .args([
3036 "-v",
3037 "error",
3038 "-f",
3039 "obu",
3040 "-select_streams",
3041 "v:0",
3042 "-show_entries",
3043 "frame=key_frame,width,height",
3044 "-of",
3045 "csv=p=0",
3046 ])
3047 .arg(&path)
3048 .output()
3049 .expect("ffprobe failed to run");
3050 let _ = std::fs::remove_file(&path);
3051 assert!(
3052 out.status.success(),
3053 "ffprobe refused the stream: {}",
3054 String::from_utf8_lossy(&out.stderr)
3055 );
3056 String::from_utf8_lossy(&out.stdout)
3057 .lines()
3058 .map(|line| {
3059 let mut f = line.trim().split(',');
3060 let key: u32 = f.next().unwrap().parse().unwrap();
3061 let width: u32 = f.next().unwrap().parse().unwrap();
3062 let height: u32 = f.next().unwrap().parse().unwrap();
3063 (key == 1, width, height)
3064 })
3065 .collect()
3066 }
3067
3068 fn ffprobe_colour(stream: &[u8]) -> String {
3069 let path = std::env::temp_dir().join(format!(
3070 "ec-av1-facade-colour-probe-{}-{}.obu",
3071 std::process::id(),
3072 std::ptr::addr_of!(stream) as usize
3073 ));
3074 std::fs::write(&path, stream).expect("writing the probe stream");
3075 let out = Command::new("ffprobe")
3076 .args([
3077 "-v",
3078 "error",
3079 "-f",
3080 "obu",
3081 "-select_streams",
3082 "v:0",
3083 "-show_entries",
3084 "stream=color_primaries,color_transfer,color_space,color_range",
3085 "-of",
3086 "csv=p=0",
3087 ])
3088 .arg(&path)
3089 .output()
3090 .expect("ffprobe failed to run");
3091 let _ = std::fs::remove_file(&path);
3092 assert!(
3093 out.status.success(),
3094 "ffprobe refused the stream: {}",
3095 String::from_utf8_lossy(&out.stderr)
3096 );
3097 String::from_utf8_lossy(&out.stdout).trim().to_string()
3098 }
3099
3100 /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)
3101 /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that
3102 /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and
3103 /// coded size confirm what the facade already reported.
3104 #[test]
3105 fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
3106 let _knobs = crate::speed::knob_read();
3107 if !have_ffmpeg() {
3108 eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg");
3109 return;
3110 }
3111 let (width, height) = (96usize, 96usize);
3112 let config = EncoderConfig {
3113 width,
3114 height,
3115 base_q_idx: 120,
3116 gop: 15,
3117 colour: Colour::Bt709Limited,
3118 tile_cols_log2: 0,
3119 tile_rows_log2: 0,
3120 };
3121 let mut enc = Av1Encoder::new(config).unwrap();
3122 assert_eq!(enc.display_size(), (width, height));
3123 let (coded_w, coded_h) = enc.coded_size();
3124 assert_eq!(
3125 (coded_w, coded_h),
3126 (
3127 width.next_multiple_of(SUPERBLOCK),
3128 height.next_multiple_of(SUPERBLOCK)
3129 )
3130 );
3131
3132 let pictures: Vec<Picture> = (0..30).map(|t| test_card(width, height, t)).collect();
3133 let packets: Vec<Packet> = encode_all(&mut enc, &pictures);
3134 let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect();
3135 assert_eq!(
3136 packets.iter().map(|p| p.key).collect::<Vec<_>>(),
3137 expect_key,
3138 "facade's own key/inter flags"
3139 );
3140
3141 let stream = concat(&packets);
3142 let frames = ffprobe_frames(&stream);
3143 assert_eq!(frames.len(), 30, "ffprobe frame count");
3144 for (t, (key, w, h)) in frames.iter().enumerate() {
3145 assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag");
3146 assert_eq!(
3147 (*w, *h),
3148 (width as u32, height as u32),
3149 "picture {t}: ffprobe reports the true (display) size, not the padded coded one"
3150 );
3151 }
3152 }
3153
3154 /// The configured colour properties are what `ffprobe` reports back,
3155 /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it
3156 /// is the default a player assumes and the one this test would silently
3157 /// pass without wiring for (`ffprobe` reports "unknown" for the
3158 /// hardcoded "unspecified" this crate wrote before the facade existed,
3159 /// which is a visibly different string).
3160 #[test]
3161 fn bt709_limited_colour_is_reported_by_ffprobe() {
3162 let _knobs = crate::speed::knob_read();
3163 if !have_ffmpeg() {
3164 eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg");
3165 return;
3166 }
3167 let config = EncoderConfig {
3168 width: 64,
3169 height: 64,
3170 base_q_idx: 100,
3171 gop: 4,
3172 colour: Colour::Bt709Limited,
3173 tile_cols_log2: 0,
3174 tile_rows_log2: 0,
3175 };
3176 let mut enc = Av1Encoder::new(config).unwrap();
3177 let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]);
3178 let colour = ffprobe_colour(&packets[0].data);
3179 assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields");
3180 }
3181
3182 /// The same, for BT.601: a different set of CICP integers must produce a
3183 /// different string, or the wiring could be a no-op that happens to read
3184 /// as BT.709 for every input.
3185 #[test]
3186 fn bt601_limited_colour_is_reported_by_ffprobe() {
3187 let _knobs = crate::speed::knob_read();
3188 if !have_ffmpeg() {
3189 eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg");
3190 return;
3191 }
3192 let config = EncoderConfig {
3193 width: 64,
3194 height: 64,
3195 base_q_idx: 100,
3196 gop: 4,
3197 colour: Colour::Bt601Limited,
3198 tile_cols_log2: 0,
3199 tile_rows_log2: 0,
3200 };
3201 let mut enc = Av1Encoder::new(config).unwrap();
3202 let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]);
3203 let colour = ffprobe_colour(&packets[0].data);
3204 assert_eq!(
3205 colour, "tv,smpte170m,smpte170m,smpte170m",
3206 "ffprobe colour fields"
3207 );
3208 }
3209
3210 /// A frame whose size does not match the encoder's configured geometry
3211 /// is refused by name.
3212 #[test]
3213 fn geometry_mismatch_is_refused() {
3214 let _knobs = crate::speed::knob_read();
3215 let config = EncoderConfig {
3216 width: 64,
3217 height: 64,
3218 base_q_idx: 100,
3219 gop: 4,
3220 colour: Colour::Bt709Limited,
3221 tile_cols_log2: 0,
3222 tile_rows_log2: 0,
3223 };
3224 let mut enc = Av1Encoder::new(config).unwrap();
3225 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
3226 assert!(err.to_string().contains("64x64"), "{err}");
3227 }
3228
3229 /// `gop == 0` is refused at construction, not the first `encode()` call.
3230 #[test]
3231 fn zero_gop_is_refused() {
3232 let _knobs = crate::speed::knob_read();
3233 let config = EncoderConfig {
3234 width: 64,
3235 height: 64,
3236 base_q_idx: 100,
3237 gop: 0,
3238 colour: Colour::Bt709Limited,
3239 tile_cols_log2: 0,
3240 tile_rows_log2: 0,
3241 };
3242 let err = Av1Encoder::new(config).unwrap_err();
3243 assert!(err.to_string().contains("gop"), "{err}");
3244 }
3245
3246 /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget`
3247 /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down
3248 /// to this facade's own input size, and re-coded through the facade so the
3249 /// rate-target surface is exercised at the entry point a caller actually
3250 /// drives.
3251 fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> {
3252 if !have_ffmpeg() {
3253 return None;
3254 }
3255 // lane-av1speed3: the wall tables below are read on REAL film as
3256 // well as on the colour-bar fixture (`bars` vs `film` in the BD
3257 // gate's own vocabulary), and the film crop lives outside the repo --
3258 // `EC_AV1_WALL_CLIP` names it. Unset everywhere else, so every other
3259 // caller still gets the fixture.
3260 let clip = match std::env::var("EC_AV1_WALL_CLIP") {
3261 Ok(p) => std::path::PathBuf::from(p),
3262 Err(_) => std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
3263 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4"),
3264 };
3265 if !clip.exists() {
3266 return None;
3267 }
3268 let out = Command::new("ffmpeg")
3269 .args(["-v", "error", "-i", clip.to_str().unwrap()])
3270 .args(["-frames:v", &frames.to_string()])
3271 .args(["-vf", &format!("scale={width}:{height}")])
3272 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
3273 .output()
3274 .expect("ffmpeg failed to run");
3275 assert!(
3276 out.status.success(),
3277 "{}",
3278 String::from_utf8_lossy(&out.stderr)
3279 );
3280 let (luma, chroma) = (width * height, width * height / 4);
3281 let frame_len = luma + 2 * chroma;
3282 assert_eq!(
3283 out.stdout.len(),
3284 frame_len * frames,
3285 "expected {frames} 4:2:0 frames"
3286 );
3287 Some(
3288 (0..frames)
3289 .map(|i| {
3290 let bytes = &out.stdout[i * frame_len..][..frame_len];
3291 Picture {
3292 width,
3293 height,
3294 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
3295 u: bytes[luma..luma + chroma]
3296 .iter()
3297 .map(|&v| u16::from(v))
3298 .collect(),
3299 v: bytes[luma + chroma..]
3300 .iter()
3301 .map(|&v| u16::from(v))
3302 .collect(),
3303 }
3304 })
3305 .collect(),
3306 )
3307 }
3308
3309 /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total
3310 /// coded size within ±20% of `frames * target` once the first few
3311 /// frames' settling has been discarded (the key frame's own reference
3312 /// state and the controller's first couple of steps).
3313 #[test]
3314 fn bytes_per_frame_target_settles_within_20_percent() {
3315 let _knobs = crate::speed::knob_read();
3316 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
3317 eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture");
3318 return;
3319 };
3320 let target_bytes = 4_000u32;
3321 let config = EncoderConfig {
3322 width: 640,
3323 height: 384,
3324 base_q_idx: 100,
3325 gop: 24,
3326 colour: Colour::Bt709Limited,
3327 tile_cols_log2: 0,
3328 tile_rows_log2: 0,
3329 };
3330 let mut enc =
3331 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
3332 let sizes: Vec<usize> = encode_all(&mut enc, &pictures)
3333 .iter()
3334 .map(|p| p.data.len())
3335 .collect();
3336 // Discard the key frame (always far larger than an inter target) and
3337 // the next 4 inter frames the loop needs to step toward it.
3338 let settled = &sizes[5..];
3339 let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64;
3340 let low = f64::from(target_bytes) * 0.8;
3341 let high = f64::from(target_bytes) * 1.2;
3342 assert!(
3343 mean >= low && mean <= high,
3344 "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}"
3345 );
3346 }
3347
3348 /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±5% of the
3349 /// target over 48 frames of a real clip, flat and under a pyramid alike,
3350 /// across a 5x span of bitrates. This is the accuracy claim of the
3351 /// target-bitrate mode: no two-pass, no lookahead, just each frame's size
3352 /// predicted from the previous frame of its own level, one clamped
3353 /// proportional step, and the level model
3354 /// ([`WEIGHT_LEVEL_GAIN`]) that says how the run's budget splits.
3355 ///
3356 /// The tolerance was ±10% and every arm was inside ±3.0% when it was cut
3357 /// to ±5%; the worst arm is the 2 Mbit/s pyramid at -4.4%, which is the
3358 /// ENCODER'S OWN CEILING showing through, not the loop's aim: at that
3359 /// rate the hidden slot already codes at `q_idx` 1 (its 22863 bytes a
3360 /// frame are the same at 1.5 and 2 Mbit/s) and the leaves sit at 1 + 12
3361 /// `leaf_q_offset`, so this clip cannot be made to spend much past
3362 /// 2.4 Mbit/s under the default pyramid however the budget is split.
3363 #[test]
3364 fn bitrate_target_lands_within_5_percent_over_48_frames() {
3365 let _knobs = crate::speed::knob_read();
3366 let (width, height, frames) = (640usize, 384usize, 48usize);
3367 let Some(pictures) = h264_clip_frames(width, height, frames) else {
3368 eprintln!(
3369 "SKIP bitrate_target_lands_within_5_percent_over_48_frames: no ffmpeg/fixture"
3370 );
3371 return;
3372 };
3373 let fps = 24.0;
3374 for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] {
3375 let config = EncoderConfig {
3376 width,
3377 height,
3378 base_q_idx: 100,
3379 gop: frames,
3380 colour: Colour::Bt709Limited,
3381 tile_cols_log2: 0,
3382 tile_rows_log2: 0,
3383 };
3384 let rate = RateTarget::Bitrate {
3385 bits_per_second,
3386 frames_per_second: fps,
3387 };
3388 for pyramid in [None, Some(Pyramid::default())] {
3389 let mut enc = match pyramid {
3390 None => Av1Encoder::with_rate_target(config, rate).unwrap(),
3391 Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(),
3392 };
3393 let targets = enc.rate_loop.as_ref().unwrap().target;
3394 let mut coded = 0usize;
3395 // Per level, so a miss reads as WHICH level's model is off
3396 // rather than as one aggregate percentage.
3397 let (mut bytes, mut count) = ([0usize; 4], [0usize; 4]);
3398 let mut take = |packets: Vec<Packet>| {
3399 for packet in packets {
3400 coded += packet.data.len();
3401 let i = match packet.level {
3402 Level::Key => 0,
3403 Level::Arf => 1,
3404 Level::Leaf => 2,
3405 Level::ShowExisting => 3,
3406 };
3407 bytes[i] += packet.data.len();
3408 count[i] += 1;
3409 }
3410 };
3411 for picture in &pictures {
3412 take(enc.encode_frames(picture).unwrap());
3413 }
3414 take(enc.flush().unwrap());
3415 let seconds = frames as f64 / fps;
3416 let achieved = coded as f64 * 8.0 / seconds;
3417 let error = achieved / f64::from(bits_per_second) - 1.0;
3418 let per = |i: usize| match count[i] {
3419 0 => "-".to_string(),
3420 n => format!("{n}x{}", bytes[i] / n),
3421 };
3422 eprintln!(
3423 "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \
3424 = {achieved:.0} bps ({:+.1}%) | targets {:.0}/{:.0}/{:.0} \
3425 coded key {} arf {} leaf {}",
3426 pyramid.is_some(),
3427 100.0 * error,
3428 targets[0],
3429 targets[1],
3430 targets[2],
3431 per(0),
3432 per(1),
3433 per(2),
3434 );
3435 assert!(
3436 error.abs() <= 0.05,
3437 "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \
3438 (pyramid {})",
3439 100.0 * error,
3440 pyramid.is_some(),
3441 );
3442 }
3443 }
3444 }
3445
3446 /// The `BytesPerFrame` controller's own windup bound: no frame's coded
3447 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
3448 /// clip's full range of content (so a scene cut can't be the one frame
3449 /// that breaks the bound).
3450 ///
3451 /// The SEEDING frame is the one exemption ([`RateLoop::update`]): a slot
3452 /// that has coded nothing yet is still sitting on the caller's
3453 /// `base_q_idx` guess, and its first step is the acquisition jump, not
3454 /// windup. Exactly one frame is exempt -- the loop below asserts the
3455 /// bound on every frame after it, which is where a scene cut would
3456 /// break it.
3457 #[test]
3458 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
3459 let _knobs = crate::speed::knob_read();
3460 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
3461 eprintln!(
3462 "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture"
3463 );
3464 return;
3465 };
3466 let config = EncoderConfig {
3467 width: 640,
3468 height: 384,
3469 base_q_idx: 100,
3470 gop: 24,
3471 colour: Colour::Bt709Limited,
3472 tile_cols_log2: 0,
3473 tile_rows_log2: 0,
3474 };
3475 let mut enc =
3476 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
3477 let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
3478 // The first frame this encoder EMITS is several `encode_frames` calls
3479 // in (the lookahead queue holds the earlier ones), so the seeding
3480 // step is not frame zero -- it is the first frame `q` moves at all.
3481 let mut seeded = false;
3482 let mut seed_frame = None;
3483 for (frame, picture) in pictures.iter().enumerate() {
3484 enc.encode_frames(picture).unwrap();
3485 let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
3486 let step = (i32::from(q) - i32::from(prev_q)).abs();
3487 if step > 0 && !seeded {
3488 seeded = true;
3489 seed_frame = Some(frame);
3490 } else {
3491 assert!(
3492 f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
3493 "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp",
3494 RateLoop::STEP_CLAMP
3495 );
3496 }
3497 prev_q = q;
3498 }
3499 assert!(
3500 seed_frame.is_some(),
3501 "the controller never steered at all -- the bound below is vacuous"
3502 );
3503 }
3504
3505 fn psnr(a: &[u16], b: &[u16]) -> f64 {
3506 let squared: f64 = a
3507 .iter()
3508 .zip(b)
3509 .map(|(&x, &y)| {
3510 let d = f64::from(x) - f64::from(y);
3511 d * d
3512 })
3513 .sum();
3514 if squared == 0.0 {
3515 return f64::INFINITY;
3516 }
3517 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
3518 }
3519
3520 /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one
3521 /// entry per coded frame, in order — this facade's own equivalent of
3522 /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
3523 /// PSNR check needs the decoded pixels, not just the coded byte count.
3524 fn ffmpeg_decode_planes(
3525 stream: &[u8],
3526 width: usize,
3527 height: usize,
3528 ) -> Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> {
3529 let path = std::env::temp_dir().join(format!(
3530 "ec-av1-facade-rate-decode-{}-{}.obu",
3531 std::process::id(),
3532 std::ptr::addr_of!(stream) as usize
3533 ));
3534 std::fs::write(&path, stream).expect("writing the decode probe stream");
3535 let out = Command::new("ffmpeg")
3536 .args(["-v", "error", "-f", "obu", "-i"])
3537 .arg(&path)
3538 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
3539 .output()
3540 .expect("ffmpeg failed to run");
3541 let _ = std::fs::remove_file(&path);
3542 assert!(
3543 out.status.success(),
3544 "{}",
3545 String::from_utf8_lossy(&out.stderr)
3546 );
3547 let (luma, chroma) = (width * height, width * height / 4);
3548 let frame_len = luma + 2 * chroma;
3549 out.stdout
3550 .chunks_exact(frame_len)
3551 .map(|f| {
3552 (
3553 f[..luma].to_vec(),
3554 f[luma..luma + chroma].to_vec(),
3555 f[luma + chroma..].to_vec(),
3556 )
3557 })
3558 .collect()
3559 }
3560
3561 /// [`ffmpeg_decode_planes`]' luma half, which is what most rows compare.
3562 fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
3563 ffmpeg_decode_planes(stream, width, height)
3564 .into_iter()
3565 .map(|(y, _, _)| y)
3566 .collect()
3567 }
3568
3569 /// lane-palw: OUR encoder's own witness for the writer half of the
3570 /// palette on-screen defect. `screen_card` at 384x152 is 38 mi rows tall,
3571 /// so the bottom superblock row's palette blocks hang 8 luma rows off the
3572 /// mi grid: spec 5.11.50 codes their colour-index map over the ON-SCREEN
3573 /// corner only and replicates it outward, and the writer used to code the
3574 /// full block grid -- symbols a conformant decoder never reads, so
3575 /// ffmpeg/dav1d desynced the rest of the tile while our own trial decode
3576 /// (unclamped on both sides) agreed with itself. Class
3577 /// `writer-phantom-units-past-edge`.
3578 ///
3579 /// Driven through the ENTRY SURFACE, `Av1Encoder` (what the editor's
3580 /// export calls), and compared on EVERY plane -- a chroma palette map is
3581 /// cut by the same edge. `palette_cut_maps_written` is asserted non-zero
3582 /// so the row cannot pass on a stream that cuts no palette map (class
3583 /// gate-blind-to-feature).
3584 #[test]
3585 fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() {
3586 const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg";
3587 let _knobs = crate::speed::knob_read();
3588 let _gate_lock = crate::stream::tests::lock_gate_counters();
3589 let (width, height) = (384usize, 152usize);
3590 // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at
3591 // most two luma values, so the palette arm wins across the WHOLE
3592 // frame -- including the bottom superblock row, whose 16x16 blocks at
3593 // y=144 and 32x32 blocks at y=128 hang past the 152-row mi grid.
3594 // `screen_card`'s 4-px bands fire only 9 palettes here and none of
3595 // them at the cut edge (class gate-blind-to-feature).
3596 let card = |shift: usize| -> Picture {
3597 let mut picture = Picture::grey(width, height);
3598 for y in 0..height {
3599 for x in 0..width {
3600 let cell = ((x + shift) / 8 + y / 8) % 2;
3601 picture.y[y * width + x] = if cell == 0 { 40 } else { 200 };
3602 }
3603 }
3604 picture
3605 };
3606 let sources: Vec<Picture> = (0..2).map(|t| card(t * 16)).collect();
3607 let config = EncoderConfig {
3608 width,
3609 height,
3610 base_q_idx: 60,
3611 gop: 2,
3612 colour: Colour::Bt709Limited,
3613 tile_cols_log2: 0,
3614 tile_rows_log2: 0,
3615 };
3616 let mut enc = Av1Encoder::new(config).unwrap();
3617 crate::tile::reset_palette_cut_maps_written();
3618 let mut stream = Vec::new();
3619 for packet in encode_all(&mut enc, &sources) {
3620 stream.extend_from_slice(&packet.data);
3621 }
3622 eprintln!(
3623 "{NAME}: {} cut colour-index maps written",
3624 crate::tile::palette_cut_maps_written()
3625 );
3626 assert!(
3627 crate::tile::palette_cut_maps_written() > 0,
3628 "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind"
3629 );
3630 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3631 assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames");
3632 if !have_ffmpeg() {
3633 eprintln!("SKIP the ffmpeg half of {NAME}: no ffmpeg");
3634 return;
3635 }
3636 let theirs = ffmpeg_decode_planes(&stream, width, height);
3637 assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames");
3638 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3639 for (plane, got, want) in [("luma", &a.y, &b.0), ("U", &a.u, &b.1), ("V", &a.v, &b.2)] {
3640 let got: Vec<u8> = got.iter().map(|&v| v as u8).collect();
3641 if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) {
3642 let w = if plane == "luma" { width } else { width / 2 };
3643 panic!(
3644 "{NAME}: frame {i} {plane} differs first at ({}, {}): ours {} vs ffmpeg {}",
3645 at % w,
3646 at / w,
3647 got[at],
3648 want[at],
3649 );
3650 }
3651 assert_eq!(
3652 got.len(),
3653 want.len(),
3654 "{NAME}: frame {i} {plane} is {} samples, ffmpeg's is {}",
3655 got.len(),
3656 want.len()
3657 );
3658 }
3659 }
3660 }
3661
3662 /// A pyramid stream reorders pictures: the hidden `ALTREF` of each
3663 /// mini-GOP is coded before the leaves that precede it in display order,
3664 /// and a `show_existing_frame` header puts it back. This pins the shape
3665 /// (one packet per source picture plus one `show_existing_frame` per
3666 /// group, `dts` monotone, `order` NOT monotone) and then decodes the
3667 /// whole stream through OUR decoder and through ffmpeg/dav1d and requires
3668 /// the two display-order outputs to agree sample for sample — the
3669 /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never
3670 /// output, or output twice, or output in the wrong position, changes the
3671 /// display-order list and fails here.
3672 #[test]
3673 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
3674 // `take_ref_frame_hits` is a process-global counter: a reader-locked
3675 // sibling encoding at the same time zeroes it between our encode and
3676 // our read (seen once: LAST 0 GOLDEN 0 ALTREF 0), so this takes the
3677 // exclusive lock.
3678 let _knobs = crate::speed::knob_write();
3679 pyramid_round_trip(
3680 Pyramid {
3681 mini_gop: 4,
3682 mid_q_offset: None,
3683 ..Pyramid::default()
3684 },
3685 2,
3686 );
3687 }
3688
3689 /// The same round trip over a THREE-level group (`mid_q_offset`): each
3690 /// mini-GOP now codes two hidden frames -- the top ARF at the group's
3691 /// last picture and the mid ARF at the middle of the leaf run -- and
3692 /// re-outputs both with `show_existing_frame`, so a mid frame emitted in
3693 /// the wrong display position, or twice, fails the display-order compare
3694 /// against ffmpeg exactly as a top ARF does.
3695 #[test]
3696 fn a_three_level_pyramid_stream_decodes_in_display_order() {
3697 let _knobs = crate::speed::knob_write();
3698 pyramid_round_trip(
3699 Pyramid {
3700 mini_gop: 8,
3701 mid_q_offset: Some(-8),
3702 ..Pyramid::default()
3703 },
3704 2,
3705 );
3706 }
3707
3708 /// The same round trip over a FOUR-level group
3709 /// ([`Pyramid::quarter_q_offset`]): a mini-GOP of eight now codes four
3710 /// hidden frames -- the top ARF at picture 8, the mid at 4 and the two
3711 /// quarters at 2 and 6 -- each re-output by its own
3712 /// `show_existing_frame`. Every leaf reads a different pair of DPB slots
3713 /// than it did at three levels, so a slot map that lets one level
3714 /// overwrite a picture another is still reading shows up here as a
3715 /// display-order mismatch against ffmpeg.
3716 #[test]
3717 fn a_four_level_pyramid_stream_decodes_in_display_order() {
3718 let _knobs = crate::speed::knob_write();
3719 pyramid_round_trip(
3720 Pyramid {
3721 mini_gop: 8,
3722 mid_q_offset: Some(-8),
3723 quarter_q_offset: Some(4),
3724 ..Pyramid::default()
3725 },
3726 4,
3727 );
3728 }
3729
3730 /// [`Pyramid::key_q_offset`] reaches the key frame: the whole run reads
3731 /// the key, so an offset that never arrived would be invisible in the BD
3732 /// table except as "no change" (class symbol-consumption-gap). A finer
3733 /// key must cost strictly more bytes than the same picture at base q.
3734 #[test]
3735 fn the_key_q_offset_reaches_the_key_frame() {
3736 let _knobs = crate::speed::knob_read();
3737 crate::encode::force_screen(Some(false));
3738 let key_bytes = |offset: i16| {
3739 let config = EncoderConfig {
3740 width: 128,
3741 height: 128,
3742 base_q_idx: 120,
3743 gop: 32,
3744 colour: Colour::Bt709Limited,
3745 tile_cols_log2: 0,
3746 tile_rows_log2: 0,
3747 };
3748 let pyramid = Pyramid {
3749 key_q_offset: offset,
3750 ..Pyramid::default()
3751 };
3752 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
3753 let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap();
3754 let key = packets
3755 .iter()
3756 .find(|p| p.level == Level::Key)
3757 .expect("key frame");
3758 key.data.len()
3759 };
3760 let (base, finer) = (key_bytes(0), key_bytes(-48));
3761 eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes");
3762 assert!(
3763 finer > base,
3764 "key_q_offset -48 did not reach the key frame ({finer} <= {base})"
3765 );
3766 }
3767
3768 /// lane-last2's witness: a clip whose pictures ALTERNATE between two
3769 /// textures, so for every leaf the picture two back is an exact match and
3770 /// the one before it (`LAST_FRAME`) is not. With the lever on, the leaf
3771 /// chain alternates its refresh over [`LEAF_SLOTS`] and names the older
3772 /// slot `LAST2_FRAME`; blocks must actually be CODED off it
3773 /// ([[gate-blind-to-feature]]: a slot that is retained but never chosen
3774 /// proves only that the bookkeeping compiles), the stream must decode
3775 /// sample-exact through OUR decoder and through ffmpeg, and the hidden
3776 /// frames must still come out in display order. With the lever OFF the
3777 /// same clip codes ZERO `LAST2` blocks, which is what makes the counter a
3778 /// measurement of this lane and not of the reference set we already had.
3779 #[test]
3780 fn a_leaf_predicts_off_last2_when_the_picture_two_back_matches() {
3781 let _knobs = crate::speed::knob_write();
3782 crate::encode::force_screen(Some(false));
3783 let (width, height) = (128usize, 128usize);
3784 let sources: Vec<Picture> = (0..9)
3785 .map(|t| test_card(width, height, (t % 2) * 24))
3786 .collect();
3787 let run = |on: bool| -> ([usize; 8], Vec<u8>, Vec<Packet>) {
3788 set_last2(Some(on));
3789 let config = EncoderConfig {
3790 width,
3791 height,
3792 base_q_idx: 120,
3793 gop: 32,
3794 colour: Colour::Bt709Limited,
3795 tile_cols_log2: 0,
3796 tile_rows_log2: 0,
3797 };
3798 let pyramid = Pyramid {
3799 mini_gop: 4,
3800 mid_q_offset: None,
3801 ..Pyramid::default()
3802 };
3803 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
3804 let _ = crate::encode::take_ref_frame_hits();
3805 let mut packets = Vec::new();
3806 for picture in &sources {
3807 packets.extend(enc.encode_frames(picture).unwrap());
3808 }
3809 packets.extend(enc.flush().unwrap());
3810 let hits = crate::encode::take_ref_frame_hits();
3811 (hits, concat(&packets), packets)
3812 };
3813 let (off_hits, off_stream, _) = run(false);
3814 let (on_hits, stream, packets) = run(true);
3815 set_last2(None);
3816 eprintln!(
3817 "LAST2 off: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B); \
3818 on: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B)",
3819 off_hits[1],
3820 off_hits[2],
3821 off_hits[4],
3822 off_hits[7],
3823 off_stream.len(),
3824 on_hits[1],
3825 on_hits[2],
3826 on_hits[4],
3827 on_hits[7],
3828 stream.len(),
3829 );
3830 assert_eq!(off_hits[2], 0, "LAST2 was coded with the lever OFF");
3831 assert!(
3832 on_hits[2] >= 8,
3833 "the picture two back matches exactly and only {} blocks were coded off LAST2",
3834 on_hits[2],
3835 );
3836
3837 // Display order and sample-exactness, both decoders (the same shape
3838 // `pyramid_round_trip` gates the hidden frames with).
3839 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3840 assert_eq!(
3841 ours.len(),
3842 sources.len(),
3843 "our decoder's display-order count"
3844 );
3845 if !have_ffmpeg() {
3846 eprintln!("SKIP the ffmpeg half of the LAST2 witness: no ffmpeg");
3847 return;
3848 }
3849 let theirs = ffmpeg_decode_luma(&stream, width, height);
3850 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
3851 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3852 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
3853 assert_eq!(got.len(), b.len(), "frame {i}: luma size");
3854 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
3855 panic!(
3856 "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
3857 at % width,
3858 at / width,
3859 got[at],
3860 b[at],
3861 );
3862 }
3863 }
3864 // The reordering itself is unchanged by the second leaf slot.
3865 let shown = packets
3866 .iter()
3867 .filter(|p| p.level == Level::ShowExisting)
3868 .count();
3869 let arfs = packets.iter().filter(|p| p.level == Level::Arf).count();
3870 assert_eq!(shown, arfs, "one show_existing_frame per hidden frame");
3871 }
3872
3873 /// A picture whose content is a static gradient plus a per-picture
3874 /// pseudo-random +-2 of noise: motion search matches the neighbours
3875 /// almost exactly, so the ARF temporal filter's weights are near 1 and
3876 /// the filter actually changes the source (a moving test card gives every
3877 /// neighbour a large MSE, weight ~0, and the filter is a no-op that would
3878 /// make the future-window witness below pass blind).
3879 fn noisy_card(width: usize, height: usize, t: usize) -> Picture {
3880 let mut picture = Picture::grey(width, height);
3881 let mut seed = (t as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15);
3882 for y in 0..height {
3883 for x in 0..width {
3884 seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
3885 let noise = ((seed >> 33) % 5) as i32 - 2;
3886 let base = 40 + (x + y) as i32 / 2;
3887 picture.y[y * width + x] = base.saturating_add(noise).clamp(0, 255) as u16;
3888 }
3889 }
3890 for i in 0..(width / 2) * (height / 2) {
3891 picture.u[i] = 110;
3892 picture.v[i] = 140;
3893 }
3894 picture
3895 }
3896
3897 /// lane-lookahead's correctness witness. One group of lookahead
3898 /// (`Av1Encoder::drain_pending` hands the closed group to `ready` and
3899 /// codes the group before it) must not change WHAT is coded:
3900 ///
3901 /// * with the future half of the filter window empty AND the top ARF's
3902 /// temporal lambda window pinned to the past (`TPL_FUT=0`) the stream
3903 /// is byte for byte the one the encoder coded without a lookahead, at
3904 /// every run length -- 1 picture (no hidden frame at all), 7 (a short
3905 /// group), 8 (exactly `mini_gop`), 9 (a group plus a tail) and 17 --
3906 /// and at a GOP short enough (8) that key frames drain the buffer
3907 /// mid-run. lane-tplhalf's WIN=11 default also reads that buffer, so
3908 /// the identity arm pins the lambda window off or this witness tests
3909 /// a different lever;
3910 /// * every run decodes to exactly its picture count through OUR decoder
3911 /// and through ffmpeg, sample-exact between the two, so the flush and
3912 /// the `show_existing_frame` order survive the delay;
3913 /// * and with ONE future neighbour the top ARF's source filter actually
3914 /// reads it -- the stream MOVES (class gate-blind-to-feature: a
3915 /// buffered picture nothing consumes would pass every check above).
3916 #[test]
3917 fn the_lookahead_holds_one_group_and_still_codes_every_picture() {
3918 let _knobs = crate::speed::knob_write();
3919 // The preset is PROCESS-GLOBAL and another test may have left it
3920 // anywhere: at a high one every block of this fixture codes as skip
3921 // (17 pictures in 493 bytes) and the source filter cannot change a
3922 // byte, which failed the future-half assertion below in the suite and
3923 // passed it standalone (class process-global-knob-races-tests).
3924 let was = crate::speed::speed();
3925 crate::speed::set_speed(0);
3926 crate::encode::force_screen(Some(false));
3927 let (width, height) = (128usize, 128usize);
3928 let run = |n: usize, gop: usize, on: bool, fut: usize| -> (Vec<u8>, Vec<Packet>) {
3929 set_lookahead(Some(on));
3930 set_arf_tf_future(Some(fut));
3931 set_tpl_fut(Some(0));
3932 let config = EncoderConfig {
3933 // FINE (not the 120 the other facade tests use): at a coarse
3934 // quantizer this fixture's ARF codes almost pure skip (17
3935 // pictures in 493 bytes) and a filtered source quantizes back
3936 // to the same bytes, which made the future-half assertion
3937 // below depend on where the suite's other tests had left the
3938 // process-global preset. At q=60 the anchor carries real
3939 // coefficients and the filter must move them.
3940 base_q_idx: 60,
3941 width,
3942 height,
3943 gop,
3944 colour: Colour::Bt709Limited,
3945 tile_cols_log2: 0,
3946 tile_rows_log2: 0,
3947 };
3948 let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
3949 let sources: Vec<Picture> = (0..n).map(|t| noisy_card(width, height, t)).collect();
3950 let packets = encode_all(&mut enc, &sources);
3951 // The content gate is process-global and so is the preset: if
3952 // either has been flipped under this test the pyramid is gone and
3953 // there is no ARF to filter, which is a different failure from
3954 // "the future neighbour changed nothing" (the suite reported the
3955 // second when it meant the first).
3956 assert!(
3957 enc.pyramid().is_some(),
3958 "{n} pictures at gop {gop}: the content gate dropped the pyramid, so no ARF was coded (speed {})",
3959 crate::speed::speed(),
3960 );
3961 (concat(&packets), packets)
3962 };
3963 for gop in [32usize, 8] {
3964 for n in [1usize, 7, 8, 9, 17] {
3965 let (flat, flat_packets) = run(n, gop, false, 0);
3966 let (held, packets) = run(n, gop, true, 0);
3967 assert_eq!(
3968 flat.len(),
3969 held.len(),
3970 "{n} pictures at gop {gop}: the lookahead changed the stream LENGTH"
3971 );
3972 assert!(
3973 flat == held,
3974 "{n} pictures at gop {gop}: the stream is not byte-identical"
3975 );
3976 assert_eq!(
3977 packets
3978 .iter()
3979 .map(|p| (p.order, p.key, p.level))
3980 .collect::<Vec<_>>(),
3981 flat_packets
3982 .iter()
3983 .map(|p| (p.order, p.key, p.level))
3984 .collect::<Vec<_>>(),
3985 "{n} pictures at gop {gop}: coding order/levels moved"
3986 );
3987 let ours = crate::stream::decode_stream(&held).expect("our decoder");
3988 assert_eq!(
3989 ours.len(),
3990 n,
3991 "{n} pictures at gop {gop}: our decoder's count"
3992 );
3993 if !have_ffmpeg() {
3994 continue;
3995 }
3996 let theirs = ffmpeg_decode_luma(&held, width, height);
3997 assert_eq!(theirs.len(), n, "{n} pictures at gop {gop}: ffmpeg's count");
3998 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3999 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4000 assert!(
4001 got == *b,
4002 "{n} pictures at gop {gop}, display frame {i}: ours differs from ffmpeg"
4003 );
4004 }
4005 }
4006 }
4007 // The future half REACHES the filter, and what it produces still
4008 // decodes exactly.
4009 let (base, _) = run(17, 32, true, 0);
4010 let (symmetric, _) = run(17, 32, true, 1);
4011 set_lookahead(None);
4012 set_arf_tf_future(None);
4013 set_tpl_fut(None);
4014 assert!(
4015 base != symmetric,
4016 "one display-future neighbour left the top ARF's filter unchanged \
4017 ({} B vs {} B, preset {})",
4018 base.len(),
4019 symmetric.len(),
4020 crate::speed::speed()
4021 );
4022 let ours = crate::stream::decode_stream(&symmetric).expect("our decoder");
4023 assert_eq!(ours.len(), 17, "the symmetric arm's display-order count");
4024 if have_ffmpeg() {
4025 let theirs = ffmpeg_decode_luma(&symmetric, width, height);
4026 assert_eq!(theirs.len(), 17, "the symmetric arm's ffmpeg count");
4027 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4028 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4029 assert!(
4030 got == *b,
4031 "symmetric arm, display frame {i}: ours differs from ffmpeg"
4032 );
4033 }
4034 }
4035 crate::speed::set_speed(was);
4036 }
4037
4038 /// lane-tplfut's correctness witness, the sibling of
4039 /// [`the_lookahead_holds_one_group_and_still_codes_every_picture`]: with
4040 /// the top ARF's TEMPORAL LAMBDA window taken out of the buffered next
4041 /// group (`speed::TPL_FUT`), every picture is still coded, the streams
4042 /// decode exactly through our decoder and ffmpeg, and the stream MOVES
4043 /// against the knob off wherever a next group exists (class
4044 /// gate-blind-to-feature). Coded at q=60, not 120: at a coarse
4045 /// quantizer this fixture's ARF is almost pure skip and a different
4046 /// lambda map re-quantises to identical bytes.
4047 #[test]
4048 fn the_future_tpl_window_still_codes_every_picture_and_moves_the_stream() {
4049 let _knobs = crate::speed::knob_write();
4050 let was = crate::speed::speed();
4051 crate::speed::set_speed(0);
4052 crate::encode::force_screen(Some(false));
4053 let (width, height) = (128usize, 128usize);
4054 let run = |n: usize, gop: usize, fut: usize| -> (Vec<u8>, Vec<Packet>) {
4055 set_lookahead(Some(true));
4056 set_arf_tf_future(Some(0));
4057 set_tpl_fut(Some(fut));
4058 let config = EncoderConfig {
4059 base_q_idx: 60,
4060 width,
4061 height,
4062 gop,
4063 colour: Colour::Bt709Limited,
4064 tile_cols_log2: 0,
4065 tile_rows_log2: 0,
4066 };
4067 let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
4068 let sources: Vec<Picture> = (0..n).map(|t| noisy_card(width, height, t)).collect();
4069 let packets = encode_all(&mut enc, &sources);
4070 assert!(
4071 enc.pyramid().is_some(),
4072 "{n} pictures at gop {gop}: the content gate dropped the pyramid (speed {})",
4073 crate::speed::speed(),
4074 );
4075 (concat(&packets), packets)
4076 };
4077 for gop in [32usize, 8] {
4078 for n in [1usize, 7, 8, 9, 17] {
4079 let (off, off_packets) = run(n, gop, 0);
4080 for mode in [1usize, 2, 3] {
4081 let (on, packets) = run(n, gop, mode);
4082 assert_eq!(
4083 packets
4084 .iter()
4085 .map(|p| (p.order, p.key, p.level))
4086 .collect::<Vec<_>>(),
4087 off_packets
4088 .iter()
4089 .map(|p| (p.order, p.key, p.level))
4090 .collect::<Vec<_>>(),
4091 "{n} pictures at gop {gop} mode {mode}: coding order/levels moved"
4092 );
4093 let ours = crate::stream::decode_stream(&on).expect("our decoder");
4094 assert_eq!(
4095 ours.len(),
4096 n,
4097 "{n} pictures at gop {gop} mode {mode}: our count"
4098 );
4099 if !have_ffmpeg() {
4100 continue;
4101 }
4102 let theirs = ffmpeg_decode_luma(&on, width, height);
4103 assert_eq!(
4104 theirs.len(),
4105 n,
4106 "{n} pictures at gop {gop} mode {mode}: ffmpeg count"
4107 );
4108 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4109 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4110 assert!(
4111 got == *b,
4112 "{n} pictures at gop {gop} mode {mode}, frame {i}: ours differs from ffmpeg"
4113 );
4114 }
4115 }
4116 let _ = &off;
4117 }
4118 }
4119 // The future window REACHES the lambda map: 17 pictures at gop 32 is
4120 // three groups, so the first two top ARFs each have a next group
4121 // buffered and their windows really are display-future.
4122 let (off, _) = run(17, 32, 0);
4123 // Mode 2 is NOT in this list: at its default split it keeps the three
4124 // NEAREST past neighbours, and those dominate the propagation -- on
4125 // this 128x128 fixture the map moves too little to flip an RD
4126 // decision and the stream comes back byte-identical to mode 0. Not a
4127 // dead knob: the same run with `EC_AV1_TPL_FUT_HALF=1` (one past
4128 // neighbour, six future) does move the stream, and the gate below
4129 // measures mode 2 on real content.
4130 for mode in [1usize, 3] {
4131 let (on, _) = run(17, 32, mode);
4132 assert!(
4133 off != on,
4134 "mode {mode} left the top ARF's temporal lambda map unchanged \
4135 ({} B vs {} B, preset {})",
4136 off.len(),
4137 on.len(),
4138 crate::speed::speed()
4139 );
4140 }
4141 set_lookahead(None);
4142 set_arf_tf_future(None);
4143 set_tpl_fut(None);
4144 crate::speed::set_speed(was);
4145 }
4146
4147 /// lane-arfmode: the top ARF's leaf offer set. Three guards in one
4148 /// witness, over 17 pictures at gop 32 (three groups, so several top
4149 /// ARFs) at q=60 -- the lookahead witness's lesson: at a fine q the
4150 /// anchor carries real coefficients, so a cut that moves only the
4151 /// hidden frame's internal decisions cannot hide behind "everything
4152 /// quantized to the same bytes":
4153 ///
4154 /// 1. OFF (default and explicit `Some(0)`) is byte-identical -- the
4155 /// shipped table is 0 and the lever is bit-exact when off;
4156 /// 2. each armed mode (1 no intra, 2 no 8x8, 4 no compound) really
4157 /// FIRES -- its own [`crate::encode::take_arfmode_hits`] counter
4158 /// moves (class `gate-blind-to-feature`) -- and MOVES THE STREAM;
4159 /// 3. the coding order and levels never change, and every armed stream
4160 /// decodes sample-exact through `decode_stream` AND ffmpeg.
4161 #[test]
4162 fn the_arf_leaf_offer_set_fires_moves_the_stream_and_decodes_sample_exact() {
4163 let _knobs = crate::speed::knob_write();
4164 let was = crate::speed::speed();
4165 crate::speed::set_speed(0);
4166 crate::encode::force_screen(Some(false));
4167 let (width, height) = (128usize, 128usize);
4168 let run = |mode: Option<u8>| -> (Vec<u8>, Vec<Packet>) {
4169 crate::encode::set_arfmode(mode);
4170 let _ = crate::encode::take_arfmode_hits();
4171 let config = EncoderConfig {
4172 base_q_idx: 60,
4173 width,
4174 height,
4175 gop: 32,
4176 colour: Colour::Bt709Limited,
4177 tile_cols_log2: 0,
4178 tile_rows_log2: 0,
4179 };
4180 let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
4181 // Groups at three luma LEVELS (the base ramp 40/110/180): the
4182 // middle group's top ARF sits halfway between the two dark/light
4183 // anchors its slots hold, which is exactly where neither
4184 // single-reference prediction nor intra wins by default -- the
4185 // AVERAGE of two references (compound) and the DC of the new
4186 // level (intra) do. Without this the synthetic cards' noise
4187 // quantizes to skip and no arm can move anything (measured:
4188 // 516 intra trials skipped, zero won, stream identical).
4189 let sources: Vec<Picture> = (0..17)
4190 .map(|t| {
4191 let mut p = noisy_card(width, height, t);
4192 let shift = 70i32 * (t / 8) as i32;
4193 for v in p.y.iter_mut() {
4194 *v = (i32::from(*v) + shift).clamp(0, 255) as u16;
4195 }
4196 p
4197 })
4198 .collect();
4199 let packets = encode_all(&mut enc, &sources);
4200 (concat(&packets), packets)
4201 };
4202 let (off, off_packets) = run(None);
4203 let (explicit_off, _) = run(Some(0));
4204 assert_eq!(
4205 off, explicit_off,
4206 "mode 0 is not bit-exact with the default"
4207 );
4208 for (mode, arm) in [(1u8, 0usize), (2, 1), (4, 2)] {
4209 let (on, packets) = run(Some(mode));
4210 let hits = crate::encode::take_arfmode_hits();
4211 assert_eq!(
4212 packets
4213 .iter()
4214 .map(|p| (p.order, p.key, p.level))
4215 .collect::<Vec<_>>(),
4216 off_packets
4217 .iter()
4218 .map(|p| (p.order, p.key, p.level))
4219 .collect::<Vec<_>>(),
4220 "mode {mode}: coding order/levels moved"
4221 );
4222 assert!(
4223 hits[arm] > 0,
4224 "mode {mode}: its counter never fired ({hits:?}) -- the lever is \
4225 gate-blind on this fixture",
4226 );
4227 assert_ne!(
4228 off, on,
4229 "mode {mode} left the stream byte-identical despite {} firing hits",
4230 hits[arm],
4231 );
4232 eprintln!(
4233 "mode {mode}: {} -> {} B, hits {hits:?}",
4234 off.len(),
4235 on.len()
4236 );
4237 let ours = crate::stream::decode_stream(&on).expect("our decoder");
4238 assert_eq!(ours.len(), 17, "mode {mode}: our decoder's picture count");
4239 if !have_ffmpeg() {
4240 continue;
4241 }
4242 let theirs = ffmpeg_decode_luma(&on, width, height);
4243 assert_eq!(theirs.len(), 17, "mode {mode}: ffmpeg's picture count");
4244 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4245 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4246 assert!(
4247 got == *b,
4248 "mode {mode}, frame {i}: ours differs from ffmpeg"
4249 );
4250 }
4251 }
4252 crate::encode::set_arfmode(None);
4253 crate::speed::set_speed(was);
4254 }
4255
4256 fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) {
4257 let (width, height) = (128usize, 128usize);
4258 let config = EncoderConfig {
4259 width,
4260 height,
4261 base_q_idx: 120,
4262 gop: 32,
4263 colour: Colour::Bt709Limited,
4264 tile_cols_log2: 0,
4265 tile_rows_log2: 0,
4266 };
4267 // The content gate ([`Av1Encoder::encode_frames`]) would drop a
4268 // screen-content stream to the flat path, and a synthetic test card
4269 // is exactly the few-colour picture the detector fires on: this gate
4270 // is about the reordering, so it asks for camera content explicitly.
4271 crate::encode::force_screen(Some(false));
4272 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
4273 let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect();
4274 let _ = crate::encode::take_ref_frame_hits();
4275 let mut packets = Vec::new();
4276 for picture in &sources {
4277 packets.extend(enc.encode_frames(picture).unwrap());
4278 }
4279 packets.extend(enc.flush().unwrap());
4280
4281 // Shape: every source picture is coded exactly once, and each closed
4282 // group adds one `show_existing_frame` packet.
4283 let coded: Vec<u64> = packets
4284 .iter()
4285 .filter(|p| p.level != Level::ShowExisting)
4286 .map(|p| p.order)
4287 .collect();
4288 let mut sorted = coded.clone();
4289 sorted.sort_unstable();
4290 assert_eq!(
4291 sorted,
4292 (0..9).collect::<Vec<u64>>(),
4293 "one packet per picture"
4294 );
4295 assert_ne!(coded, sorted, "the pyramid never reordered anything");
4296 let shown = packets
4297 .iter()
4298 .filter(|p| p.level == Level::ShowExisting)
4299 .count();
4300 assert_eq!(shown, hidden, "one show_existing_frame per hidden frame");
4301 for (i, p) in packets.iter().enumerate() {
4302 assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position");
4303 }
4304 let hist = |l: Level| packets.iter().filter(|p| p.level == l).count();
4305 eprintln!(
4306 "pyramid levels: key {} arf {} leaf {} show_existing {}",
4307 hist(Level::Key),
4308 hist(Level::Arf),
4309 hist(Level::Leaf),
4310 hist(Level::ShowExisting),
4311 );
4312 assert_eq!(hist(Level::Arf), hidden, "hidden frames");
4313 let refs = crate::encode::take_ref_frame_hits();
4314 eprintln!(
4315 "blocks per reference: LAST {} GOLDEN {} ALTREF {}",
4316 refs[crate::mvstack::LAST_FRAME as usize],
4317 refs[crate::mvstack::GOLDEN_FRAME as usize],
4318 refs[crate::mvstack::ALTREF_FRAME as usize],
4319 );
4320 // [[gate-blind-to-feature]]: the whole point of the hidden frame is
4321 // that the leaves predict BACKWARD off it, which is also the only
4322 // thing that exercises `ref_frame_sign_bias` in the MV stack. A green
4323 // round trip in which `ALTREF_FRAME` never won a block would prove
4324 // only that a hidden frame can be written and re-output.
4325 assert!(
4326 refs[crate::mvstack::ALTREF_FRAME as usize] > 0,
4327 "no block predicted off the hidden ALTREF"
4328 );
4329
4330 let stream = concat(&packets);
4331 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4332 assert_eq!(
4333 ours.len(),
4334 sources.len(),
4335 "our decoder's display-order count"
4336 );
4337 if !have_ffmpeg() {
4338 eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg");
4339 return;
4340 }
4341 let theirs = ffmpeg_decode_luma(&stream, width, height);
4342 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
4343 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4344 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4345 assert_eq!(got.len(), b.len(), "frame {i}: luma size");
4346 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
4347 panic!(
4348 "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4349 at % width,
4350 at / width,
4351 got[at],
4352 b[at],
4353 );
4354 }
4355 }
4356 }
4357
4358 /// Every tile layout this encoder can write decodes SAMPLE-EXACT
4359 /// through both decoders -- ours and ffmpeg's -- and the frames really
4360 /// carry the tiles the header claims (the OBU parser locates one payload
4361 /// per tile, so a stream that quietly stayed single-tile fails here
4362 /// rather than passing on a green round trip).
4363 ///
4364 /// The bytes are what the gate is on: an encoder that clipped its
4365 /// neighbour availability wrong writes a stream whose two decoders agree
4366 /// with each other and disagree with nothing -- so the ffmpeg half is
4367 /// the one that catches a tile boundary the writer respected and the
4368 /// spec does not, and the parser half catches the reverse.
4369
4370 /// A STATIC clip: every inter frame predicts perfectly from the last, so
4371 /// the search takes the 64x64 root ([`crate::encode::B64_ROOT`]) instead
4372 /// of coding four 32x32 quadrants, and the stream both decoders
4373 /// reconstruct is still sample-exact against the encoder's own
4374 /// reconstruction. The counter is the point (class
4375 /// `gate-blind-to-feature`): without it a green three-way compare says
4376 /// nothing about whether a single 64x64 block was ever written.
4377 /// lane-sb128 step 1: the same static clip under a 128x128 SUPERBLOCK.
4378 /// Every partition decision below the root is the one the 64-superblock
4379 /// encoder makes -- the root itself is always `PARTITION_SPLIT` into the
4380 /// four 64x64 superblocks -- so the only thing this proves is the
4381 /// structural syntax: the root's own partition symbol, its loop
4382 /// restoration read once over the 128 span at the 128 unit size, and
4383 /// libaom's TL/TR/BL/BR visit order. 256x128 is 2x1 128x128 superblocks
4384 /// per frame over three frames, so the root fires 6 times.
4385 ///
4386 /// `#[ignore]`: [`crate::encode::force_sb128`] moves a process-global
4387 /// (the superblock size is a sequence field), so this gate runs alone:
4388 ///
4389 /// cargo test -p ec-av1 --release --lib -- --ignored \
4390 /// a_static_clip_codes_128x128_superblock_roots --nocapture
4391 #[test]
4392 #[ignore = "sets the process-global superblock size: run it alone"]
4393 fn a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact() {
4394 let _knobs = crate::speed::knob_write();
4395 let _gate_lock = crate::stream::tests::lock_gate_counters();
4396 crate::encode::force_sb128(true);
4397 let (width, height) = (256usize, 128usize);
4398 let still = test_card(width, height, 0);
4399 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
4400 let config = EncoderConfig {
4401 width,
4402 height,
4403 base_q_idx: 120,
4404 gop: 8,
4405 colour: Colour::Bt709Limited,
4406 tile_cols_log2: 0,
4407 tile_rows_log2: 0,
4408 };
4409 let mut enc = Av1Encoder::new(config).unwrap();
4410 let mut stream = Vec::new();
4411 let _ = crate::tile::take_sb128_root_hits();
4412 for packet in encode_all(&mut enc, &sources) {
4413 stream.extend_from_slice(&packet.data);
4414 }
4415 let roots = crate::tile::take_sb128_root_hits();
4416 assert!(
4417 roots >= 4,
4418 "a 128x128-superblock clip coded {roots} superblock roots, wanted at least 4"
4419 );
4420 eprintln!("128x128 superblock roots: {roots}");
4421
4422 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4423 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4424 assert!(
4425 crate::decode::part128_split_hits() >= 4,
4426 "our decoder read no 128x128 superblock root"
4427 );
4428 if !have_ffmpeg() {
4429 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4430 return;
4431 }
4432 let theirs = ffmpeg_decode_luma(&stream, width, height);
4433 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4434 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4435 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4436 assert_eq!(&got, b, "frame {i}: ffmpeg and our decoder disagree");
4437 }
4438 }
4439
4440 #[test]
4441 fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() {
4442 let _knobs = crate::speed::knob_write();
4443 let _gate_lock = crate::stream::tests::lock_gate_counters();
4444 let (width, height) = (256usize, 128usize);
4445 let still = test_card(width, height, 0);
4446 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
4447 let config = EncoderConfig {
4448 width,
4449 height,
4450 base_q_idx: 120,
4451 gop: 8,
4452 colour: Colour::Bt709Limited,
4453 tile_cols_log2: 0,
4454 tile_rows_log2: 0,
4455 };
4456 let mut enc = Av1Encoder::new(config).unwrap();
4457 let mut stream = Vec::new();
4458 let _ = crate::encode::take_b64_root_hits();
4459 for packet in encode_all(&mut enc, &sources) {
4460 stream.extend_from_slice(&packet.data);
4461 }
4462 let roots = crate::encode::take_b64_root_hits();
4463 // 8 superblocks per frame, two inter frames.
4464 assert!(
4465 roots > 0,
4466 "a static clip coded no 64x64 root at all (of 16 inter superblocks)"
4467 );
4468 eprintln!("64x64 roots on a static clip: {roots} of 16 inter superblocks");
4469
4470 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4471 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4472 if !have_ffmpeg() {
4473 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4474 return;
4475 }
4476 let theirs = ffmpeg_decode_luma(&stream, width, height);
4477 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4478 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4479 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4480 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
4481 panic!(
4482 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4483 at % width,
4484 at / width,
4485 got[at],
4486 b[at],
4487 );
4488 }
4489 assert_eq!(
4490 got.len(),
4491 b.len(),
4492 "frame {i}: luma is {} samples, ffmpeg's is {}",
4493 got.len(),
4494 b.len()
4495 );
4496 }
4497 }
4498
4499 /// The same clip with a DC step between frames (lane-tx64): the 64x64
4500 /// root still predicts the whole superblock from the last frame, but the
4501 /// prediction is uniformly off, so the root's NON-skip arm -- one
4502 /// TX_64X64 luma transform and two TX_32X32 chroma ones -- prices below
4503 /// its skip arm and a 64x64 residual is really written. The counter is
4504 /// the gate (class `gate-blind-to-feature`; the static clip above cannot
4505 /// reach this arm at all because its prediction is exact), and both
4506 /// decoders have to reconstruct those coefficients sample-exact -- a
4507 /// writer that names the wrong coefficient set or the wrong `txfm_split`
4508 /// desyncs the whole tile here.
4509 #[test]
4510 fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() {
4511 let _knobs = crate::speed::knob_write();
4512 let _gate_lock = crate::stream::tests::lock_gate_counters();
4513 let (width, height) = (256usize, 128usize);
4514 let still = test_card(width, height, 0);
4515 let sources: Vec<Picture> = (0..3)
4516 .map(|t| {
4517 let mut p = still.clone();
4518 let step = (t * 6) as u16;
4519 for v in &mut p.y {
4520 *v = (*v + step).min(255);
4521 }
4522 p
4523 })
4524 .collect();
4525 let config = EncoderConfig {
4526 width,
4527 height,
4528 base_q_idx: 120,
4529 gop: 8,
4530 colour: Colour::Bt709Limited,
4531 tile_cols_log2: 0,
4532 tile_rows_log2: 0,
4533 };
4534 let mut enc = Av1Encoder::new(config).unwrap();
4535 let mut stream = Vec::new();
4536 let _ = crate::encode::take_b64_residual_hits();
4537 for packet in encode_all(&mut enc, &sources) {
4538 stream.extend_from_slice(&packet.data);
4539 }
4540 let residuals = crate::encode::take_b64_residual_hits();
4541 assert!(
4542 residuals > 0,
4543 "a DC-stepped clip coded no 64x64 root with a residual at all"
4544 );
4545 eprintln!("64x64 roots with a residual: {residuals} of 16 inter superblocks");
4546
4547 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4548 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4549 if !have_ffmpeg() {
4550 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4551 return;
4552 }
4553 let theirs = ffmpeg_decode_luma(&stream, width, height);
4554 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4555 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4556 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4557 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
4558 panic!(
4559 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4560 at % width,
4561 at / width,
4562 got[at],
4563 b[at],
4564 );
4565 }
4566 assert_eq!(
4567 got.len(),
4568 b.len(),
4569 "frame {i}: luma is {} samples, ffmpeg's is {}",
4570 got.len(),
4571 b.len()
4572 );
4573 }
4574 }
4575
4576 /// A frame whose size is NOT a multiple of a superblock (lane-b64b):
4577 /// 232x168 leaves the last superblock column and row cut by the true
4578 /// frame edge, with more than half of each inside -- which is exactly
4579 /// what AV1's `has_cols`/`has_rows` allow to stay whole. Both gate films
4580 /// are superblock-aligned, so nothing but a synthetic size reaches this
4581 /// path at all (class `gate-blind-to-feature`), and the user's own
4582 /// exports are arbitrary sizes.
4583 #[test]
4584 fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() {
4585 let _knobs = crate::speed::knob_write();
4586 let _gate_lock = crate::stream::tests::lock_gate_counters();
4587 let (width, height) = (232usize, 168usize);
4588 let still = test_card(width, height, 0);
4589 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
4590 let config = EncoderConfig {
4591 width,
4592 height,
4593 base_q_idx: 120,
4594 gop: 8,
4595 colour: Colour::Bt709Limited,
4596 tile_cols_log2: 0,
4597 tile_rows_log2: 0,
4598 };
4599 let mut enc = Av1Encoder::new(config).unwrap();
4600 let mut stream = Vec::new();
4601 let _ = crate::encode::take_b64_edge_hits();
4602 for packet in encode_all(&mut enc, &sources) {
4603 stream.extend_from_slice(&packet.data);
4604 }
4605 let edges = crate::encode::take_b64_edge_hits();
4606 assert!(
4607 edges > 0,
4608 "no 64x64 root was taken at a superblock the frame edge cuts"
4609 );
4610 eprintln!("edge 64x64 roots: {edges}");
4611
4612 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4613 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4614 if !have_ffmpeg() {
4615 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4616 return;
4617 }
4618 let theirs = ffmpeg_decode_luma(&stream, width, height);
4619 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4620 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
4621 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
4622 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
4623 panic!(
4624 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4625 at % width,
4626 at / width,
4627 got[at],
4628 theirs_i[at],
4629 );
4630 }
4631 assert_eq!(
4632 got.len(),
4633 theirs_i.len(),
4634 "frame {i}: luma is {} samples, ffmpeg's is {}",
4635 got.len(),
4636 theirs_i.len()
4637 );
4638 }
4639 }
4640
4641 /// The 1080p SHAPE at a fifth of its size (lane-sse): 384x216 is three
4642 /// whole superblock columns and 1.6875 superblock rows, so the bottom
4643 /// 88-pixel band straddles at EVERY level -- the 64x64 root lane-b64b
4644 /// already clipped, and the 32x32 (216 = 6*32 + 24) and 16x16 (13*16 + 8)
4645 /// leaves it did not. Every one of them is now scored over its inside
4646 /// part alone, and a distortion change that moved a partition or a
4647 /// transform decision the writer did not follow would desync the tile, so
4648 /// both decoders reconstruct it sample-exact.
4649 #[test]
4650 fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() {
4651 let _knobs = crate::speed::knob_write();
4652 let _gate_lock = crate::stream::tests::lock_gate_counters();
4653 let (width, height) = (384usize, 216usize);
4654 let sources: Vec<Picture> = (0..3).map(|i| test_card(width, height, i)).collect();
4655 let config = EncoderConfig {
4656 width,
4657 height,
4658 base_q_idx: 120,
4659 gop: 8,
4660 colour: Colour::Bt709Limited,
4661 tile_cols_log2: 0,
4662 tile_rows_log2: 0,
4663 };
4664 let mut enc = Av1Encoder::new(config).unwrap();
4665 let mut stream = Vec::new();
4666 for packet in encode_all(&mut enc, &sources) {
4667 stream.extend_from_slice(&packet.data);
4668 }
4669 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4670 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4671 if !have_ffmpeg() {
4672 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4673 return;
4674 }
4675 let theirs = ffmpeg_decode_luma(&stream, width, height);
4676 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4677 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
4678 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
4679 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
4680 panic!(
4681 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4682 at % width,
4683 at / width,
4684 got[at],
4685 theirs_i[at],
4686 );
4687 }
4688 assert_eq!(
4689 got.len(),
4690 theirs_i.len(),
4691 "frame {i}: luma is {} samples, ffmpeg's is {}",
4692 got.len(),
4693 theirs_i.len()
4694 );
4695 }
4696 }
4697
4698 /// A clip whose inter residual is HIGH-FREQUENCY (lane-b64b): every
4699 /// frame adds a 4-pixel checkerboard, so the 64x64 root's prediction is
4700 /// off by exactly the detail a TX_64X64 throws away (it codes only the
4701 /// top-left 32x32 corner of its coefficient space) and the root's var-tx
4702 /// arm splits its luma into four TX_32X32 units instead. The counter is
4703 /// the gate (class `gate-blind-to-feature`), and a `txfm_split` the
4704 /// reader does not expect desyncs the whole tile, so both decoders have
4705 /// to reconstruct it sample-exact.
4706 #[test]
4707 fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() {
4708 let _knobs = crate::speed::knob_write();
4709 let _gate_lock = crate::stream::tests::lock_gate_counters();
4710 let (width, height) = (256usize, 128usize);
4711 let still = test_card(width, height, 0);
4712 let sources: Vec<Picture> = (0..4)
4713 .map(|t| {
4714 let mut p = still.clone();
4715 for (i, v) in p.y.iter_mut().enumerate() {
4716 let checker = ((i % width) / 4 + (i / width) / 4) % 2;
4717 let bump = (t * 5 * (checker + 1)) as u16;
4718 *v = (*v + bump).min(255);
4719 }
4720 p
4721 })
4722 .collect();
4723 let config = EncoderConfig {
4724 width,
4725 height,
4726 base_q_idx: 90,
4727 gop: 8,
4728 colour: Colour::Bt709Limited,
4729 tile_cols_log2: 0,
4730 tile_rows_log2: 0,
4731 };
4732 let mut enc = Av1Encoder::new(config).unwrap();
4733 let mut stream = Vec::new();
4734 let _ = crate::encode::take_b64_var_tx_hits();
4735 for packet in encode_all(&mut enc, &sources) {
4736 stream.extend_from_slice(&packet.data);
4737 }
4738 let split = crate::encode::take_b64_var_tx_hits();
4739 assert!(split > 0, "no 64x64 root split its luma transform at all");
4740 eprintln!("64x64 roots with a SPLIT luma transform: {split}");
4741
4742 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4743 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4744 if !have_ffmpeg() {
4745 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4746 return;
4747 }
4748 let theirs = ffmpeg_decode_luma(&stream, width, height);
4749 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4750 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
4751 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
4752 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
4753 panic!(
4754 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4755 at % width,
4756 at / width,
4757 got[at],
4758 theirs_i[at],
4759 );
4760 }
4761 assert_eq!(
4762 got.len(),
4763 theirs_i.len(),
4764 "frame {i}: luma is {} samples, ffmpeg's is {}",
4765 got.len(),
4766 theirs_i.len()
4767 );
4768 }
4769 }
4770
4771 /// A CROSSFADE clip (lane-b64b): each picture is a linear blend of two
4772 /// stills, so on a leaf frame the average of its past (`LAST`) and future
4773 /// (`ALTREF`) references IS the source and neither reference alone is --
4774 /// exactly the content a COMPOUND 64x64 root pays on. The counter is the
4775 /// gate (class `gate-blind-to-feature`): without it a green three-way
4776 /// compare says nothing about whether one compound root was written, and
4777 /// the writer's compound arm (`write_compound_block` at `SB_MI` 16, no
4778 /// `motion_mode` symbol) desyncs the whole tile if it is wrong.
4779 #[test]
4780 fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() {
4781 let _knobs = crate::speed::knob_write();
4782 let _gate_lock = crate::stream::tests::lock_gate_counters();
4783 let (width, height) = (256usize, 128usize);
4784 let (a, b) = (test_card(width, height, 0), test_card(width, height, 24));
4785 let sources: Vec<Picture> = (0..9)
4786 .map(|t| {
4787 let mut p = a.clone();
4788 let w = t as u32;
4789 for (v, &other) in p.y.iter_mut().zip(&b.y) {
4790 *v = ((u32::from(*v) * (8 - w) + u32::from(other) * w) / 8) as u16;
4791 }
4792 p
4793 })
4794 .collect();
4795 let config = EncoderConfig {
4796 width,
4797 height,
4798 base_q_idx: 120,
4799 gop: 9,
4800 colour: Colour::Bt709Limited,
4801 tile_cols_log2: 0,
4802 tile_rows_log2: 0,
4803 };
4804 let mut enc = Av1Encoder::new(config).unwrap();
4805 let mut stream = Vec::new();
4806 let _ = crate::encode::take_b64_compound_hits();
4807 for packet in encode_all(&mut enc, &sources) {
4808 stream.extend_from_slice(&packet.data);
4809 }
4810 let compound = crate::encode::take_b64_compound_hits();
4811 assert!(
4812 compound > 0,
4813 "a crossfade clip coded no COMPOUND 64x64 root at all"
4814 );
4815 eprintln!("compound 64x64 roots on a crossfade clip: {compound}");
4816
4817 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4818 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4819 if !have_ffmpeg() {
4820 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4821 return;
4822 }
4823 let theirs = ffmpeg_decode_luma(&stream, width, height);
4824 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4825 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
4826 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
4827 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
4828 panic!(
4829 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4830 at % width,
4831 at / width,
4832 got[at],
4833 theirs_i[at],
4834 );
4835 }
4836 assert_eq!(
4837 got.len(),
4838 theirs_i.len(),
4839 "frame {i}: luma is {} samples, ffmpeg's is {}",
4840 got.len(),
4841 theirs_i.len()
4842 );
4843 }
4844 }
4845
4846 #[test]
4847 fn every_tile_layout_decodes_sample_exact_through_both_decoders() {
4848 let _knobs = crate::speed::knob_read();
4849 let (width, height) = (640usize, 384usize);
4850 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
4851 let mut sizes = Vec::new();
4852 for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] {
4853 let config = EncoderConfig {
4854 width,
4855 height,
4856 base_q_idx: 120,
4857 gop: 4,
4858 colour: Colour::Bt709Limited,
4859 tile_cols_log2: cols_log2,
4860 tile_rows_log2: rows_log2,
4861 };
4862 let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
4863 // lane-b128m: the SPEC's uniform spacing derives the tile count
4864 // from the superblock grid (`tileWidthSb = ceil(sbCols >> log2)`),
4865 // so a frame with fewer superblock columns than the requested
4866 // count codes fewer tiles -- which is what a 128-superblock
4867 // sequence does here. The grid the encoder itself computes is the
4868 // expectation; at 64 superblocks it is `1 << log2` exactly.
4869 let grid = crate::tile::TileLayout::new(
4870 (width as u32).div_ceil(4),
4871 (height as u32).div_ceil(4),
4872 cols_log2,
4873 rows_log2,
4874 );
4875 let (want_cols, want_rows) = (grid.cols(), grid.rows());
4876 let mut enc = Av1Encoder::new(config).unwrap();
4877 let mut stream = Vec::new();
4878 for packet in encode_all(&mut enc, &sources) {
4879 stream.extend_from_slice(&packet.data);
4880 }
4881 sizes.push((layout.clone(), stream.len()));
4882
4883 // The frames carry the tiles their headers claim.
4884 let mut parser = ec_av1_syntax::Av1Parser::new();
4885 let mut frames = 0usize;
4886 let mut offset = 0usize;
4887 while offset < stream.len() {
4888 let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap();
4889 let unit: usize = obus.iter().map(|o| o.total_size).sum();
4890 for obu in &obus {
4891 if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind {
4892 assert_eq!(
4893 (parsed.tile_info.cols, parsed.tile_info.rows),
4894 (want_cols, want_rows),
4895 "{layout}: the header's own tile grid"
4896 );
4897 assert_eq!(
4898 tiles.len(),
4899 (want_cols * want_rows) as usize,
4900 "{layout}: tile payloads located in the tile group"
4901 );
4902 frames += 1;
4903 }
4904 }
4905 offset += unit;
4906 }
4907 assert_eq!(frames, sources.len(), "{layout}: coded frames");
4908
4909 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4910 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
4911 if !have_ffmpeg() {
4912 eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg");
4913 continue;
4914 }
4915 let theirs = ffmpeg_decode_luma(&stream, width, height);
4916 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
4917 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4918 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4919 assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size");
4920 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
4921 panic!(
4922 "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4923 at % width,
4924 at / width,
4925 got[at],
4926 b[at],
4927 );
4928 }
4929 }
4930 }
4931 let base = sizes[0].1 as f64;
4932 for (layout, bytes) in &sizes {
4933 eprintln!(
4934 "{layout}: {bytes} bytes ({:+.2}% vs one tile)",
4935 (*bytes as f64 / base - 1.0) * 100.0
4936 );
4937 }
4938 }
4939
4940 /// lane-deltaq's three-way witness: a clip with a real gradient of tpl
4941 /// factors -- a moving detail region over a flat background, so the
4942 /// superblocks the NEXT picture predicts from are worth more than the
4943 /// ones it does not -- codes at least two distinct per-superblock
4944 /// quantizer levels (the fire count, class `gate-blind-to-feature`), and
4945 /// both decoders reconstruct every frame sample-exact from the
4946 /// `delta_qindex` syntax that carries them.
4947 #[test]
4948 fn a_moving_detail_clip_codes_two_delta_q_levels_both_decoders_read_exactly() {
4949 // `knob_write`, not `knob_read`: the override below is
4950 // process-global and every other test's bytes move under it.
4951 let _knobs = crate::speed::knob_write();
4952 let _gate_lock = crate::stream::tests::lock_gate_counters();
4953 crate::encode::set_deltaq_res(Some(2));
4954 let (width, height) = (640usize, 384usize);
4955 // The gate's own moving test card, with a 128x128 patch of fine
4956 // detail travelling right by 32 samples a frame laid over it: the
4957 // patch is what the tpl pass finds worth propagating and the card
4958 // around it is not, so the map -- and with it the quantizer grid --
4959 // is a gradient and not one flat number.
4960 let sources: Vec<Picture> = (0..4)
4961 .map(|t| {
4962 let mut p = test_card(width, height, t * 3);
4963 let x0 = 32 + t * 32;
4964 for y in 128..256 {
4965 for x in x0..x0 + 128 {
4966 p.y[y * width + x] = if (x / 2 + y / 3) % 2 == 0 { 40 } else { 210 };
4967 }
4968 }
4969 p
4970 })
4971 .collect();
4972 let config = EncoderConfig {
4973 width,
4974 height,
4975 base_q_idx: 120,
4976 gop: 4,
4977 colour: Colour::Bt709Limited,
4978 tile_cols_log2: 0,
4979 tile_rows_log2: 0,
4980 };
4981 let mut enc = Av1Encoder::new(config).unwrap();
4982 let _ = crate::encode::take_deltaq_levels();
4983 let mut stream = Vec::new();
4984 for packet in encode_all(&mut enc, &sources) {
4985 stream.extend_from_slice(&packet.data);
4986 }
4987 let levels = crate::encode::take_deltaq_levels();
4988 // The quantizer grid rides the tpl map, and `speed::TPL_DEPTH` cuts
4989 // the lookahead window to one picture at the top presets, so there IS
4990 // no map -- and no delta_q syntax -- there. The exactness half below
4991 // still runs; only the fire count needs a window (lane-tplwin: the
4992 // predicate is the window, not preset 0, since presets 1..6 have one).
4993 if crate::speed::at(&crate::speed::TPL_DEPTH) > 1 {
4994 assert!(
4995 levels >= 2,
4996 "the quantizer grid was flat ({levels} level(s)): no delta_qindex was coded"
4997 );
4998 } else {
4999 eprintln!(
5000 "SKIP the fire count at preset {}: no tpl map",
5001 crate::speed::speed()
5002 );
5003 }
5004 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5005 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
5006 if have_ffmpeg() {
5007 let theirs = ffmpeg_decode_luma(&stream, width, height);
5008 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5009 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
5010 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
5011 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
5012 panic!(
5013 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
5014 at % width,
5015 at / width,
5016 got[at],
5017 b[at],
5018 );
5019 }
5020 assert_eq!(
5021 got.len(),
5022 b.len(),
5023 "frame {i}: luma is {} samples, ffmpeg's is {}",
5024 got.len(),
5025 b.len()
5026 );
5027 }
5028 } else {
5029 eprintln!("SKIP the ffmpeg half: no ffmpeg");
5030 }
5031 crate::encode::set_deltaq_res(None);
5032 eprintln!(
5033 "delta_q witness: {levels} quantizer levels, {} bytes",
5034 stream.len()
5035 );
5036 }
5037
5038 /// lane-txset's witness: a clip of hard directional edges makes the intra
5039 /// luma search take EVERY type of the five-type reduced set
5040 /// (`TX_SET_INTRA_2`: `DCT_DCT`, `ADST_ADST`, `ADST_DCT`, `DCT_ADST`,
5041 /// `IDTX`) at least once -- the fire count, class `gate-blind-to-feature`
5042 /// -- and both decoders reconstruct every frame sample-exact from the
5043 /// `tx_type` symbols that name them. Before the lane the writer coded
5044 /// `DCT_DCT` for every luma transform unit ever written, so this is also
5045 /// the statement that the other four are REACHABLE at all.
5046 #[test]
5047 fn an_edge_clip_codes_every_reduced_set_tx_type_both_decoders_read_exactly() {
5048 // `knob_write`: the screen override below is process-global, and the
5049 // type search is SCREEN-ONLY (`encode::tx_type_candidates`).
5050 let _knobs = crate::speed::knob_write();
5051 crate::encode::force_screen(Some(true));
5052 let _gate_lock = crate::stream::tests::lock_gate_counters();
5053 let (width, height) = (320usize, 192usize);
5054 // Sharp horizontal and vertical steps: a vertical edge is what an
5055 // `ADST` column pass beats a `DCT` one on, a horizontal edge the
5056 // mirror, and the flat/ramp areas between them are where `IDTX` wins.
5057 let sources: Vec<Picture> = (0..2)
5058 .map(|t| {
5059 let mut p = test_card(width, height, t * 3);
5060 for y in 0..height {
5061 for x in 0..width {
5062 let v = match ((x + t * 4) / 16 % 2, y / 16 % 2) {
5063 (0, 0) => 16u16,
5064 (1, 0) => 235,
5065 (0, 1) => (x % 64 * 3) as u16,
5066 _ => (y % 64 * 3) as u16,
5067 };
5068 p.y[y * width + x] = v;
5069 }
5070 }
5071 p
5072 })
5073 .collect();
5074 let config = EncoderConfig {
5075 width,
5076 height,
5077 base_q_idx: 90,
5078 gop: 2,
5079 colour: Colour::Bt709Limited,
5080 tile_cols_log2: 0,
5081 tile_rows_log2: 0,
5082 };
5083 let mut enc = Av1Encoder::new(config).unwrap();
5084 let _ = crate::encode::take_tx_type_hits();
5085 let mut stream = Vec::new();
5086 for packet in encode_all(&mut enc, &sources) {
5087 stream.extend_from_slice(&packet.data);
5088 }
5089 let hits = crate::encode::take_tx_type_hits();
5090 // The type search is a speed lever (`speed::TX_TYPE_SEARCH`); above
5091 // the presets that carry it only `DCT_DCT` is offered, and the
5092 // exactness half below is what still runs there. The FULL five-type
5093 // fire count is preset 0's to make: a faster preset prunes modes and
5094 // partitions before a type is ever priced on them, so `ADST_ADST` and
5095 // `IDTX` stop winning on this clip at preset 6 (measured: hits
5096 // `[0, 6192, 0, 79, 284, ..]`). Every preset that carries the lever
5097 // still has to reach SOME non-`DCT_DCT` type -- that is the
5098 // "reachable at all" statement, class `gate-blind-to-feature`.
5099 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) {
5100 let non_dct: usize =
5101 hits.iter().sum::<usize>() - hits[crate::transform::TxType::DctDct as usize];
5102 assert!(
5103 non_dct > 0,
5104 "every luma transform unit took DCT_DCT: {hits:?}"
5105 );
5106 }
5107 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 {
5108 for (name, ty) in [
5109 ("DCT_DCT", crate::transform::TxType::DctDct),
5110 ("ADST_ADST", crate::transform::TxType::AdstAdst),
5111 ("ADST_DCT", crate::transform::TxType::AdstDct),
5112 ("DCT_ADST", crate::transform::TxType::DctAdst),
5113 ("IDTX", crate::transform::TxType::Idtx),
5114 ] {
5115 assert!(
5116 hits[ty as usize] > 0,
5117 "no luma transform unit took {name}: {hits:?}"
5118 );
5119 }
5120 } else {
5121 eprintln!(
5122 "SKIP the five-type fire count at preset {}: {hits:?}",
5123 crate::speed::speed()
5124 );
5125 }
5126 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5127 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
5128 if have_ffmpeg() {
5129 let theirs = ffmpeg_decode_luma(&stream, width, height);
5130 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5131 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
5132 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
5133 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
5134 panic!(
5135 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
5136 at % width,
5137 at / width,
5138 got[at],
5139 b[at],
5140 );
5141 }
5142 assert_eq!(
5143 got.len(),
5144 b.len(),
5145 "frame {i}: luma is {} samples, ffmpeg's is {}",
5146 got.len(),
5147 b.len()
5148 );
5149 }
5150 } else {
5151 eprintln!("SKIP the ffmpeg half: no ffmpeg");
5152 }
5153 crate::encode::force_screen(None);
5154 eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len());
5155 }
5156
5157 /// lane-txset2's witness: an INTER frame's luma transform units take BOTH
5158 /// types of the two-type inter set the writer already codes a symbol for
5159 /// (`TX_SET_INTER_3`: `IDTX` and `DCT_DCT`) at least once -- the fire
5160 /// count, class `gate-blind-to-feature` -- and both decoders reconstruct
5161 /// every frame sample-exact from the `tx_type` symbols that name them.
5162 /// Before this lane every inter luma unit was coded `DCT_DCT`.
5163 #[test]
5164 fn an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly() {
5165 // The lever is OFF at every preset (`speed::TX_TYPE_SEARCH_INTER`), so
5166 // this turns it on process-globally under the same exclusive lock the
5167 // presets take.
5168 let _knobs = crate::speed::knob_write();
5169 let _gate_lock = crate::stream::tests::lock_gate_counters();
5170 crate::encode::set_inter_tx_search(Some(true));
5171 let (width, height) = (320usize, 192usize);
5172 // Sharp steps that MOVE: the motion-compensated residual along a
5173 // moving edge is exactly where the identity transform beats a DCT,
5174 // and the flat plateaus between them predict to nothing at all.
5175 let sources: Vec<Picture> = (0..4)
5176 .map(|t| {
5177 let mut p = test_card(width, height, t * 3);
5178 for y in 0..height {
5179 for x in 0..width {
5180 let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) {
5181 (0, 0) => 16u16,
5182 (1, 0) => 235,
5183 (0, 1) => ((x + t) % 64 * 3) as u16,
5184 _ => ((y + t) % 64 * 3) as u16,
5185 };
5186 p.y[y * width + x] = v;
5187 }
5188 }
5189 p
5190 })
5191 .collect();
5192 let config = EncoderConfig {
5193 width,
5194 height,
5195 base_q_idx: 90,
5196 gop: 4,
5197 colour: Colour::Bt709Limited,
5198 tile_cols_log2: 0,
5199 tile_rows_log2: 0,
5200 };
5201 let mut enc = Av1Encoder::new(config).unwrap();
5202 let _ = crate::encode::take_inter_tx_type_hits();
5203 let mut stream = Vec::new();
5204 for packet in encode_all(&mut enc, &sources) {
5205 stream.extend_from_slice(&packet.data);
5206 }
5207 let hits = crate::encode::take_inter_tx_type_hits();
5208 crate::encode::set_inter_tx_search(None);
5209 for (name, ty) in [
5210 ("DCT_DCT", crate::transform::TxType::DctDct),
5211 ("IDTX", crate::transform::TxType::Idtx),
5212 ] {
5213 assert!(
5214 hits[ty as usize] > 0,
5215 "no inter luma transform unit was CODED {name}: {hits:?}"
5216 );
5217 }
5218 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5219 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
5220 if have_ffmpeg() {
5221 let theirs = ffmpeg_decode_luma(&stream, width, height);
5222 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5223 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
5224 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
5225 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
5226 panic!(
5227 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
5228 at % width,
5229 at / width,
5230 got[at],
5231 b[at],
5232 );
5233 }
5234 assert_eq!(
5235 got.len(),
5236 b.len(),
5237 "frame {i}: luma is {} samples, ffmpeg's is {}",
5238 got.len(),
5239 b.len()
5240 );
5241 }
5242 } else {
5243 eprintln!("SKIP the ffmpeg half: no ffmpeg");
5244 }
5245 eprintln!(
5246 "inter tx_type witness: hits {hits:?}, {} bytes",
5247 stream.len()
5248 );
5249 }
5250
5251 /// lane-txi's witness: a `reduced_tx_set = 0` frame codes the WIDER
5252 /// `tx_type` alphabets -- the seven-type `TX_SET_INTRA_1` at intra
5253 /// 8x8/4x4 and the twelve/sixteen-type inter sets at 16x16 and below --
5254 /// and both decoders reconstruct every frame sample-exact from them. The
5255 /// statement is that the types only those alphabets can NAME (`V_DCT`,
5256 /// `H_DCT`, and any inter type outside the two-type `DCT_IDTX`) are
5257 /// reachable at all, and that the header bit, the writer's set map and
5258 /// the search's pricer agree on which alphabet a symbol was coded into
5259 /// (class `wrong-alphabet-same-value`: a disagreement here changes no
5260 /// symbol VALUE and desyncs the arithmetic coder anyway).
5261 #[test]
5262 #[ignore = "sets process-global search levers: run it alone"]
5263 fn a_wide_tx_set_clip_codes_the_new_alphabets_both_decoders_read_exactly() {
5264 // Every lever below is process-global: the same exclusive lock the
5265 // presets take.
5266 let _knobs = crate::speed::knob_write();
5267 let _gate_lock = crate::stream::tests::lock_gate_counters();
5268 crate::encode::set_intra_tx_search(Some(true));
5269 crate::encode::set_inter_tx_search(Some(true));
5270 crate::encode::set_wide_tx_set(Some(true));
5271 let (width, height) = (320usize, 192usize);
5272 // The same moving hard-edge card the two narrow-set witnesses use:
5273 // vertical steps are what a 1-D `V_DCT`/`H_DCT` pass wins on, the
5274 // ramps are `ADST`'s and the moving plateaus `IDTX`'s.
5275 let sources: Vec<Picture> = (0..4)
5276 .map(|t| {
5277 let mut p = test_card(width, height, t * 3);
5278 for y in 0..height {
5279 for x in 0..width {
5280 let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) {
5281 (0, 0) => 16u16,
5282 (1, 0) => 235,
5283 (0, 1) => ((x + t) % 64 * 3) as u16,
5284 _ => ((y + t) % 64 * 3) as u16,
5285 };
5286 p.y[y * width + x] = v;
5287 }
5288 }
5289 p
5290 })
5291 .collect();
5292 let config = EncoderConfig {
5293 width,
5294 height,
5295 base_q_idx: 90,
5296 gop: 4,
5297 colour: Colour::Bt709Limited,
5298 tile_cols_log2: 0,
5299 tile_rows_log2: 0,
5300 };
5301 let mut enc = Av1Encoder::new(config).unwrap();
5302 let _ = crate::encode::take_tx_type_hits();
5303 let _ = crate::encode::take_inter_tx_type_hits();
5304 let mut stream = Vec::new();
5305 for packet in encode_all(&mut enc, &sources) {
5306 stream.extend_from_slice(&packet.data);
5307 }
5308 let (intra, inter) = (
5309 crate::encode::take_tx_type_hits(),
5310 crate::encode::take_inter_tx_type_hits(),
5311 );
5312 crate::encode::set_wide_tx_set(None);
5313 crate::encode::set_inter_tx_search(None);
5314 crate::encode::set_intra_tx_search(None);
5315 eprintln!(
5316 "wide tx_type witness: intra {intra:?} inter {inter:?}, {} bytes",
5317 stream.len()
5318 );
5319 // The fire count is preset 0's, for the reason the five-type witness
5320 // spells out: a faster preset prunes the modes and partitions a type
5321 // wins on before it is ever priced (class `gate-blind-to-feature`).
5322 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 {
5323 use crate::transform::TxType;
5324 let wide_only = |hits: &[usize; 16]| -> usize {
5325 hits[TxType::VDct as usize] + hits[TxType::HDct as usize]
5326 };
5327 assert!(
5328 wide_only(&intra) > 0,
5329 "no intra luma unit took a 1-D DCT, the type only TX_SET_INTRA_1 names: {intra:?}"
5330 );
5331 // The INTER units of this same frame are coded into the
5332 // twelve/sixteen-symbol alphabets too (the header bit widens
5333 // every luma set at once), but their SEARCH still offers the
5334 // two-type list -- see `encode::inter_luma_set`'s note on the
5335 // reference-slot refusal the wider inter candidates trip. So the
5336 // statement here is that those units still decode sample-exact
5337 // out of the wider alphabet, which the two decoders below make.
5338 assert!(
5339 inter.iter().sum::<usize>() > 0,
5340 "the clip coded no inter luma transform unit at all: {inter:?}"
5341 );
5342 } else {
5343 eprintln!(
5344 "SKIP the wide-alphabet fire count at preset {}",
5345 crate::speed::speed()
5346 );
5347 }
5348 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5349 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
5350 if have_ffmpeg() {
5351 let theirs = ffmpeg_decode_luma(&stream, width, height);
5352 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5353 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
5354 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
5355 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
5356 panic!(
5357 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
5358 at % width,
5359 at / width,
5360 got[at],
5361 b[at],
5362 );
5363 }
5364 assert_eq!(
5365 got.len(),
5366 b.len(),
5367 "frame {i}: luma is {} samples, ffmpeg's is {}",
5368 got.len(),
5369 b.len()
5370 );
5371 }
5372 } else {
5373 eprintln!("SKIP the ffmpeg half: no ffmpeg");
5374 }
5375 }
5376 /// lane-intertx's witness: on a clip the screen detector calls
5377 /// NON-screen, the inter luma search offers the wider
5378 /// `reduced_tx_set = 0` alphabets and CODES a 1-D `V_DCT`/`H_DCT` unit
5379 /// (a `coded > 0` guard on the committed-winners census, class
5380 /// `gate-blind-to-feature`), the block's chroma transforms inherit that
5381 /// type reduced to the chroma size's set against the frame's own honest
5382 /// header bit, and BOTH decoders reconstruct every frame sample-exact on
5383 /// ALL THREE planes -- chroma is the plane the inheritance desync
5384 /// corrupts, so luma-only comparisons cannot see it.
5385 #[test]
5386 #[ignore = "sets process-global search levers: run it alone"]
5387 fn a_non_screen_inter_clip_codes_a_one_d_type_both_decoders_read_every_plane_exactly() {
5388 let _knobs = crate::speed::knob_write();
5389 let _gate_lock = crate::stream::tests::lock_gate_counters();
5390 crate::encode::set_intra_tx_search(Some(true));
5391 crate::encode::set_inter_tx_search(Some(true));
5392 crate::encode::set_wide_tx_set(Some(true));
5393 crate::encode::force_screen(Some(false));
5394 let (width, height) = (320usize, 192usize);
5395 // The wide witness's moving card: vertical steps (where a 1-D
5396 // `V_DCT`/`H_DCT` beats the 2-D DCT on the motion-compensated
5397 // residual), ramps (`ADST`) and moving plateaus (`IDTX`), translated
5398 // a few samples per frame so the inter search sees real motion.
5399 let sources: Vec<Picture> = (0..4)
5400 .map(|t| {
5401 let mut p = test_card(width, height, t * 3);
5402 for y in 0..height {
5403 for x in 0..width {
5404 let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) {
5405 (0, 0) => 16u16,
5406 (1, 0) => 235,
5407 (0, 1) => ((x + t) % 64 * 3) as u16,
5408 _ => ((y + t) % 64 * 3) as u16,
5409 };
5410 p.y[y * width + x] = v;
5411 }
5412 }
5413 p
5414 })
5415 .collect();
5416 let config = EncoderConfig {
5417 width,
5418 height,
5419 base_q_idx: 90,
5420 gop: 4,
5421 colour: Colour::Bt709Limited,
5422 tile_cols_log2: 0,
5423 tile_rows_log2: 0,
5424 };
5425 let mut enc = Av1Encoder::new(config).unwrap();
5426 let _ = crate::encode::take_inter_tx_type_hits();
5427 let mut stream = Vec::new();
5428 for packet in encode_all(&mut enc, &sources) {
5429 stream.extend_from_slice(&packet.data);
5430 }
5431 let hits = crate::encode::take_inter_tx_type_hits();
5432 crate::encode::force_screen(None);
5433 crate::encode::set_wide_tx_set(None);
5434 crate::encode::set_inter_tx_search(None);
5435 crate::encode::set_intra_tx_search(None);
5436 use crate::transform::TxType;
5437 eprintln!(
5438 "inter wide-set witness: inter hits {hits:?}, {} bytes",
5439 stream.len()
5440 );
5441 assert!(
5442 hits[TxType::Idtx as usize] > 0,
5443 "no inter luma unit was CODED IDTX: {hits:?}"
5444 );
5445 assert!(
5446 hits[TxType::VDct as usize] + hits[TxType::HDct as usize] > 0,
5447 "no inter luma unit was CODED a 1-D type -- the wider search \
5448 never fired on non-screen content (class gate-blind-to-feature): {hits:?}"
5449 );
5450 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5451 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
5452 if have_ffmpeg() {
5453 let theirs = ffmpeg_decode_planes(&stream, width, height);
5454 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5455 let (cw, ch) = (width / 2, height / 2);
5456 for (i, (a, (y, u, v))) in ours.iter().zip(&theirs).enumerate() {
5457 for (name, got16, want, w) in [
5458 ("y", &a.y, y, width),
5459 ("u", &a.u, u, cw),
5460 ("v", &a.v, v, ch),
5461 ] {
5462 let got: Vec<u8> = got16.iter().map(|&s| s as u8).collect();
5463 assert_eq!(got.len(), want.len(), "frame {i} {name} plane size");
5464 if let Some(at) = got.iter().zip(want.iter()).position(|(x, y)| x != y) {
5465 panic!(
5466 "frame {i}: {name} differs first at ({}, {}): ours {} vs ffmpeg {}",
5467 at % w,
5468 at / w,
5469 got[at],
5470 want[at],
5471 );
5472 }
5473 }
5474 }
5475 } else {
5476 eprintln!("SKIP the ffmpeg half: no ffmpeg");
5477 }
5478 }
5479
5480 /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct
5481 /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from
5482 /// its neighbour (a preset that changes no byte is a preset that buys no
5483 /// wall: class `gate-blind-to-feature`). Preset 0's bytes are the
5484 /// full-search ones, which is the cheap in-suite statement of the byte
5485 /// pins' rule.
5486 ///
5487 /// Ignored by default because the preset is PROCESS-GLOBAL
5488 /// ([`crate::speed`]): flipping it while the suite's other tests encode
5489 /// in parallel would move their bytes under them. Run it on its own:
5490 /// `cargo test -p ec-av1 --release -- --ignored every_speed_preset`.
5491 #[test]
5492 #[ignore = "sets the process-global speed preset: run it alone"]
5493 fn every_speed_preset_decodes_sample_exact_through_both_decoders() {
5494 let _knobs = crate::speed::knob_write();
5495 let _gate_lock = crate::stream::tests::lock_gate_counters();
5496 let (width, height) = (640usize, 384usize);
5497 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
5498 let mut sizes: Vec<(u8, usize)> = Vec::new();
5499 for speed in [0u8, 3, 6, 10] {
5500 let config = EncoderConfig {
5501 width,
5502 height,
5503 base_q_idx: 120,
5504 gop: 4,
5505 colour: Colour::Bt709Limited,
5506 tile_cols_log2: 1,
5507 tile_rows_log2: 0,
5508 };
5509 let mut enc = Av1Encoder::with_speed(config, speed).unwrap();
5510 let mut stream = Vec::new();
5511 for packet in encode_all(&mut enc, &sources) {
5512 stream.extend_from_slice(&packet.data);
5513 }
5514 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5515 assert_eq!(
5516 ours.len(),
5517 sources.len(),
5518 "speed {speed}: our decoder's frames"
5519 );
5520 if have_ffmpeg() {
5521 let theirs = ffmpeg_decode_luma(&stream, width, height);
5522 assert_eq!(
5523 theirs.len(),
5524 sources.len(),
5525 "speed {speed}: ffmpeg's frames"
5526 );
5527 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
5528 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
5529 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
5530 panic!(
5531 "speed {speed} frame {i}: luma differs first at ({}, {}): \
5532 ours {} vs ffmpeg {}",
5533 at % width,
5534 at / width,
5535 got[at],
5536 b[at],
5537 );
5538 }
5539 assert_eq!(
5540 got.len(),
5541 b.len(),
5542 "speed {speed} frame {i}: luma is {} samples, ffmpeg's is {}",
5543 got.len(),
5544 b.len()
5545 );
5546 }
5547 } else {
5548 eprintln!("SKIP the ffmpeg half of speed {speed}: no ffmpeg");
5549 }
5550 eprintln!(
5551 "speed {speed}: {} bytes [{}]",
5552 stream.len(),
5553 crate::speed::levers(speed).join(", ")
5554 );
5555 sizes.push((speed, stream.len()));
5556 }
5557 crate::speed::set_speed(0);
5558 for w in sizes.windows(2) {
5559 assert_ne!(
5560 w[0].1, w[1].1,
5561 "speed {} and {} coded the same bytes: the preset changed no decision",
5562 w[0].0, w[1].0
5563 );
5564 }
5565 }
5566
5567 /// What tiles and tile threads are worth at the size the editor exports
5568 /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall
5569 /// per cell. Ignored by default (minutes).
5570 #[test]
5571 #[ignore = "1080p wall table: minutes, run it with --ignored"]
5572 fn tile_wall_table_at_1080p() {
5573 let _knobs = crate::speed::knob_write();
5574 let _gate_lock = crate::stream::tests::lock_gate_counters();
5575 let (width, height) = (1920usize, 1080usize);
5576 let Some(sources) = h264_clip_frames(width, height, 8) else {
5577 eprintln!("SKIP tile_wall_table_at_1080p: no fixture");
5578 return;
5579 };
5580 let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)];
5581 let threadings = [1usize, 2, 4, 8];
5582 let mut table: Vec<(String, usize, f64, usize)> = Vec::new();
5583 for pass in 0..2 {
5584 for &(cols_log2, rows_log2) in &layouts {
5585 for &threads in &threadings {
5586 crate::par::set_tile_threads(threads);
5587 let config = EncoderConfig {
5588 width,
5589 height,
5590 base_q_idx: 120,
5591 gop: 8,
5592 colour: Colour::Bt709Limited,
5593 tile_cols_log2: cols_log2,
5594 tile_rows_log2: rows_log2,
5595 };
5596 let mut enc = Av1Encoder::new(config).unwrap();
5597 let start = std::time::Instant::now();
5598 let mut bytes = 0usize;
5599 for packet in encode_all(&mut enc, &sources) {
5600 bytes += packet.data.len();
5601 }
5602 let wall = start.elapsed().as_secs_f64();
5603 let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2);
5604 match table.iter_mut().find(|r| r.0 == name && r.1 == threads) {
5605 Some(row) => row.2 = row.2.min(wall),
5606 None => table.push((name, threads, wall, bytes)),
5607 }
5608 let _ = pass;
5609 }
5610 }
5611 }
5612 crate::par::set_tile_threads(1);
5613 eprintln!("| tiles | threads | wall (s, best of 2) | bytes |");
5614 for (name, threads, wall, bytes) in &table {
5615 eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |");
5616 }
5617 }
5618
5619 /// The tiles of a frame are entropy-independent, so the bytes must not
5620 /// depend on how many workers wrote them: the same stream at one tile
5621 /// thread and at four, per layout.
5622 #[test]
5623 fn tile_bytes_do_not_depend_on_the_thread_count() {
5624 let _knobs = crate::speed::knob_write();
5625 let _gate_lock = crate::stream::tests::lock_gate_counters();
5626 let (width, height) = (320usize, 192usize);
5627 let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect();
5628 let coded = |threads: usize, cols_log2: u32, rows_log2: u32| {
5629 crate::par::set_tile_threads(threads);
5630 let config = EncoderConfig {
5631 width,
5632 height,
5633 base_q_idx: 120,
5634 gop: 3,
5635 colour: Colour::Bt709Limited,
5636 tile_cols_log2: cols_log2,
5637 tile_rows_log2: rows_log2,
5638 };
5639 let mut enc = Av1Encoder::new(config).unwrap();
5640 let mut stream = Vec::new();
5641 for packet in encode_all(&mut enc, &sources) {
5642 stream.extend_from_slice(&packet.data);
5643 }
5644 stream
5645 };
5646 for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] {
5647 let one = coded(1, cols_log2, rows_log2);
5648 let four = coded(4, cols_log2, rows_log2);
5649 assert_eq!(
5650 one,
5651 four,
5652 "{}x{} tiles: {} bytes at one thread, {} at four",
5653 1 << cols_log2,
5654 1 << rows_log2,
5655 one.len(),
5656 four.len()
5657 );
5658 }
5659 crate::par::set_tile_threads(1);
5660 }
5661
5662 /// What the per-tile search (lane-av1tsearch) is worth in wall and in
5663 /// frames per second at the editor's own export sizes: every tile layout
5664 /// crossed with every tile-thread count, plus librav1e at the matching
5665 /// `tile_cols`/`tile_rows`/`threads` as the reference point. Two passes
5666 /// over the whole table (A,B,A,B... rather than AA,BB) with the best of
5667 /// the two kept, so a thermal drift cannot order the rows.
5668 ///
5669 /// Measurement, not a pass/fail gate: it asserts only that every cell
5670 /// produced a stream.
5671 #[test]
5672 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
5673 fn tile_search_wall_1080p() {
5674 let _knobs = crate::speed::knob_write();
5675 tile_search_wall(
5676 1920,
5677 1080,
5678 12,
5679 &[(0, 0), (1, 0), (1, 1), (2, 1)],
5680 &[1, 2, 4, 8],
5681 );
5682 }
5683
5684 /// The same table at the 4K frame size the editor exports (3840x1608),
5685 /// at the two layouts with enough tiles to fill this box.
5686 #[test]
5687 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
5688 fn tile_search_wall_4k() {
5689 let _knobs = crate::speed::knob_write();
5690 tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]);
5691 }
5692
5693 /// lane-av1fpar: the frame-level FILTER stage is banded across the same
5694 /// workers the tile search uses (`par::override_filter_threads`), so the
5695 /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in
5696 /// pieces. Every piece is a disjoint band of the same integers, so the
5697 /// stream must not move -- at a size that crops and is several superblock
5698 /// rows tall, which is what makes the bands non-trivial.
5699 #[test]
5700 fn filter_stage_bytes_do_not_depend_on_the_thread_count() {
5701 let _knobs = crate::speed::knob_write();
5702 let _gate_lock = crate::stream::tests::lock_gate_counters();
5703 let (width, height) = (384usize, 288usize);
5704 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
5705 let coded = |threads: usize| {
5706 crate::par::set_tile_threads(threads);
5707 let config = EncoderConfig {
5708 width,
5709 height,
5710 base_q_idx: 120,
5711 gop: 2,
5712 colour: Colour::Bt709Limited,
5713 tile_cols_log2: 0,
5714 tile_rows_log2: 0,
5715 };
5716 let mut enc = Av1Encoder::new(config).unwrap();
5717 let mut stream = Vec::new();
5718 for packet in encode_all(&mut enc, &sources) {
5719 stream.extend_from_slice(&packet.data);
5720 }
5721 stream
5722 };
5723 // One tile, so only the filter stage can differ between these.
5724 let one = coded(1);
5725 for threads in [2usize, 4, 8] {
5726 assert_eq!(
5727 one,
5728 coded(threads),
5729 "the filter stage moved at {threads} threads"
5730 );
5731 }
5732 crate::par::set_tile_threads(1);
5733 }
5734
5735 /// lane-av1fpar: the filter search scores its ~30 candidates by replaying
5736 /// the loop filters on one captured reconstruction instead of decoding
5737 /// the coded tile again per candidate. The replay must be that decode,
5738 /// byte for byte -- including at a size that CROPS (1080 and 1608 both
5739 /// pad to a superblock row, i.e. every export size the editor uses),
5740 /// which is the arm this lane opened.
5741 #[test]
5742 fn filter_replay_codes_the_same_stream_as_a_full_decode() {
5743 let _knobs = crate::speed::knob_read();
5744 let _gate_lock = crate::stream::tests::lock_gate_counters();
5745 let run = |width: usize, height: usize, off: bool| {
5746 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
5747 crate::decode::set_filter_replay_disabled(off);
5748 let config = EncoderConfig {
5749 width,
5750 height,
5751 base_q_idx: 120,
5752 gop: 2,
5753 colour: Colour::Bt709Limited,
5754 tile_cols_log2: 0,
5755 tile_rows_log2: 0,
5756 };
5757 let mut enc = Av1Encoder::new(config).unwrap();
5758 let mut stream = Vec::new();
5759 for packet in encode_all(&mut enc, &sources) {
5760 stream.extend_from_slice(&packet.data);
5761 }
5762 crate::decode::set_filter_replay_disabled(false);
5763 stream
5764 };
5765 // 320x160 crops (the coding surface is 320x192, one superblock row
5766 // taller); 320x192 is a whole number of superblocks, the shape the
5767 // replay already covered.
5768 for (width, height) in [(320usize, 160usize), (320, 192)] {
5769 let replayed = run(width, height, false);
5770 let decoded = run(width, height, true);
5771 assert_eq!(
5772 replayed,
5773 decoded,
5774 "{width}x{height}: the filter replay is not the decode it stands in for \
5775 ({} bytes replayed, {} decoded)",
5776 replayed.len(),
5777 decoded.len(),
5778 );
5779 }
5780 }
5781
5782 /// lane-av1cap: the filter stage's FINAL replay -- the one that replaced
5783 /// the capture decode -- against that decode. `set_verify_final_replay`
5784 /// makes `encode::pick_and_apply_filters` run both on every frame and
5785 /// assert, per frame, that the spliced picture and the two filter stages
5786 /// the loop-restoration search reads are bit-identical.
5787 #[test]
5788 fn filter_replay_final_matches_the_capture_decode() {
5789 let _knobs = crate::speed::knob_read();
5790 let _gate_lock = crate::stream::tests::lock_gate_counters();
5791 let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| {
5792 let config = EncoderConfig {
5793 width,
5794 height,
5795 base_q_idx: 120,
5796 gop: 2,
5797 colour: Colour::Bt709Limited,
5798 tile_cols_log2: tiles.0,
5799 tile_rows_log2: tiles.1,
5800 };
5801 let mut enc = Av1Encoder::new(config).unwrap();
5802 for packet in encode_all(&mut enc, sources) {
5803 assert!(!packet.data.is_empty());
5804 }
5805 };
5806 crate::decode::set_verify_final_replay(true);
5807 // 320x160 crops (its coding surface is one superblock row taller);
5808 // 320x192 is a whole number of superblocks.
5809 for (width, height) in [(320usize, 160usize), (320, 192)] {
5810 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
5811 run(&sources, width, height, (0, 0));
5812 }
5813 // Real gate content, where the CDEF preset search actually chooses
5814 // `bits > 0` and the tile is re-coded, one tile and four.
5815 if let Some(sources) = h264_clip_frames(640, 384, 3) {
5816 run(&sources, 640, 384, (0, 0));
5817 run(&sources, 640, 384, (1, 1));
5818 } else {
5819 eprintln!("SKIP the gate-clip arm: no fixture or no ffmpeg");
5820 }
5821 crate::decode::set_verify_final_replay(false);
5822 }
5823
5824 /// lane-av1fpar: where a frame's wall actually goes, stage by stage --
5825 /// the per-tile search, the tile write, the frame-level filter search
5826 /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture
5827 /// decode the loop-restoration search rides on, and that search itself.
5828 /// Measurement, not a pass/fail gate.
5829 #[test]
5830 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
5831 fn filter_stage_wall_1080p() {
5832 let _knobs = crate::speed::knob_write();
5833 filter_stage_wall(1920, 1080, 8, (2, 1), &[8]);
5834 }
5835
5836 #[test]
5837 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
5838 fn filter_stage_wall_4k() {
5839 let _knobs = crate::speed::knob_write();
5840 filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]);
5841 }
5842
5843 /// The same breakdown at the real films' own crop size. With
5844 /// `EC_AV1_WALL_CLIP` pointing at a film window this is the film row; with
5845 /// it unset it is the colour-bar fixture at the same size, which is what
5846 /// makes the pair a comparison rather than a number.
5847 #[test]
5848 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
5849 fn filter_stage_wall_film() {
5850 let _knobs = crate::speed::knob_write();
5851 filter_stage_wall(1920, 768, 4, (2, 1), &[8]);
5852 }
5853
5854 fn filter_stage_wall(
5855 width: usize,
5856 height: usize,
5857 frames: usize,
5858 (cols_log2, rows_log2): (u32, u32),
5859 threads: &[usize],
5860 ) {
5861 let _gate_lock = crate::stream::tests::lock_gate_counters();
5862 let Some(sources) = h264_clip_frames(width, height, frames) else {
5863 eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg");
5864 return;
5865 };
5866 crate::par::set_stage_times(true);
5867 for &t in threads {
5868 crate::par::set_tile_threads(t);
5869 let config = EncoderConfig {
5870 width,
5871 height,
5872 base_q_idx: 120,
5873 gop: frames,
5874 colour: Colour::Bt709Limited,
5875 tile_cols_log2: cols_log2,
5876 tile_rows_log2: rows_log2,
5877 };
5878 let mut enc = Av1Encoder::new(config).unwrap();
5879 let _ = crate::par::take_stage_ns();
5880 let start = std::time::Instant::now();
5881 for packet in encode_all(&mut enc, &sources) {
5882 assert!(!packet.data.is_empty());
5883 }
5884 let wall = start.elapsed().as_secs_f64();
5885 let ns = crate::par::take_stage_ns();
5886 let ms = |i: usize| ns[i] as f64 / 1e6;
5887 eprintln!(
5888 "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \
5889 {wall:.2}s wall, {:.2} fps",
5890 1 << cols_log2,
5891 1 << rows_log2,
5892 frames as f64 / wall,
5893 );
5894 eprintln!("| stage | ms | ms/frame | % of wall |");
5895 for (i, name) in crate::par::STAGES.iter().enumerate() {
5896 eprintln!(
5897 "| {name} | {:.0} | {:.1} | {:.1}% |",
5898 ms(i),
5899 ms(i) / frames as f64,
5900 100.0 * ms(i) / (wall * 1e3),
5901 );
5902 }
5903 // Top-level stages only (the deblock/CDEF/SSE rows are inside
5904 // the filter-search total); the rest is per-frame setup, the
5905 // source conversion and the splice.
5906 let top: f64 = [
5907 crate::par::S_TILE_SEARCH,
5908 crate::par::S_TILE_WRITE,
5909 crate::par::S_FILTER,
5910 crate::par::S_CAPTURE,
5911 crate::par::S_LR,
5912 ]
5913 .iter()
5914 .map(|&i| ms(i))
5915 .sum();
5916 eprintln!(
5917 "accounted {:.1}% of wall; outside the tile search {:.1}%",
5918 100.0 * top / (wall * 1e3),
5919 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)),
5920 );
5921 }
5922 crate::par::set_stage_times(false);
5923 crate::par::set_tile_threads(1);
5924 }
5925
5926 fn tile_search_wall(
5927 width: usize,
5928 height: usize,
5929 frames: usize,
5930 layouts: &[(u32, u32)],
5931 threads: &[usize],
5932 ) {
5933 let _gate_lock = crate::stream::tests::lock_gate_counters();
5934 let Some(sources) = h264_clip_frames(width, height, frames) else {
5935 eprintln!("SKIP the tile-search wall table: no fixture or no ffmpeg");
5936 return;
5937 };
5938 let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) {
5939 crate::par::set_tile_threads(t);
5940 let config = EncoderConfig {
5941 width,
5942 height,
5943 base_q_idx: 120,
5944 gop: frames,
5945 colour: Colour::Bt709Limited,
5946 tile_cols_log2: cols_log2,
5947 tile_rows_log2: rows_log2,
5948 };
5949 let mut enc = Av1Encoder::new(config).unwrap();
5950 let start = std::time::Instant::now();
5951 let mut bytes = 0usize;
5952 for packet in encode_all(&mut enc, &sources) {
5953 bytes += packet.data.len();
5954 }
5955 (start.elapsed(), bytes)
5956 };
5957 let cells: Vec<((u32, u32), usize)> = layouts
5958 .iter()
5959 .flat_map(|&l| threads.iter().map(move |&t| (l, t)))
5960 .collect();
5961 let mut best: Vec<Option<(std::time::Duration, usize)>> = vec![None; cells.len()];
5962 for _pass in 0..2 {
5963 for (i, &((c, r), t)) in cells.iter().enumerate() {
5964 let got = run(c, r, t);
5965 assert!(
5966 got.1 > 0,
5967 "{}x{} tiles at {t} threads: empty stream",
5968 1 << c,
5969 1 << r
5970 );
5971 if best[i].is_none_or(|(w, _)| got.0 < w) {
5972 best[i] = Some(got);
5973 }
5974 }
5975 }
5976 crate::par::set_tile_threads(1);
5977 eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes");
5978 eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |");
5979 let base = best[0].expect("the first cell ran").0.as_secs_f64();
5980 for (i, &((c, r), t)) in cells.iter().enumerate() {
5981 let (wall, bytes) = best[i].expect("every cell ran");
5982 let secs = wall.as_secs_f64();
5983 eprintln!(
5984 "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |",
5985 1 << c,
5986 1 << r,
5987 1 << (c + r),
5988 frames as f64 / secs,
5989 base / secs,
5990 );
5991 }
5992 // Parallel efficiency per layout: what the extra threads actually
5993 // took off that layout's own single-threaded wall, and so what share
5994 // of the added cores sat idle.
5995 for &(c, r) in layouts {
5996 let one = cells
5997 .iter()
5998 .position(|&(l, t)| l == (c, r) && t == threads[0])
5999 .map(|i| best[i].expect("cell").0.as_secs_f64());
6000 let Some(one) = one else { continue };
6001 for &t in &threads[1..] {
6002 let i = cells
6003 .iter()
6004 .position(|&(l, tt)| l == (c, r) && tt == t)
6005 .expect("cell");
6006 let secs = best[i].expect("cell").0.as_secs_f64();
6007 let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64;
6008 let speedup = one / secs;
6009 eprintln!(
6010 "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \
6011 idle share {:.0}%",
6012 1 << c,
6013 1 << r,
6014 threads[0],
6015 100.0 * (1.0 - speedup / workers).max(0.0),
6016 );
6017 }
6018 }
6019 rav1e_wall_reference(width, height, frames, layouts, threads);
6020 }
6021
6022 /// librav1e at the same sizes, layouts and thread counts, through ffmpeg
6023 /// -- the reference the wall table is read against.
6024 fn rav1e_wall_reference(
6025 width: usize,
6026 height: usize,
6027 frames: usize,
6028 layouts: &[(u32, u32)],
6029 threads: &[usize],
6030 ) {
6031 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
6032 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
6033 let listed = Command::new("ffmpeg")
6034 .args(["-hide_banner", "-encoders"])
6035 .output();
6036 let has_rav1e = listed
6037 .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e"))
6038 .unwrap_or(false);
6039 if !has_rav1e || !clip.exists() {
6040 eprintln!("SKIP the rav1e reference: no librav1e or no fixture");
6041 return;
6042 }
6043 eprintln!("| rav1e layout | threads | wall | fps | bytes |");
6044 for &(c, r) in layouts {
6045 for &t in threads {
6046 let out =
6047 std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id()));
6048 let params = format!(
6049 "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}",
6050 1 << c,
6051 1 << r
6052 );
6053 let start = std::time::Instant::now();
6054 let status = Command::new("ffmpeg")
6055 .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()])
6056 .args(["-frames:v", &frames.to_string()])
6057 .args(["-vf", &format!("scale={width}:{height}")])
6058 .args(["-c:v", "librav1e", "-rav1e-params", &params])
6059 .arg(out.to_str().unwrap())
6060 .output()
6061 .expect("ffmpeg failed to run");
6062 let secs = start.elapsed().as_secs_f64();
6063 if !status.status.success() {
6064 eprintln!(
6065 "| {}x{} | {t} | FAILED: {} |",
6066 1 << c,
6067 1 << r,
6068 String::from_utf8_lossy(&status.stderr)
6069 .lines()
6070 .last()
6071 .unwrap_or("")
6072 );
6073 continue;
6074 }
6075 let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
6076 let _ = std::fs::remove_file(&out);
6077 eprintln!(
6078 "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |",
6079 1 << c,
6080 1 << r,
6081 frames as f64 / secs
6082 );
6083 }
6084 }
6085 }
6086
6087 /// The same round trip at a real 1920x1080 crop of the gate's own clip
6088 /// -- the size the editor's export actually runs at, where a tile grid
6089 /// is worth having. Ignored by default only for its wall (a 1080p
6090 /// encode of three pictures), not for any weakness in the check.
6091 #[test]
6092 #[ignore = "1080p encode: minutes, run it with --ignored"]
6093 fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() {
6094 let _knobs = crate::speed::knob_read();
6095 let (width, height) = (1920usize, 1080usize);
6096 let Some(sources) = h264_clip_frames(width, height, 3) else {
6097 eprintln!("SKIP the 1080p tile round trip: no fixture");
6098 return;
6099 };
6100 for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] {
6101 let config = EncoderConfig {
6102 width,
6103 height,
6104 base_q_idx: 120,
6105 gop: 3,
6106 colour: Colour::Bt709Limited,
6107 tile_cols_log2: cols_log2,
6108 tile_rows_log2: rows_log2,
6109 };
6110 let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
6111 let mut enc = Av1Encoder::new(config).unwrap();
6112 let mut stream = Vec::new();
6113 for packet in encode_all(&mut enc, &sources) {
6114 stream.extend_from_slice(&packet.data);
6115 }
6116 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
6117 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
6118 if !have_ffmpeg() {
6119 eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg");
6120 continue;
6121 }
6122 let theirs = ffmpeg_decode_luma(&stream, width, height);
6123 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
6124 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
6125 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
6126 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
6127 panic!(
6128 "1080p {layout} frame {i}: luma differs first at ({}, {})",
6129 at % width,
6130 at / width
6131 );
6132 }
6133 assert_eq!(
6134 got.len(),
6135 b.len(),
6136 "1080p {layout} frame {i}: luma is {} samples, ffmpeg's is {}",
6137 got.len(),
6138 b.len()
6139 );
6140 }
6141 eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len());
6142 }
6143 }
6144
6145 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
6146 /// produces a smaller stream or a worse mean PSNR than a lower one, on
6147 /// the same real clip.
6148 #[test]
6149 fn quality_target_is_monotone_in_bytes_and_psnr() {
6150 let _knobs = crate::speed::knob_read();
6151 if !have_ffmpeg() {
6152 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg");
6153 return;
6154 }
6155 let (width, height) = (640, 384);
6156 let Some(pictures) = h264_clip_frames(width, height, 8) else {
6157 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture");
6158 return;
6159 };
6160 let mut prev_bytes = 0usize;
6161 let mut prev_psnr = 0.0f64;
6162 for quality in [20u8, 50, 80] {
6163 let config = EncoderConfig {
6164 width,
6165 height,
6166 base_q_idx: 100,
6167 gop: 8,
6168 colour: Colour::Bt709Limited,
6169 tile_cols_log2: 0,
6170 tile_rows_log2: 0,
6171 };
6172 let mut enc =
6173 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
6174 let mut stream = Vec::new();
6175 let mut total_bytes = 0usize;
6176 for packet in encode_all(&mut enc, &pictures) {
6177 total_bytes += packet.data.len();
6178 stream.extend_from_slice(&packet.data);
6179 }
6180 let decoded = ffmpeg_decode_luma(&stream, width, height);
6181 assert_eq!(
6182 decoded.len(),
6183 pictures.len(),
6184 "quality {quality}: dav1d frame count"
6185 );
6186 let mean_psnr: f64 = decoded
6187 .iter()
6188 .zip(&pictures)
6189 .map(|(d, p)| {
6190 let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect();
6191 psnr(&d16, &p.y)
6192 })
6193 .sum::<f64>()
6194 / decoded.len() as f64;
6195 assert!(
6196 total_bytes >= prev_bytes,
6197 "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}"
6198 );
6199 assert!(
6200 mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours
6201 "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB"
6202 );
6203 prev_bytes = total_bytes;
6204 prev_psnr = mean_psnr;
6205 }
6206 }
6207}