forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.4 MiB35bdf35Tahinli2 months ago3757 commits

encoder.rs6505 lines, 290.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<Box<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///
1481/// lane-av1enchang: the `CdfSnapshot` is BOXED, not held by value. Eight
1482/// inline copies made [`Av1Encoder`] 139960 bytes, and that struct is
1483/// returned by value through three nested `Result<Self>` constructors
1484/// ([`Av1Encoder::with_pyramid_and_rate_target`] ->
1485/// [`Av1Encoder::with_pyramid`] -> [`Av1Encoder::new`]), so an unoptimized
1486/// build put several of those on the stack at once: the pyramid path
1487/// overflowed libtest's 2 MiB test thread and aborted the whole crate suite
1488/// with `fatal runtime error: stack overflow`. One heap box per DPB slot
1489/// brings the struct from 139960 bytes down to 18168 (measured). The tables'
1490/// VALUES are untouched.
1491#[derive(Debug, Clone)]
1492struct DpbSlot {
1493 picture: Picture,
1494 order_hint: u32,
1495 cdfs: Box<crate::encode::CdfSnapshot>,
1496}
1497
1498/// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are
1499/// `Send` but `!Sync`): it can move to another thread, it just cannot be
1500/// shared by reference across threads.
1501const _: fn() = || {
1502 fn assert_send<T: Send>() {}
1503 assert_send::<Av1Encoder>();
1504};
1505
1506impl Av1Encoder {
1507 /// [`Av1Encoder::new`] at a SPEED PRESET (`speed` 0..=10, rav1e's scale:
1508 /// 0 is the full search this encoder has always run and is byte for byte
1509 /// identical to [`Av1Encoder::new`]; higher presets switch search levers
1510 /// off, [`crate::speed::levers`] naming which).
1511 ///
1512 /// The preset is process-global (the tile search reads it from worker
1513 /// threads -- see [`crate::speed`]), so it is set here for every encode
1514 /// that follows on this process, and two encoders at different speeds
1515 /// must not run concurrently. `EC_AV1_SPEED=<n>` is the same knob for a
1516 /// caller that does not construct the encoder itself.
1517 ///
1518 /// # Errors
1519 /// [`Av1Encoder::new`]'s.
1520 pub fn with_speed(config: EncoderConfig, speed: u8) -> Result<Self> {
1521 crate::speed::set_speed(speed);
1522 Self::new(config)
1523 }
1524
1525 /// # Errors
1526 /// Returns an error when `config.width`/`config.height` are zero, odd,
1527 /// or larger than the 16-bit frame size an AV1 sequence header carries,
1528 /// or when `config.gop` is zero (there would be no picture to code the
1529 /// next key frame from a cadence of).
1530 pub fn new(config: EncoderConfig) -> Result<Self> {
1531 if config.gop == 0 {
1532 return Err(Error::unsupported("AV1 encode", "gop must be at least 1"));
1533 }
1534 // Validate the geometry the same way the picture-level entry points
1535 // do, before the first `encode()` call rather than only surfacing it
1536 // then.
1537 Picture::grey(config.width, config.height).check_even()?;
1538 // A tile is a whole number of superblocks, so a frame cannot carry
1539 // more tile columns (rows) than it has 64x64 superblocks across
1540 // (down) -- the header's own `max_log2_tile_cols` bound (spec
1541 // 5.9.15), refused here rather than at the first `encode()` call.
1542 let sb_cols = config.width.div_ceil(64) as u32;
1543 let sb_rows = config.height.div_ceil(64) as u32;
1544 if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows {
1545 return Err(Error::unsupported(
1546 "AV1 encode",
1547 format!(
1548 "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has",
1549 1 << config.tile_cols_log2,
1550 1 << config.tile_rows_log2
1551 ),
1552 ));
1553 }
1554 Ok(Self {
1555 carried_cdfs: None,
1556 golden: None,
1557 prev2: None,
1558 color_config: config.colour.color_config(),
1559 config,
1560 reference: None,
1561 next_index: 0,
1562 rate_loop: None,
1563 fctx: crate::decode::FrameCtx::for_encoder(),
1564 pyramid: None,
1565 dpb: [const { None }; 8],
1566 pending: Vec::new(),
1567 ready: Vec::new(),
1568 held: std::collections::VecDeque::new(),
1569 anchor: 0,
1570 leaf_hist: Vec::new(),
1571 next_dts: 0,
1572 collected: None,
1573 })
1574 }
1575
1576 /// [`Av1Encoder::new`] in pyramid mode: pictures are coded out of display
1577 /// order, so a call to [`Av1Encoder::encode_frames`] returns zero, one or
1578 /// several packets and [`Av1Encoder::flush`] drains whatever is still
1579 /// held at the end of the stream. [`Av1Encoder::encode`]'s one-in-one-out
1580 /// contract cannot hold here and it returns an error instead; a caller
1581 /// that wants the old shape simply does not call this constructor.
1582 ///
1583 /// # Errors
1584 /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be
1585 /// left between the anchor and the hidden frame) or above `config.gop`
1586 /// (the group would straddle a key frame).
1587 pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> {
1588 if pyramid.mini_gop < 2 {
1589 return Err(Error::unsupported(
1590 "AV1 encode",
1591 "a pyramid mini-GOP is at least 2 pictures",
1592 ));
1593 }
1594 let mut encoder = Self::new(config)?;
1595 encoder.pyramid = Some(pyramid);
1596 Ok(encoder)
1597 }
1598
1599 /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it,
1600 /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of
1601 /// `config.base_q_idx` being used as-is.
1602 ///
1603 /// # Errors
1604 /// Same as [`Av1Encoder::new`].
1605 pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> {
1606 let rate_loop = rate.into_loop(&mut config, None);
1607 let mut encoder = Self::new(config)?;
1608 encoder.rate_loop = rate_loop;
1609 Ok(encoder)
1610 }
1611
1612 /// [`Av1Encoder::with_pyramid`] and [`Av1Encoder::with_rate_target`] at
1613 /// once: the rate loop then keeps a separate quantizer per pyramid level,
1614 /// predicting each frame's size from the previous frame of its OWN level
1615 /// (a leaf and a hidden `ALTREF` differ by several times in size, so one
1616 /// shared predictor would swing the quantizer every frame).
1617 ///
1618 /// # Errors
1619 /// As both.
1620 pub fn with_pyramid_and_rate_target(
1621 mut config: EncoderConfig,
1622 pyramid: Pyramid,
1623 rate: RateTarget,
1624 ) -> Result<Self> {
1625 let rate_loop = rate.into_loop(&mut config, Some(pyramid));
1626 let mut encoder = Self::with_pyramid(config, pyramid)?;
1627 encoder.rate_loop = rate_loop;
1628 Ok(encoder)
1629 }
1630
1631 /// The [`Pyramid`] this stream is actually coding under: what
1632 /// [`Av1Encoder::with_pyramid`] asked for, or `None` once the content gate
1633 /// in [`Av1Encoder::encode_frames`] has dropped a screen-content stream
1634 /// back to the flat path. Meaningful after the first picture has been
1635 /// handed in.
1636 #[must_use]
1637 pub fn pyramid(&self) -> Option<Pyramid> {
1638 self.pyramid
1639 }
1640
1641 /// The coded (padded-to-64) frame size every picture in this stream is
1642 /// coded at — what a decoder allocates and what `ffprobe` reports.
1643 #[must_use]
1644 pub fn coded_size(&self) -> (usize, usize) {
1645 (
1646 self.config.width.next_multiple_of(SUPERBLOCK),
1647 self.config.height.next_multiple_of(SUPERBLOCK),
1648 )
1649 }
1650
1651 /// The display (render) size every frame header signals — [`EncoderConfig`]'s
1652 /// own `width`/`height`, always, whatever the coded size pads it to.
1653 #[must_use]
1654 pub fn display_size(&self) -> (usize, usize) {
1655 (self.config.width, self.config.height)
1656 }
1657
1658 /// Takes one picture and returns the PREVIOUS picture's packet, key or
1659 /// inter by this stream's `gop` cadence — the facade's one frame of
1660 /// latency (the picture just handed in is what the previous one is coded
1661 /// against as its lookahead). The FIRST call has no previous picture and
1662 /// returns a packet with an EMPTY `data` (its other fields are
1663 /// placeholders; test `data.is_empty()`), and the last picture's packet
1664 /// comes out of [`Av1Encoder::flush`] — so a caller that concatenates
1665 /// `data` in call order still gets the whole stream, provided it flushes
1666 /// at the end.
1667 ///
1668 /// # Errors
1669 /// Returns an error when `picture`'s size does not match
1670 /// [`EncoderConfig::width`]/[`EncoderConfig::height`], when the encoder
1671 /// was built by [`Av1Encoder::with_pyramid`] (which reorders pictures, so
1672 /// one call cannot return one packet), or under the same conditions
1673 /// [`crate::encode::encode_key_frame`]/[`crate::encode::encode_sequence`]
1674 /// do.
1675 pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {
1676 if self.pyramid.is_some() {
1677 return Err(Error::unsupported(
1678 "AV1 encode",
1679 "a pyramid stream reorders pictures -- use encode_frames()/flush()",
1680 ));
1681 }
1682 let mut packets = self.encode_frames(picture)?;
1683 Ok(packets.pop().unwrap_or(Packet {
1684 data: Vec::new(),
1685 key: false,
1686 order: 0,
1687 dts: 0,
1688 level: Level::Leaf,
1689 }))
1690 }
1691
1692 /// Takes one picture and returns every packet it completed, in coding
1693 /// order. Without a [`Pyramid`] that is one packet — the PREVIOUS
1694 /// picture's, since this one is its lookahead — and none at all on the
1695 /// first call; with one it is
1696 /// empty for most pictures and a whole mini-GOP's worth (the hidden
1697 /// frame, its leaves and the `show_existing_frame` that re-outputs it)
1698 /// for the picture that closes a group.
1699 ///
1700 /// # Errors
1701 /// As [`Av1Encoder::encode`], minus the pyramid refusal.
1702 pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {
1703 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
1704 // lane-split: the split census prints on every exit of this call when
1705 // armed, so no `return` path loses it; the counters are cumulative, so
1706 // the last table a run prints is that run's total.
1707 struct SplitCensusDump;
1708 impl Drop for SplitCensusDump {
1709 fn drop(&mut self) {
1710 if crate::encode::split_census_on() {
1711 crate::encode::dump_split_census();
1712 }
1713 if crate::encode::newmv_census_on() {
1714 crate::encode::dump_newmv_census();
1715 }
1716 }
1717 }
1718 // `then_some` would CONSTRUCT the guard eagerly and drop it when the
1719 // flag is off, which runs `Drop` -- and printed the census header on
1720 // every unarmed encode. `then` builds it only when armed.
1721 let _census = (crate::encode::split_census_on() || crate::encode::newmv_census_on())
1722 .then(|| SplitCensusDump);
1723 if (picture.width, picture.height) != (self.config.width, self.config.height) {
1724 return Err(Error::unsupported(
1725 "AV1 encode",
1726 format!(
1727 "picture is {}x{}, encoder is {}x{}",
1728 picture.width, picture.height, self.config.width, self.config.height
1729 ),
1730 ));
1731 }
1732 // THE CONTENT GATE (lane-av1pyrgate): the pyramid is for camera
1733 // material. A desktop capture is the one content class every pyramid
1734 // sweep measured WORSE under it, and it is exactly the class the
1735 // screen detector separates (`encode::screen_content`: 0/48 frames on
1736 // both real films, 48/48 on the OBS capture), so a stream whose first
1737 // picture reads as screen content drops back to the flat path and
1738 // codes byte for byte what it coded before the pyramid existed.
1739 //
1740 // Decided ONCE, on the first picture, not per mini-GOP: the flat path
1741 // keeps its references in `reference`/`golden`/`prev2` and the pyramid
1742 // path in `dpb`, so a switch after the first frame would read slots
1743 // the other path never filled. Per-GOP re-decision needs the two
1744 // reference sets kept in step first; the gate's own recipe codes one
1745 // GOP per stream, where the two are the same decision.
1746 if self.pyramid.is_some()
1747 && self.next_index == 0
1748 && crate::encode::picture_is_screen(picture)
1749 {
1750 self.pyramid = None;
1751 }
1752 let Some(pyramid) = self.pyramid else {
1753 // The delay queue: the pictures behind this one are the
1754 // lookahead window the one at its head is coded with, which is
1755 // what makes the facade's bytes identical to
1756 // `encode_sequence`'s (lane-av1facade, lane-av1tpl2).
1757 self.held.push_back(picture.clone());
1758 if self.held.len() <= crate::encode::tpl_depth() - 1 {
1759 return Ok(Vec::new());
1760 }
1761 let previous = self.held.pop_front().expect("queue is over depth");
1762 let window: Vec<Picture> = self.held.iter().cloned().collect();
1763 return Ok(vec![self.encode_flat(&previous, &window)?]);
1764 };
1765 let order = self.next_index;
1766 self.next_index += 1;
1767 if order.is_multiple_of(self.config.gop as u64) {
1768 // A key frame closes whatever group is open (there is nothing for
1769 // its leaves to point forward at across the boundary) and then
1770 // restarts the pyramid from the key itself.
1771 let mut packets = self.drain_all(Some(picture))?;
1772 packets.push(self.encode_key(order, picture)?);
1773 return Ok(packets);
1774 }
1775 self.pending.push((order, picture.clone()));
1776 // The group closes on the size the LAYOUT gives it (which depends on
1777 // how many pictures are left before the next key frame, so no short
1778 // tail group is left behind), or early when the next picture would be
1779 // a key frame.
1780 let run_start = self.pending[0].0;
1781 let remaining = self.config.gop - (run_start % self.config.gop as u64) as usize;
1782 let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64);
1783 if self.pending.len() >= group_target(remaining, pyramid.mini_gop, absorb_tail())
1784 || next_is_key
1785 {
1786 return self.drain_pending();
1787 }
1788 Ok(Vec::new())
1789 }
1790
1791 /// Codes and returns every picture still held back — the last picture of
1792 /// a flat stream (which has no lookahead and is coded without one), or
1793 /// the tail of a pyramid stream whose last mini-GOP never filled up.
1794 /// Empty once there is nothing held.
1795 ///
1796 /// # Errors
1797 /// As [`Av1Encoder::encode_frames`].
1798 pub fn flush(&mut self) -> Result<Vec<Packet>> {
1799 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
1800 if !self.held.is_empty() {
1801 let mut packets = Vec::with_capacity(self.held.len());
1802 while let Some(previous) = self.held.pop_front() {
1803 let window: Vec<Picture> = self.held.iter().cloned().collect();
1804 packets.push(self.encode_flat(&previous, &window)?);
1805 }
1806 return Ok(packets);
1807 }
1808 self.drain_all(None)
1809 }
1810
1811 /// The flat path: one picture and its lookahead (the next source picture,
1812 /// `None` at the end of the stream) in, one packet out — the same inputs
1813 /// [`crate::encode::encode_sequence`] gives each of its inter frames, so
1814 /// the bytes are identical.
1815 fn encode_flat(&mut self, picture: &Picture, lookahead: &[Picture]) -> Result<Packet> {
1816 let render = (self.config.width, self.config.height);
1817 let padded = picture.padded_to(SUPERBLOCK);
1818 let is_key = self.next_index.is_multiple_of(self.config.gop as u64);
1819 let order = self.next_index;
1820 let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| {
1821 r.q_idx(if is_key { Level::Key } else { Level::Leaf })
1822 });
1823
1824 let encoded: Encoded = if is_key {
1825 encode_key_frame_inner(
1826 &padded,
1827 base_q_idx,
1828 DEADZONE,
1829 &KEY_FRAME_MODES,
1830 split_blocks(),
1831 render,
1832 self.color_config,
1833 &self.fctx,
1834 )?
1835 } else {
1836 let reference = self.reference.as_ref().ok_or_else(|| {
1837 Error::unsupported(
1838 "AV1 encode",
1839 "an inter frame needs a previous reconstruction",
1840 )
1841 })?;
1842 encode_inter_frame(
1843 &padded,
1844 reference,
1845 base_q_idx,
1846 DEADZONE,
1847 order as u32,
1848 // The flat path's own slot plan, in order hints: the key frame
1849 // of the GOP this picture sits in is what `GOLDEN_FRAME`
1850 // names, and every reference but `ALTREF_FRAME` is the frame
1851 // just coded.
1852 crate::encode::flat_order_hints(
1853 order as u32 & 0x7f,
1854 (order - order % self.config.gop as u64) as u32 & 0x7f,
1855 self.prev2.is_some(),
1856 ),
1857 render,
1858 self.carried_cdfs.as_ref().map(|c| &c.0),
1859 self.golden.as_ref(),
1860 self.prev2.as_ref(),
1861 None,
1862 &self.fctx,
1863 None,
1864 &lookahead
1865 .iter()
1866 .map(|n| n.padded_to(SUPERBLOCK))
1867 .collect::<Vec<_>>(),
1868 )?
1869 };
1870
1871 self.carried_cdfs = Some(encoded.next_cdfs.clone());
1872 if is_key {
1873 self.golden = Some(encoded.reconstruction.clone());
1874 self.prev2 = None;
1875 } else {
1876 self.prev2 = self.reference.take();
1877 }
1878 self.reference = Some(encoded.reconstruction.clone());
1879 self.next_index += 1;
1880 let cropped = crop_encoded(&encoded, render.0, render.1);
1881 let level = if is_key { Level::Key } else { Level::Leaf };
1882 if let Some(rate_loop) = self.rate_loop.as_mut() {
1883 // The flat path codes every frame at the slot's own q, no offset.
1884 rate_loop.update(level, 0, i16::from(base_q_idx), cropped.stream.len());
1885 }
1886 Ok(self.packet(cropped.stream, is_key, order, level))
1887 }
1888
1889 /// THE SHARED MINI-GOP DRIVER: codes a whole sequence — one key frame
1890 /// then all inter, which is [`crate::encode::encode_sequence`]'s only
1891 /// shape — through this very facade, under `pyramid`, and hands back what
1892 /// that path returns. The two are byte-identical BY CONSTRUCTION rather
1893 /// than by a mirrored second implementation: there is one reordering,
1894 /// one DPB/slot policy and one set of per-level quantizer offsets, here
1895 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
1896 /// still pins it, now over a pyramid sequence too).
1897 ///
1898 /// The content gate lives in [`Av1Encoder::encode_frames`] and applies
1899 /// unchanged, so a screen-content clip handed in here codes flat.
1900 ///
1901 /// `EncodedSequence::frames` comes back in DISPLAY order, one entry per
1902 /// source picture — the order the flat path's coding order happens to be,
1903 /// and the order every reader of it (the BD gate's sample-exactness
1904 /// assertions against a decoder's output) needs. `stream` stays in coding
1905 /// order, which is the order a decoder reads.
1906 ///
1907 /// # Errors
1908 /// As [`Av1Encoder::encode_frames`].
1909 pub(crate) fn encode_sequence_pyramid(
1910 pictures: &[Picture],
1911 base_q_idx: u8,
1912 pyramid: Pyramid,
1913 tiles: (u32, u32),
1914 ) -> Result<crate::encode::EncodedSequence> {
1915 let first = pictures.first().ok_or_else(|| {
1916 Error::unsupported("AV1 encode", "a sequence needs at least one picture")
1917 })?;
1918 let config = EncoderConfig {
1919 width: first.width,
1920 height: first.height,
1921 base_q_idx,
1922 // One key frame, at picture 0, and inter for the rest.
1923 gop: pictures.len().max(1),
1924 // `encode_sequence` writes an unspecified colour config.
1925 colour: Colour::Unspecified,
1926 tile_cols_log2: tiles.0,
1927 tile_rows_log2: tiles.1,
1928 };
1929 let mut encoder = Self::with_pyramid(config, pyramid)?;
1930 encoder.collected = Some(Vec::with_capacity(pictures.len()));
1931 let mut stream = Vec::new();
1932 for picture in pictures {
1933 for packet in encoder.encode_frames(picture)? {
1934 stream.extend_from_slice(&packet.data);
1935 }
1936 }
1937 for packet in encoder.flush()? {
1938 stream.extend_from_slice(&packet.data);
1939 }
1940 let mut collected = encoder.collected.take().expect("collecting");
1941 // Every source picture is coded exactly once, so a frame's display
1942 // order IS its index once the list is sorted by it.
1943 let coding_order: Vec<usize> = collected.iter().map(|(order, _)| *order as usize).collect();
1944 collected.sort_by_key(|(order, _)| *order);
1945 let frames: Vec<Encoded> = collected.into_iter().map(|(_, encoded)| encoded).collect();
1946 assert!(
1947 coding_order.iter().all(|&i| i < frames.len()),
1948 "a coded frame's display position is outside the sequence"
1949 );
1950 Ok(crate::encode::EncodedSequence {
1951 stream,
1952 frames,
1953 coding_order,
1954 })
1955 }
1956
1957 /// Stamps a packet with its display and coding positions and advances the
1958 /// coding-order clock.
1959 fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet {
1960 let dts = self.next_dts;
1961 self.next_dts += 1;
1962 Packet {
1963 data,
1964 key,
1965 order,
1966 dts,
1967 level,
1968 }
1969 }
1970
1971 /// Stores a coded frame into every DPB slot its `refresh_frame_flags`
1972 /// names (spec 7.20).
1973 fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) {
1974 let slot = DpbSlot {
1975 picture: encoded.reconstruction.clone(),
1976 order_hint,
1977 // `next_cdfs` is already a `Box<CdfSnapshot>` (lane-av1stacksweep),
1978 // so this is a pointer copy rather than a second boxing -- the
1979 // same fix lane-av1enchang made here, now that the producer hands
1980 // over a box instead of an inline 15232-byte `Cdfs`.
1981 cdfs: encoded.next_cdfs.clone(),
1982 };
1983 for &s in slots {
1984 self.dpb[s as usize] = Some(slot.clone());
1985 }
1986 }
1987
1988 /// Codes a key frame in pyramid mode: it refreshes all eight slots, so it
1989 /// becomes the anchor, the `GOLDEN_FRAME` and the CDF source for the
1990 /// whole GOP at once.
1991 fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> {
1992 let render = (self.config.width, self.config.height);
1993 let base = self
1994 .rate_loop
1995 .as_ref()
1996 .map_or(i16::from(self.config.base_q_idx), |r| {
1997 i16::from(r.q_idx(Level::Key))
1998 });
1999 let offset = self.pyramid.map_or(0, |p| p.key_q_offset);
2000 let base_q_idx = (base + offset).clamp(1, 255) as u8;
2001 let encoded = encode_key_frame_inner(
2002 &picture.padded_to(SUPERBLOCK),
2003 base_q_idx,
2004 DEADZONE,
2005 &KEY_FRAME_MODES,
2006 split_blocks(),
2007 render,
2008 self.color_config,
2009 &self.fctx,
2010 )?;
2011 self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0);
2012 self.anchor = 0;
2013 // Every leaf slot now holds the key frame, which `GOLDEN_FRAME`
2014 // already names: the chain starts empty again.
2015 self.leaf_hist.clear();
2016 let cropped = crop_encoded(&encoded, render.0, render.1);
2017 if let Some(rate_loop) = self.rate_loop.as_mut() {
2018 rate_loop.update(Level::Key, 0, base + offset, cropped.stream.len());
2019 }
2020 if let Some(collected) = self.collected.as_mut() {
2021 collected.push((order, cropped.clone()));
2022 }
2023 Ok(self.packet(cropped.stream, true, order, Level::Key))
2024 }
2025
2026 /// Codes one inter frame at `order` from the DPB, in coding order.
2027 #[allow(clippy::too_many_arguments)]
2028 fn encode_pyramid_inter(
2029 &mut self,
2030 order: u64,
2031 picture: &Picture,
2032 last_slot: u8,
2033 self_slot: u8,
2034 altref_slot: u8,
2035 // lane-last2: the slot read as `LAST2_FRAME`. `None` -- and any slot
2036 // holding no picture, or the same one `LAST_FRAME` reads -- leaves
2037 // the reference set exactly as it was before this lane.
2038 last2_slot: Option<u8>,
2039 show_frame: bool,
2040 level: Level,
2041 // The quantizer offset comes from the CALLER, not from `level`: a
2042 // three-level group codes two `Level::Arf` frames (the group's top
2043 // ARF and the mid one) at different offsets, and they share the
2044 // rate-control slot but not the offset.
2045 offset: i16,
2046 // The lookahead window this frame's temporal lambda map is built
2047 // from, already padded (lane-arfcen). Empty codes the frame at one
2048 // lambda, which is what the whole pyramid path used to do.
2049 lookahead: &[Picture],
2050 // lane-lookahead: DISPLAY-FUTURE pictures for the SOURCE temporal
2051 // filter only (the top ARF's, out of the buffered next group), never
2052 // for the temporal lambda map -- keeping the filter's window and the
2053 // tpl window separate levers. Empty everywhere else.
2054 future: &[Picture],
2055 ) -> Result<Packet> {
2056 let render = (self.config.width, self.config.height);
2057 let order_hint = (order & 0x7f) as u32;
2058 let base = self
2059 .rate_loop
2060 .as_ref()
2061 .map_or(i16::from(self.config.base_q_idx), |r| {
2062 i16::from(r.q_idx(level))
2063 });
2064 let base_q_idx = (base + offset).clamp(1, 255) as u8;
2065 // lane-arfq: the top ARF of a mini-GOP is the hidden frame coded at
2066 // the pyramid's OWN `arf_q_offset` (the mid and quarter levels are
2067 // `Level::Arf` too but sit at their own offsets), and it is the level
2068 // the whole group predicts from -- so it reads its own `delta_q`
2069 // strength (`crate::speed::DQ_LEVEL_K`).
2070 let dq_level = match (show_frame, self.pyramid.map(|p| p.arf_q_offset)) {
2071 (true, _) => crate::encode::DqLevel::Leaf,
2072 (false, Some(arf)) if arf == offset => crate::encode::DqLevel::TopArf,
2073 (false, _) => crate::encode::DqLevel::MidArf,
2074 };
2075 // spec 5.9.2's `ref_frame_sign_bias`, derived from what the slots
2076 // this frame names actually hold: a reference whose order hint is
2077 // AHEAD of this frame's is backward-biased, and the MV stack scans
2078 // (writer and decoder alike) flip borrowed candidates across the
2079 // boundary. Only `ALTREF_FRAME` can be ahead here — the leaves of a
2080 // mini-GOP name the group's hidden frame there.
2081 let mut sign_bias = crate::mvstack::NO_SIGN_BIAS;
2082 let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| {
2083 dpb[slot as usize]
2084 .as_ref()
2085 .is_some_and(|s| s.order_hint > order_hint)
2086 };
2087 // A LAST2 slot only counts when it holds a picture that is not the
2088 // one `LAST_FRAME` already names; otherwise the frame codes the
2089 // reference set it always did.
2090 let last2_slot = last2_slot.filter(|&s| s != last_slot && self.dpb[s as usize].is_some());
2091 let slots = [
2092 last_slot,
2093 last2_slot.unwrap_or(last_slot),
2094 last_slot,
2095 GOLDEN_SLOT,
2096 last_slot,
2097 last_slot,
2098 altref_slot,
2099 ];
2100 for (i, slot) in slots.into_iter().enumerate() {
2101 sign_bias[i] = ahead(slot, &self.dpb);
2102 }
2103 // The same seven slots' order hints, for `skipModeAllowed` (spec
2104 // 5.9.22) in the frame-header writer.
2105 let order_hints: [u32; 7] = slots.map(|slot| {
2106 self.dpb[slot as usize]
2107 .as_ref()
2108 .map_or(0, |s| (s.order_hint & 0x7f) as u32)
2109 });
2110 let reference = self.dpb[last_slot as usize]
2111 .as_ref()
2112 .map(|s| s.picture.clone())
2113 .ok_or_else(|| {
2114 Error::unsupported(
2115 "AV1 encode",
2116 "an inter frame needs a previous reconstruction",
2117 )
2118 })?;
2119 let last2 =
2120 last2_slot.and_then(|s| self.dpb[s as usize].as_ref().map(|d| d.picture.clone()));
2121 let golden = self.dpb[GOLDEN_SLOT as usize]
2122 .as_ref()
2123 .map(|s| s.picture.clone());
2124 let altref = (altref_slot != GOLDEN_SLOT)
2125 .then(|| {
2126 self.dpb[altref_slot as usize]
2127 .as_ref()
2128 .map(|s| s.picture.clone())
2129 })
2130 .flatten();
2131 let start_cdfs = self.dpb[last_slot as usize]
2132 .as_ref()
2133 .map(|s| s.cdfs.0.clone());
2134 // lane-arfpred: the top ARF is coded from a TEMPORALLY FILTERED
2135 // source when `speed::ARF_TF` is non-zero -- the grain it would
2136 // otherwise spend its residual on is averaged out against the
2137 // group's own display neighbours (`lookahead`, already padded).
2138 let source = picture.padded_to(SUPERBLOCK);
2139 // ... and never at the very top of the quality range, where the
2140 // anchor's own quantizer has hit the rate loop's floor
2141 // ([`crate::speed::ARF_TF_QMIN`]).
2142 let tf = match dq_level {
2143 crate::encode::DqLevel::TopArf => arf_tf_strength(),
2144 // lane-arftf: the mid ARF gets its own strength -- its window is
2145 // the group's later leaves, i.e. the filter runs FORWARD there.
2146 crate::encode::DqLevel::MidArf => arf_tf_mid_strength(),
2147 crate::encode::DqLevel::Leaf => 0.0,
2148 };
2149 let tf = match base_q_idx >= crate::speed::ARF_TF_QMIN {
2150 true => tf,
2151 false => 0.0,
2152 };
2153 let source = match tf > 0.0 {
2154 true => {
2155 // lane-lookahead: the filter's window is sized HERE -- up to
2156 // `ARF_TF_WIN` display-past neighbours (nearest first) and
2157 // then the display-future ones the caller buffered.
2158 let window: Vec<Picture> = lookahead
2159 .iter()
2160 .take(arf_tf_window())
2161 .chain(future.iter())
2162 .cloned()
2163 .collect();
2164 crate::encode::arf_temporal_filter(&source, &window, tf)
2165 }
2166 false => source,
2167 };
2168 let encoded = || -> Result<Encoded> {
2169 encode_inter_frame(
2170 &source,
2171 &reference,
2172 base_q_idx,
2173 DEADZONE,
2174 order_hint,
2175 order_hints,
2176 render,
2177 start_cdfs.as_ref(),
2178 golden.as_ref(),
2179 altref.as_ref(),
2180 last2.as_ref(),
2181 &self.fctx,
2182 Some(crate::encode::PyramidFrame {
2183 last_slot,
2184 self_slot,
2185 altref_slot,
2186 last2_slot,
2187 show_frame,
2188 sign_bias,
2189 dq_level,
2190 }),
2191 // lane-arfcen: the group's own sources ARE this frame's window
2192 // (`tpl_window`); it was `&[]` here, which switched the temporal
2193 // lambda map off on every frame the default stream codes.
2194 lookahead,
2195 )
2196 }();
2197 // Name the pyramid position in any failure: an error out of the tile
2198 // writer or the filter search is otherwise indistinguishable between
2199 // the hidden frame and the leaves that read it.
2200 let encoded = encoded.map_err(|e| {
2201 Error::unsupported(
2202 "AV1 encode",
2203 format!(
2204 "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \
2205 altref {altref_slot}, last2 {last2_slot:?}, shown {show_frame}, golden {}, \
2206 altref pic {}): {e}",
2207 golden.is_some(),
2208 altref.is_some(),
2209 ),
2210 )
2211 })?;
2212 self.refresh(&[self_slot], &encoded, order_hint);
2213 let cropped = crop_encoded(&encoded, render.0, render.1);
2214 if let Some(rate_loop) = self.rate_loop.as_mut() {
2215 rate_loop.update(level, offset, base + offset, cropped.stream.len());
2216 }
2217 if let Some(collected) = self.collected.as_mut() {
2218 collected.push((order, cropped.clone()));
2219 }
2220 Ok(self.packet(cropped.stream, false, order, level))
2221 }
2222
2223 /// Closes the open mini-GOP. With the lookahead off that codes it
2224 /// straight away, which is byte for byte what this encoder did before
2225 /// lane-lookahead; with it on the open group takes the `ready` slot and
2226 /// the group ALREADY there is coded, with the open one's sources as its
2227 /// display-future window.
2228 fn drain_pending(&mut self) -> Result<Vec<Packet>> {
2229 if !lookahead() {
2230 let group = std::mem::take(&mut self.pending);
2231 return self.code_group(group, &[]);
2232 }
2233 let group = std::mem::take(&mut self.ready);
2234 let next = std::mem::take(&mut self.pending);
2235 let packets = self.code_group(group, &next);
2236 self.ready = next;
2237 packets
2238 }
2239
2240 /// Codes every group still buffered, in coding order -- what a key frame
2241 /// (`next` is the key picture, the last buffered group's own
2242 /// display-future) and the end of stream (`None`) both need. The tail
2243 /// group can be any length, down to the single picture `code_group`
2244 /// codes as one shown leaf.
2245 fn drain_all(&mut self, next: Option<&Picture>) -> Result<Vec<Packet>> {
2246 let tail: Vec<(u64, Picture)> = next
2247 .filter(|_| lookahead())
2248 .map(|p| vec![(self.next_index, p.clone())])
2249 .unwrap_or_default();
2250 let ready = std::mem::take(&mut self.ready);
2251 let pending = std::mem::take(&mut self.pending);
2252 let mut packets = self.code_group(ready, &pending)?;
2253 packets.extend(self.code_group(pending, &tail)?);
2254 Ok(packets)
2255 }
2256
2257 /// Codes one mini-GOP: its hidden frame first, then its leaves, then
2258 /// the `show_existing_frame` header that puts the hidden frame back in
2259 /// display order. `future` is the display-future sources the caller has
2260 /// buffered past this group (lane-lookahead), empty without a lookahead.
2261 fn code_group(
2262 &mut self,
2263 group: Vec<(u64, Picture)>,
2264 future: &[(u64, Picture)],
2265 ) -> Result<Vec<Packet>> {
2266 if group.is_empty() {
2267 return Ok(Vec::new());
2268 }
2269 let mut packets = Vec::with_capacity(group.len() + 1);
2270 // The lookahead window of the group's picture at index `pos`: the
2271 // display-order successors inside this group, or -- for the group's
2272 // top ARF, the last picture, whose successors are not buffered yet --
2273 // the leaves BEHIND it in reverse display order, which are exactly
2274 // the pictures that predict backward from it. Padded like the frame
2275 // itself, as `encode_inter_frame` wants it.
2276 let tpl_window = |pos: usize, back: bool| -> Vec<Picture> {
2277 let depth = crate::encode::tpl_depth();
2278 if !tpl_pyramid() || depth < 2 {
2279 return Vec::new();
2280 }
2281 let window: Vec<&Picture> = match back {
2282 false => group[pos + 1..].iter().map(|(_, p)| p).collect(),
2283 true => group[..pos].iter().rev().map(|(_, p)| p).collect(),
2284 };
2285 window
2286 .into_iter()
2287 .take(depth - 1)
2288 .map(|p| p.padded_to(SUPERBLOCK))
2289 .collect()
2290 };
2291 // lane-last2: the slot a frame reading `last_slot` as `LAST_FRAME`
2292 // names as `LAST2_FRAME` -- the most recent shown leaf that is not
2293 // the one it already reads. `None` with the lever off, or before two
2294 // distinct past pictures exist.
2295 let last2_of = |hist: &[u8], last_slot: u8| -> Option<u8> {
2296 last2()
2297 .then(|| hist.iter().copied().find(|&s| s != last_slot))
2298 .flatten()
2299 };
2300 let anchor_slot = ANCHOR_SLOTS[self.anchor];
2301 let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor];
2302 let (arf_order, arf_picture) = group.last().cloned().expect("non-empty");
2303 let pyramid = self.pyramid.expect("pyramid mode");
2304 if group.len() == 1 {
2305 // Nothing to predict backward, so no hidden frame: one shown leaf
2306 // that also becomes the next group's anchor.
2307 packets.push(self.encode_pyramid_inter(
2308 arf_order,
2309 &arf_picture,
2310 anchor_slot,
2311 next_anchor_slot,
2312 GOLDEN_SLOT,
2313 last2_of(&self.leaf_hist, anchor_slot),
2314 true,
2315 Level::Leaf,
2316 pyramid.leaf_q_offset,
2317 &tpl_window(0, false),
2318 &[],
2319 )?);
2320 self.anchor = 1 - self.anchor;
2321 return Ok(packets);
2322 }
2323 // lane-lookahead: the display-future half of the top ARF's temporal
2324 // filter window, padded like the frame itself. Empty when the
2325 // lookahead is off (`future` is then always empty) or when the filter
2326 // asks for no future neighbours, which is what keeps the default
2327 // stream byte-identical.
2328 let arf_future: Vec<Picture> = future
2329 .iter()
2330 .take(arf_tf_window_future())
2331 .map(|(_, p)| p.padded_to(SUPERBLOCK))
2332 .collect();
2333 // lane-tplfut: the top ARF's TEMPORAL LAMBDA window. Mode 0 (and any
2334 // mode with no buffered future picture) keeps the group's own
2335 // display-PAST sources, reversed -- the only window that exists
2336 // without a lookahead, and the one every measurement so far was
2337 // taken with. The other modes read the next group's sources, which
2338 // is the direction libaom's tpl looks at an ARF.
2339 // `n` of the buffered display-future sources, nearest first, padded
2340 // like the frame being coded.
2341 let arf_tpl_future = |n: usize| -> Vec<Picture> {
2342 future
2343 .iter()
2344 .take(n)
2345 .map(|(_, p)| p.padded_to(SUPERBLOCK))
2346 .collect()
2347 };
2348 let arf_tpl: Vec<Picture> = {
2349 let depth = crate::encode::tpl_depth();
2350 let past = || tpl_window(group.len() - 1, true);
2351 match (tpl_fut(), future.is_empty(), tpl_pyramid() && depth >= 2) {
2352 (_, _, false) => Vec::new(),
2353 (0, _, _) | (_, true, _) => past(),
2354 (1, _, _) => arf_tpl_future(depth - 1),
2355 // Half the budget each side (`EC_AV1_TPL_FUT_HALF=<n>`
2356 // moves the split), past first: the chain then has
2357 // ONE discontinuity in the middle (the coarse pass between
2358 // the nearest past and the nearest future neighbour spans the
2359 // whole group), which is the arm's known cost.
2360 (2, _, _) => {
2361 let budget = tpl_fut_win(depth);
2362 let mut w = past();
2363 w.truncate(tpl_fut_half().max(1));
2364 let room = budget.saturating_sub(w.len());
2365 w.extend(arf_tpl_future(room));
2366 w
2367 }
2368 // Mode 3 and anything above: the WHOLE buffered next group.
2369 (_, _, _) => arf_tpl_future(future.len()),
2370 }
2371 };
2372 // The group's top level: the last picture, hidden, off the anchor.
2373 packets.push(self.encode_pyramid_inter(
2374 arf_order,
2375 &arf_picture,
2376 anchor_slot,
2377 next_anchor_slot,
2378 // lane-arfcen: the slot this ARF refreshes still holds the ARF
2379 // from two groups back, so naming it here gives the frame a
2380 // SECOND, distinct past anchor instead of the key it already
2381 // reads as GOLDEN.
2382 match arf_altref() {
2383 true => next_anchor_slot,
2384 false => GOLDEN_SLOT,
2385 },
2386 // The ARF levels take no LAST2: the anchor pair already gives a
2387 // top ARF two distinct past anchors (`arf_altref`), and the mid
2388 // and quarter frames have only the one past anchor in the DPB.
2389 None,
2390 false,
2391 Level::Arf,
2392 pyramid.arf_q_offset,
2393 &arf_tpl,
2394 // lane-lookahead: the group's top ARF is its LAST picture in
2395 // display order, so every picture of the next group is a
2396 // display-future neighbour of it -- nearest first.
2397 &arf_future,
2398 )?);
2399 let leaves = group.len() - 1;
2400 // THE THIRD LEVEL: a second hidden frame at the middle of the leaf
2401 // run, coded off the anchor with the top ARF as its own backward
2402 // reference. It needs a leaf on both sides of it, so a group of
2403 // three or fewer stays two-level.
2404 //
2405 // AND IT NEEDS A RUN LONG ENOUGH TO AMORTISE IT: a GOP that is one
2406 // single mini-GOP (`group_target` absorbs a tail, so a 12-picture GOP
2407 // under `mini_gop` 8 is ONE group of 11) pays for the second hidden
2408 // frame out of eleven pictures and reads +2.8 BD points worse against
2409 // libaom on film B at every mid offset measured (-4: +71.1, -8:
2410 // +71.2, against the two-level +68.4), while the 48-picture GOP -- six
2411 // groups sharing the same machinery -- is 6.0 points BETTER. So the
2412 // third level is switched on by the RUN's length, not by the group's:
2413 // the same GOP-length dependence `group_target` itself was built for.
2414 let long_run = self.config.gop > pyramid.mini_gop + pyramid.mini_gop / 2;
2415 let mid = pyramid
2416 .mid_q_offset
2417 .filter(|_| leaves >= 3 && long_run)
2418 .map(|offset| {
2419 let at = (leaves - 1) / 2;
2420 (at, offset)
2421 });
2422 if let Some((at, offset)) = mid {
2423 let (order, picture) = group[at].clone();
2424 packets.push(self.encode_pyramid_inter(
2425 order,
2426 &picture,
2427 anchor_slot,
2428 MID_SLOT,
2429 next_anchor_slot,
2430 None,
2431 false,
2432 Level::Arf,
2433 offset,
2434 &tpl_window(at, false),
2435 &[],
2436 )?);
2437 }
2438 // THE FOURTH LEVEL: one hidden frame at the middle of each half of
2439 // the leaf run, so no leaf is more than one picture from a hidden
2440 // reference on either side -- the depth the references run (rav1e
2441 // speed 6 codes 23 hidden frames per 48 pictures, libaom four levels
2442 // per 16-picture group) and the lever three levels had run out of.
2443 // It hangs off the mid level, and it needs a leaf on both sides of
2444 // both quarter points, which a run of fewer than seven leaves cannot
2445 // give.
2446 let quarters = match (mid, pyramid.quarter_q_offset) {
2447 (Some((at, _)), Some(offset)) if leaves >= 7 => {
2448 Some(([(at - 1) / 2, (at + leaves) / 2], offset))
2449 }
2450 _ => None,
2451 };
2452 if let Some((at, offset)) = quarters {
2453 // The first quarter predicts forward off the group's anchor and
2454 // backward off the mid ARF; the second starts FROM the mid ARF
2455 // and reads the group's top ARF backward.
2456 for (i, &pos) in at.iter().enumerate() {
2457 let (order, picture) = group[pos].clone();
2458 let (last_slot, altref_slot) = match i {
2459 0 => (anchor_slot, MID_SLOT),
2460 _ => (MID_SLOT, next_anchor_slot),
2461 };
2462 packets.push(self.encode_pyramid_inter(
2463 order,
2464 &picture,
2465 last_slot,
2466 QUARTER_SLOTS[i],
2467 altref_slot,
2468 None,
2469 false,
2470 Level::Arf,
2471 offset,
2472 &tpl_window(pos, false),
2473 &[],
2474 )?);
2475 }
2476 }
2477 // Every hidden frame INSIDE the leaf run, by leaf index, in display
2478 // order: what a leaf reads forward (the nearest one behind it) and
2479 // backward (the nearest one ahead of it, the group's top ARF when
2480 // there is none).
2481 let mut inner: Vec<(usize, u8)> = Vec::new();
2482 if let Some((at, _)) = mid {
2483 inner.push((at, MID_SLOT));
2484 }
2485 if let Some((at, _)) = quarters {
2486 inner.extend(at.iter().zip(QUARTER_SLOTS).map(|(&at, slot)| (at, slot)));
2487 }
2488 inner.sort_unstable();
2489 let (seq, _) = crate::encode::key_frame_headers(
2490 self.config.width,
2491 self.config.height,
2492 self.config.base_q_idx,
2493 )?;
2494 let show_existing = |encoder: &mut Self, slot: u8, order: u64| -> Result<Packet> {
2495 let mut data = crate::obu::temporal_delimiter();
2496 data.extend_from_slice(&crate::frame::show_existing_frame_obu(&seq, slot)?);
2497 Ok(encoder.packet(data, false, order, Level::ShowExisting))
2498 };
2499 // The leaves, in display order, so every `show_existing_frame` lands
2500 // in its own display position. Each leaf names the nearest hidden
2501 // frame BEHIND it as `LAST_FRAME` (the group's anchor for the first
2502 // leaf, otherwise the previous leaf) and the nearest one AHEAD as
2503 // `ALTREF_FRAME` (the group's top ARF when none is closer).
2504 for (i, (order, picture)) in group[..leaves].iter().enumerate() {
2505 if let Some(&(_, slot)) = inner.iter().find(|(at, _)| *at == i) {
2506 let packet = show_existing(self, slot, *order)?;
2507 packets.push(packet);
2508 continue;
2509 }
2510 // The previous shown leaf's own slot: `LEAF_SLOT` with the
2511 // lever off, and with it on whichever of [`LEAF_SLOTS`] that leaf
2512 // refreshed.
2513 let prev_leaf = self.leaf_hist.first().copied().unwrap_or(LEAF_SLOT);
2514 let last_slot = match i {
2515 0 => anchor_slot,
2516 i => inner
2517 .iter()
2518 .find(|(at, _)| at + 1 == i)
2519 .map_or(prev_leaf, |&(_, slot)| slot),
2520 };
2521 // Alternate the refresh: this leaf takes the leaf slot the
2522 // PREVIOUS leaf did not, which is the one the leaf before that
2523 // wrote and which this frame may still read as `LAST2_FRAME`
2524 // (read before write).
2525 let self_slot = match last2() {
2526 true => LEAF_SLOTS
2527 .into_iter()
2528 .find(|&s| Some(s) != self.leaf_hist.first().copied())
2529 .unwrap_or(LEAF_SLOT),
2530 false => LEAF_SLOT,
2531 };
2532 let last2_slot = last2_of(&self.leaf_hist, last_slot);
2533 let altref_slot = inner
2534 .iter()
2535 .find(|(at, _)| *at > i)
2536 .map_or(next_anchor_slot, |&(_, slot)| slot);
2537 self.leaf_hist.insert(0, self_slot);
2538 self.leaf_hist.truncate(2);
2539 packets.push(self.encode_pyramid_inter(
2540 *order,
2541 picture,
2542 last_slot,
2543 self_slot,
2544 altref_slot,
2545 last2_slot,
2546 true,
2547 Level::Leaf,
2548 pyramid.leaf_q_offset,
2549 &tpl_window(i, false),
2550 &[],
2551 )?);
2552 }
2553 let packet = show_existing(self, next_anchor_slot, arf_order)?;
2554 packets.push(packet);
2555 self.anchor = 1 - self.anchor;
2556 Ok(packets)
2557 }
2558}
2559
2560#[cfg(test)]
2561mod tests {
2562 use super::*;
2563 use std::process::{Command, Stdio};
2564
2565 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
2566 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
2567 /// aomenc gate decodes its stream through ffmpeg and is meaningless
2568 /// without it -- turns it into a hard failure. Without this the require
2569 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
2570 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
2571 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
2572 fn have_ffmpeg() -> bool {
2573 let present = Command::new("ffmpeg")
2574 .arg("-version")
2575 .stdout(Stdio::null())
2576 .stderr(Stdio::null())
2577 .status()
2578 .is_ok_and(|s| s.success());
2579 assert!(
2580 present
2581 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
2582 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
2583 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
2584 );
2585 present
2586 }
2587
2588 fn test_card(width: usize, height: usize, shift: usize) -> Picture {
2589 let mut picture = Picture::grey(width, height);
2590 for y in 0..height {
2591 for x in 0..width {
2592 let sx = (x + shift) % width;
2593 picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16;
2594 }
2595 }
2596 for y in 0..height / 2 {
2597 for x in 0..width / 2 {
2598 let i = y * (width / 2) + x;
2599 picture.u[i] = ((100 + shift * 4) % 256) as u16;
2600 picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16;
2601 }
2602 }
2603 picture
2604 }
2605
2606 /// Drives a whole stream through the facade the way a caller must since
2607 /// it holds one picture of lookahead: every picture through
2608 /// [`Av1Encoder::encode_frames`], then [`Av1Encoder::flush`].
2609 fn encode_all(enc: &mut Av1Encoder, pictures: &[Picture]) -> Vec<Packet> {
2610 let mut packets = Vec::with_capacity(pictures.len());
2611 for (i, picture) in pictures.iter().enumerate() {
2612 packets.extend(
2613 enc.encode_frames(picture)
2614 .unwrap_or_else(|e| panic!("picture {i}: {e}")),
2615 );
2616 }
2617 packets.extend(enc.flush().unwrap_or_else(|e| panic!("flush: {e}")));
2618 packets
2619 }
2620
2621 /// [`gop_shape`] prices the frames the pyramid actually CODES: its hidden
2622 /// counts and leaf count match the packets a real run emits, at three
2623 /// pyramid shapes, and the plan [`RateLoop::new`] builds from it spends
2624 /// the run's budget exactly (`gop` frame targets, no more and no less).
2625 ///
2626 /// Both halves matter: a shape that misses a level (the old model priced
2627 /// ONE hidden frame per group when the mid level had made it two) splits
2628 /// the budget by weights that do not add up to the run.
2629 #[test]
2630 fn the_rate_loop_prices_the_frames_the_pyramid_codes() {
2631 let _knobs = crate::speed::knob_read();
2632 let pictures: Vec<Picture> = (0..48).map(|i| test_card(64, 64, i)).collect();
2633 let quarters = Pyramid {
2634 quarter_q_offset: Some(-20),
2635 ..Pyramid::default()
2636 };
2637 let two_level = Pyramid {
2638 mid_q_offset: None,
2639 ..Pyramid::default()
2640 };
2641 for (gop, pyramid) in [
2642 (48, Pyramid::default()),
2643 (12, Pyramid::default()),
2644 (48, quarters),
2645 (48, two_level),
2646 ] {
2647 let config = EncoderConfig {
2648 width: 64,
2649 height: 64,
2650 base_q_idx: 100,
2651 gop,
2652 colour: Colour::Bt709Limited,
2653 tile_cols_log2: 0,
2654 tile_rows_log2: 0,
2655 };
2656 let rate = RateTarget::BytesPerFrame(2_000);
2657 let mut enc = Av1Encoder::with_pyramid_and_rate_target(config, pyramid, rate).unwrap();
2658 let packets = encode_all(&mut enc, &pictures[..gop]);
2659 let coded = |level: Level| packets.iter().filter(|p| p.level == level).count();
2660 let (hidden, leaves) = gop_shape(pyramid, gop);
2661 let hidden_frames: usize = hidden.iter().map(|&(_, n)| n).sum();
2662 assert_eq!(
2663 (hidden_frames, leaves, 1),
2664 (coded(Level::Arf), coded(Level::Leaf), coded(Level::Key)),
2665 "gop {gop} {pyramid:?}: shape {hidden:?} + {leaves} leaves"
2666 );
2667 assert_eq!(
2668 hidden_frames + leaves + 1,
2669 gop,
2670 "gop {gop}: every picture is coded exactly once"
2671 );
2672 // The plan adds up: one leaf's target times the run's whole
2673 // weight is the run's whole budget.
2674 let target_bytes = 2_000.0;
2675 let loop_ = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
2676 let planned = loop_.target[0]
2677 + loop_.target[2]
2678 * (leaves as f64
2679 + hidden
2680 .iter()
2681 .map(|&(o, n)| n as f64 * loop_.weight(o))
2682 .sum::<f64>());
2683 assert!(
2684 (planned - target_bytes * gop as f64).abs() < 1.0,
2685 "gop {gop}: plan {planned:.0} bytes against a {:.0} byte run",
2686 target_bytes * gop as f64
2687 );
2688 }
2689 }
2690
2691 /// A level at its quantizer BOUND hands its unspent bytes to the levels
2692 /// that can still move ([[vorbis-rate-loop-windup]]'s class in the
2693 /// small), and it does so AT ONCE, not once the bound level's frames are
2694 /// all coded: the loop is driven by a synthetic per-level model where the
2695 /// first hidden frame is coded at `raw_q` 0 (past the coder's own 1..=255
2696 /// clamp) and spends half its plan, and the leaves' target must jump to
2697 /// the run's remainder with EVERY remaining hidden frame priced at that
2698 /// measured rate. The old division -- whole remainder over whole
2699 /// remaining weight -- handed most of the shortfall straight back to the
2700 /// hidden slot (which carries most of the pyramid's weight and cannot
2701 /// spend it), so the leaves only saw the surplus at the end of the run,
2702 /// when there was nothing left to code with it.
2703 #[test]
2704 fn a_bound_level_hands_its_unspent_bytes_to_the_others() {
2705 let pyramid = Pyramid::default();
2706 let (gop, target_bytes) = (48usize, 2_000.0);
2707 let (hidden, leaves) = gop_shape(pyramid, gop);
2708 let run_bytes = target_bytes * gop as f64;
2709 let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
2710 let scale0 = rl.target[2];
2711 let hidden_weight: f64 = hidden.iter().map(|&(o, n)| n as f64 * rl.weight(o)).sum();
2712 // The key codes exactly its plan; the first hidden frame is at the
2713 // floor and spends half of its.
2714 let key_bytes = rl.target[0].round();
2715 rl.update(Level::Key, 0, 100, key_bytes as usize);
2716 let (offset, n0) = hidden[0];
2717 let arf_bytes = (0.5 * scale0 * rl.weight(offset)).round();
2718 rl.update(Level::Arf, offset, 0, arf_bytes as usize);
2719 // Every frame of THAT LEVEL still to come is priced at what the bound
2720 // one measured -- and only that level: its slot-mates (the mid ARF)
2721 // sit at their own offset and are still free to follow the plan.
2722 // Everything else shares the rest.
2723 let want = (run_bytes - key_bytes - arf_bytes * n0 as f64)
2724 / (leaves as f64 + hidden_weight - n0 as f64 * rl.weight(offset));
2725 assert!(
2726 want < scale0 * RateLoop::REPLAN_CLAMP,
2727 "this arm must not reach the windup bound: {want:.1} vs {:.1}",
2728 scale0 * RateLoop::REPLAN_CLAMP
2729 );
2730 assert!(
2731 (rl.target[2] - want).abs() < 1e-6,
2732 "leaf target {:.3} is not the exact remainder {want:.3} (naive division would \
2733 give {:.3})",
2734 rl.target[2],
2735 (run_bytes - key_bytes - arf_bytes)
2736 / (leaves as f64 + hidden_weight - rl.weight(offset))
2737 );
2738 // And the re-plan stays BOUNDED: hidden levels that spend nothing at
2739 // all cannot run the leaves' target away.
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, 1);
2745 }
2746 }
2747 assert!(
2748 rl.target[2] <= scale0 * RateLoop::REPLAN_CLAMP + 1e-9,
2749 "the re-plan is unbounded: leaf target {:.1} past {:.1}",
2750 rl.target[2],
2751 scale0 * RateLoop::REPLAN_CLAMP
2752 );
2753 // ... and BOTH ways: a re-plan that reached zero would stop the loop
2754 // dead (`update` returns on a non-positive target).
2755 let mut rl = RateLoop::new(target_bytes, 100.0, Some(pyramid), gop);
2756 rl.update(Level::Key, 0, 100, key_bytes as usize);
2757 for &(offset, n) in &hidden {
2758 for _ in 0..n {
2759 rl.update(Level::Arf, offset, 0, 40 * key_bytes as usize);
2760 }
2761 }
2762 assert!(
2763 rl.target[2] >= scale0 * RateLoop::REPLAN_FLOOR - 1e-9,
2764 "the re-plan froze the loop: leaf target {:.1} under {:.1}",
2765 rl.target[2],
2766 scale0 * RateLoop::REPLAN_FLOOR
2767 );
2768 }
2769
2770 /// The mini-GOP layout leaves no short tail group, and leaves the long
2771 /// GOP the fixed rule already coded alone: 47 inter pictures are
2772 /// 8 x 5 + 7 under both rules (so a 48-picture GOP is byte-identical),
2773 /// while a 12-picture GOP stops being 8 + 3 (lane-gopad).
2774 #[test]
2775 fn the_mini_gop_layout_leaves_no_short_tail() {
2776 let groups = |remaining: usize, mini_gop: usize, absorb: bool| {
2777 let (mut left, mut out) = (remaining, Vec::new());
2778 while left > 0 {
2779 let g = group_target(left, mini_gop, absorb).min(left);
2780 assert!(g > 0);
2781 out.push(g);
2782 left -= g;
2783 }
2784 out
2785 };
2786 // gop 48: what mini_gop 8 already coded, under either rule.
2787 assert_eq!(groups(47, 8, true), vec![8, 8, 8, 8, 8, 7]);
2788 assert_eq!(groups(47, 8, false), vec![8, 8, 8, 8, 8, 7]);
2789 // gop 12: 8 + 3 becomes one group of 11.
2790 assert_eq!(groups(11, 8, false), vec![8, 3]);
2791 assert_eq!(groups(11, 8, true), vec![11]);
2792 // A run shorter than a group is one group, as before (the 4-picture
2793 // pin clip).
2794 assert_eq!(groups(3, 8, true), vec![3]);
2795 // No group is ever below half the shape, and none is over 1.5x it.
2796 for mini_gop in 2..=16 {
2797 for remaining in 1..=64 {
2798 for g in groups(remaining, mini_gop, true) {
2799 assert!(g * 2 <= 3 * mini_gop, "{remaining}/{mini_gop}: long {g}");
2800 assert!(
2801 g * 2 >= mini_gop || remaining < mini_gop,
2802 "{remaining}/{mini_gop}: short tail {g}"
2803 );
2804 }
2805 }
2806 }
2807 }
2808
2809 /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
2810 /// in order.
2811 fn concat(packets: &[Packet]) -> Vec<u8> {
2812 packets.iter().flat_map(|p| p.data.clone()).collect()
2813 }
2814
2815 /// The facade's latency contract (lane-av1facade, deepened on
2816 /// lane-av1tpl2): the first [`crate::encode::tpl_depth`] - 1 calls hold
2817 /// their picture back and return an empty packet, every later call
2818 /// returns the packet of the picture that many frames earlier, and
2819 /// [`Av1Encoder::flush`] yields the whole queue — so a caller still gets
2820 /// exactly one non-empty packet per picture, `depth - 1` calls later.
2821 #[test]
2822 fn one_in_one_out_delayed_by_the_lookahead_depth() {
2823 let _knobs = crate::speed::knob_read();
2824 let config = EncoderConfig {
2825 width: 64,
2826 height: 64,
2827 base_q_idx: 100,
2828 gop: 2,
2829 colour: Colour::Bt709Limited,
2830 tile_cols_log2: 0,
2831 tile_rows_log2: 0,
2832 };
2833 let delay = crate::encode::tpl_depth() as u64 - 1;
2834 let pictures = delay + 5;
2835 let mut enc = Av1Encoder::new(config).unwrap();
2836 for t in 0..pictures {
2837 let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
2838 if t < delay {
2839 assert!(packet.data.is_empty(), "call {t} holds its picture back");
2840 continue;
2841 }
2842 assert!(!packet.data.is_empty(), "picture {t}: empty packet");
2843 assert_eq!(packet.order, t - delay, "picture {t}: order");
2844 }
2845 let tail = enc.flush().unwrap();
2846 assert_eq!(tail.len() as u64, delay, "flush yields the whole queue");
2847 for (i, p) in tail.iter().enumerate() {
2848 assert_eq!(
2849 p.order,
2850 pictures - delay + i as u64,
2851 "flushed packet {i}: order"
2852 );
2853 assert!(!p.data.is_empty(), "flushed packet {i}: empty");
2854 }
2855 assert!(enc.flush().unwrap().is_empty(), "nothing is held twice");
2856 }
2857
2858 /// A screen-like card: hard-edged 4-pixel bands of two flat luma values
2859 /// with a moving block over the lower half — few colours per 16x16 block
2860 /// at high variance, which is exactly what
2861 /// [`crate::encode::picture_is_screen`] separates. Used unforced, so the
2862 /// gate below runs the real detector rather than an override.
2863 fn screen_card(width: usize, height: usize, shift: usize) -> Picture {
2864 let mut picture = Picture::grey(width, height);
2865 for y in 0..height {
2866 for x in 0..width {
2867 let band = if (x / 4).is_multiple_of(2) { 40 } else { 200 };
2868 let over = y >= height / 2 && (x + shift) % width < width / 3;
2869 picture.y[y * width + x] = if over { 128 } else { band };
2870 }
2871 }
2872 picture
2873 }
2874
2875 /// THE ENTRY-SURFACE GATE (lane-av1facade, extended to the pyramid on
2876 /// lane-av1pyrdef): the streaming facade — what the editor's export
2877 /// drives — codes byte for byte what [`crate::encode::encode_sequence`]
2878 /// codes, which is the path the BD gate measures. Both now drive ONE
2879 /// mini-GOP driver ([`Av1Encoder::encode_sequence_pyramid`]), so the
2880 /// identity is by construction; this pins it anyway, over both content
2881 /// classes the content gate splits:
2882 ///
2883 /// * film-like (the gate's own clip when the fixture is there, a
2884 /// multi-tone moving card otherwise): the pyramid is EFFECTIVE, the
2885 /// stream is reordered (a hidden `ALTREF` per mini-GOP), and the two
2886 /// paths' whole streams are identical;
2887 /// * screen-like: the content gate drops BOTH paths back to flat, one
2888 /// packet per picture, identical frame by frame as well as whole.
2889 ///
2890 /// Never skipped, since a skipped identity gate is the defect it is meant
2891 /// to catch.
2892 #[test]
2893 fn the_facade_codes_the_same_bytes_as_encode_sequence() {
2894 let _knobs = crate::speed::knob_read();
2895 let frames = 12usize;
2896 let film = h264_clip_frames("the facade identity film arm", 640, 384, frames)
2897 .unwrap_or_else(|| {
2898 // The probe inside already printed the ONE line naming the
2899 // resolved path and the escape hatch, so this is a note about
2900 // what runs instead — not a second SKIP.
2901 eprintln!(" ...so the film arm runs on a synthetic card, not real film");
2902 (0..frames).map(|t| test_card(64, 64, t)).collect()
2903 });
2904 let screen: Vec<Picture> = (0..frames).map(|t| screen_card(64, 64, t)).collect();
2905 let pyramid = Pyramid::from_env().expect("the pyramid is this build's default");
2906 for (content, pictures, is_screen) in [("film", &film, false), ("screen", &screen, true)] {
2907 let (width, height) = (pictures[0].width, pictures[0].height);
2908 for q in [150u8, 60] {
2909 let config = EncoderConfig {
2910 width,
2911 height,
2912 base_q_idx: q,
2913 // One key frame then all inter, which is
2914 // `encode_sequence`'s only shape, and the gate's recipe.
2915 gop: frames,
2916 // `encode_sequence` writes an unspecified colour config.
2917 colour: Colour::Unspecified,
2918 tile_cols_log2: 0,
2919 tile_rows_log2: 0,
2920 };
2921 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
2922 let mut packets = Vec::new();
2923 for picture in pictures {
2924 packets.extend(enc.encode_frames(picture).unwrap());
2925 }
2926 packets.extend(enc.flush().unwrap());
2927 assert_eq!(
2928 enc.pyramid().is_none(),
2929 is_screen,
2930 "{content} q={q}: the content gate read this clip the other way round"
2931 );
2932 let sequence = crate::encode::encode_sequence(pictures, q, DEADZONE).unwrap();
2933 assert_eq!(
2934 (
2935 packets.iter().map(|p| p.data.len()).sum::<usize>(),
2936 concat(&packets)
2937 ),
2938 (sequence.stream.len(), sequence.stream.clone()),
2939 "{content} q={q}: the facade's stream is not the sequence path's"
2940 );
2941 assert_eq!(
2942 sequence.frames.len(),
2943 frames,
2944 "{content} q={q}: one entry per picture, in display order"
2945 );
2946 if is_screen {
2947 assert_eq!(
2948 packets.len(),
2949 frames,
2950 "{content} q={q}: one packet per picture"
2951 );
2952 for (i, (packet, coded)) in packets.iter().zip(&sequence.frames).enumerate() {
2953 let cropped = crate::encode::crop_encoded(coded, width, height);
2954 assert_eq!(
2955 (packet.data.len(), packet.data.clone()),
2956 (cropped.stream.len(), cropped.stream.clone()),
2957 "{content} q={q} frame {i}: the facade's bytes are not the \
2958 sequence path's"
2959 );
2960 }
2961 } else {
2962 assert!(
2963 packets.iter().any(|p| p.level == Level::Arf),
2964 "{content} q={q}: a non-screen stream coded no hidden frame"
2965 );
2966 }
2967 }
2968 }
2969 }
2970
2971 /// THE CONTENT GATE (lane-av1pyrgate): the coding pyramid is asked for by
2972 /// the caller but applied only to camera material. Over screen content
2973 /// the encoder must drop back to the flat path and code byte for byte
2974 /// what a flat encoder codes — that is what keeps the BD gate's screen
2975 /// row identical to the flat baseline — and over non-screen content the
2976 /// same request must still reorder (class `gate-blind-to-feature`: a gate
2977 /// that only checked the screen half would pass with the pyramid deleted).
2978 #[test]
2979 fn the_content_gate_keeps_screen_streams_flat() {
2980 let _knobs = crate::speed::knob_read();
2981 let frames = 8usize;
2982 let pictures: Vec<Picture> = (0..frames).map(|t| test_card(64, 64, t)).collect();
2983 let config = EncoderConfig {
2984 width: 64,
2985 height: 64,
2986 base_q_idx: 120,
2987 gop: frames,
2988 colour: Colour::Unspecified,
2989 tile_cols_log2: 0,
2990 tile_rows_log2: 0,
2991 };
2992 crate::encode::force_screen(Some(true));
2993 let mut flat = Av1Encoder::new(config).unwrap();
2994 let flat_packets = encode_all(&mut flat, &pictures);
2995 let mut gated = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
2996 let gated_packets = encode_all(&mut gated, &pictures);
2997 assert_eq!(
2998 gated.pyramid(),
2999 None,
3000 "the gate left a screen stream on the pyramid"
3001 );
3002 assert_eq!(
3003 concat(&gated_packets),
3004 concat(&flat_packets),
3005 "a screen stream's bytes are not the flat path's"
3006 );
3007 crate::encode::force_screen(Some(false));
3008 let mut kept = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
3009 let kept_packets = encode_all(&mut kept, &pictures);
3010 assert_eq!(
3011 kept.pyramid(),
3012 Some(Pyramid::default()),
3013 "the gate ate a film stream"
3014 );
3015 assert!(
3016 kept_packets.iter().any(|p| p.level == Level::Arf),
3017 "a non-screen stream coded no hidden frame"
3018 );
3019 crate::encode::force_screen(None);
3020 }
3021
3022 /// A key frame every `gop` pictures, inter otherwise — checked against
3023 /// what the facade itself reports, and (below) against what `ffprobe`
3024 /// reads back out of the coded bytes.
3025 #[test]
3026 fn gop_cadence_is_honored() {
3027 let _knobs = crate::speed::knob_read();
3028 let config = EncoderConfig {
3029 width: 64,
3030 height: 64,
3031 base_q_idx: 100,
3032 gop: 3,
3033 colour: Colour::Unspecified,
3034 tile_cols_log2: 0,
3035 tile_rows_log2: 0,
3036 };
3037 let mut enc = Av1Encoder::new(config).unwrap();
3038 let pictures: Vec<Picture> = (0..7).map(|t| test_card(64, 64, t)).collect();
3039 let keys: Vec<bool> = encode_all(&mut enc, &pictures)
3040 .iter()
3041 .map(|p| p.key)
3042 .collect();
3043 assert_eq!(keys, vec![true, false, false, true, false, false, true]);
3044 }
3045
3046 fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {
3047 let path = std::env::temp_dir().join(format!(
3048 "ec-av1-facade-probe-{}-{}.obu",
3049 std::process::id(),
3050 std::ptr::addr_of!(stream) as usize
3051 ));
3052 std::fs::write(&path, stream).expect("writing the probe stream");
3053 let out = Command::new("ffprobe")
3054 .args([
3055 "-v",
3056 "error",
3057 "-f",
3058 "obu",
3059 "-select_streams",
3060 "v:0",
3061 "-show_entries",
3062 "frame=key_frame,width,height",
3063 "-of",
3064 "csv=p=0",
3065 ])
3066 .arg(&path)
3067 .output()
3068 .expect("ffprobe failed to run");
3069 let _ = std::fs::remove_file(&path);
3070 assert!(
3071 out.status.success(),
3072 "ffprobe refused the stream: {}",
3073 String::from_utf8_lossy(&out.stderr)
3074 );
3075 String::from_utf8_lossy(&out.stdout)
3076 .lines()
3077 .map(|line| {
3078 let mut f = line.trim().split(',');
3079 let key: u32 = f.next().unwrap().parse().unwrap();
3080 let width: u32 = f.next().unwrap().parse().unwrap();
3081 let height: u32 = f.next().unwrap().parse().unwrap();
3082 (key == 1, width, height)
3083 })
3084 .collect()
3085 }
3086
3087 fn ffprobe_colour(stream: &[u8]) -> String {
3088 let path = std::env::temp_dir().join(format!(
3089 "ec-av1-facade-colour-probe-{}-{}.obu",
3090 std::process::id(),
3091 std::ptr::addr_of!(stream) as usize
3092 ));
3093 std::fs::write(&path, stream).expect("writing the probe stream");
3094 let out = Command::new("ffprobe")
3095 .args([
3096 "-v",
3097 "error",
3098 "-f",
3099 "obu",
3100 "-select_streams",
3101 "v:0",
3102 "-show_entries",
3103 "stream=color_primaries,color_transfer,color_space,color_range",
3104 "-of",
3105 "csv=p=0",
3106 ])
3107 .arg(&path)
3108 .output()
3109 .expect("ffprobe failed to run");
3110 let _ = std::fs::remove_file(&path);
3111 assert!(
3112 out.status.success(),
3113 "ffprobe refused the stream: {}",
3114 String::from_utf8_lossy(&out.stderr)
3115 );
3116 String::from_utf8_lossy(&out.stdout).trim().to_string()
3117 }
3118
3119 /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)
3120 /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that
3121 /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and
3122 /// coded size confirm what the facade already reported.
3123 #[test]
3124 fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
3125 let _knobs = crate::speed::knob_read();
3126 if !have_ffmpeg() {
3127 eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg");
3128 return;
3129 }
3130 let (width, height) = (96usize, 96usize);
3131 let config = EncoderConfig {
3132 width,
3133 height,
3134 base_q_idx: 120,
3135 gop: 15,
3136 colour: Colour::Bt709Limited,
3137 tile_cols_log2: 0,
3138 tile_rows_log2: 0,
3139 };
3140 let mut enc = Av1Encoder::new(config).unwrap();
3141 assert_eq!(enc.display_size(), (width, height));
3142 let (coded_w, coded_h) = enc.coded_size();
3143 assert_eq!(
3144 (coded_w, coded_h),
3145 (
3146 width.next_multiple_of(SUPERBLOCK),
3147 height.next_multiple_of(SUPERBLOCK)
3148 )
3149 );
3150
3151 let pictures: Vec<Picture> = (0..30).map(|t| test_card(width, height, t)).collect();
3152 let packets: Vec<Packet> = encode_all(&mut enc, &pictures);
3153 let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect();
3154 assert_eq!(
3155 packets.iter().map(|p| p.key).collect::<Vec<_>>(),
3156 expect_key,
3157 "facade's own key/inter flags"
3158 );
3159
3160 let stream = concat(&packets);
3161 let frames = ffprobe_frames(&stream);
3162 assert_eq!(frames.len(), 30, "ffprobe frame count");
3163 for (t, (key, w, h)) in frames.iter().enumerate() {
3164 assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag");
3165 assert_eq!(
3166 (*w, *h),
3167 (width as u32, height as u32),
3168 "picture {t}: ffprobe reports the true (display) size, not the padded coded one"
3169 );
3170 }
3171 }
3172
3173 /// The configured colour properties are what `ffprobe` reports back,
3174 /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it
3175 /// is the default a player assumes and the one this test would silently
3176 /// pass without wiring for (`ffprobe` reports "unknown" for the
3177 /// hardcoded "unspecified" this crate wrote before the facade existed,
3178 /// which is a visibly different string).
3179 #[test]
3180 fn bt709_limited_colour_is_reported_by_ffprobe() {
3181 let _knobs = crate::speed::knob_read();
3182 if !have_ffmpeg() {
3183 eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg");
3184 return;
3185 }
3186 let config = EncoderConfig {
3187 width: 64,
3188 height: 64,
3189 base_q_idx: 100,
3190 gop: 4,
3191 colour: Colour::Bt709Limited,
3192 tile_cols_log2: 0,
3193 tile_rows_log2: 0,
3194 };
3195 let mut enc = Av1Encoder::new(config).unwrap();
3196 let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]);
3197 let colour = ffprobe_colour(&packets[0].data);
3198 assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields");
3199 }
3200
3201 /// The same, for BT.601: a different set of CICP integers must produce a
3202 /// different string, or the wiring could be a no-op that happens to read
3203 /// as BT.709 for every input.
3204 #[test]
3205 fn bt601_limited_colour_is_reported_by_ffprobe() {
3206 let _knobs = crate::speed::knob_read();
3207 if !have_ffmpeg() {
3208 eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg");
3209 return;
3210 }
3211 let config = EncoderConfig {
3212 width: 64,
3213 height: 64,
3214 base_q_idx: 100,
3215 gop: 4,
3216 colour: Colour::Bt601Limited,
3217 tile_cols_log2: 0,
3218 tile_rows_log2: 0,
3219 };
3220 let mut enc = Av1Encoder::new(config).unwrap();
3221 let packets = encode_all(&mut enc, &[test_card(64, 64, 0)]);
3222 let colour = ffprobe_colour(&packets[0].data);
3223 assert_eq!(
3224 colour, "tv,smpte170m,smpte170m,smpte170m",
3225 "ffprobe colour fields"
3226 );
3227 }
3228
3229 /// A frame whose size does not match the encoder's configured geometry
3230 /// is refused by name.
3231 #[test]
3232 fn geometry_mismatch_is_refused() {
3233 let _knobs = crate::speed::knob_read();
3234 let config = EncoderConfig {
3235 width: 64,
3236 height: 64,
3237 base_q_idx: 100,
3238 gop: 4,
3239 colour: Colour::Bt709Limited,
3240 tile_cols_log2: 0,
3241 tile_rows_log2: 0,
3242 };
3243 let mut enc = Av1Encoder::new(config).unwrap();
3244 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
3245 assert!(err.to_string().contains("64x64"), "{err}");
3246 }
3247
3248 /// `gop == 0` is refused at construction, not the first `encode()` call.
3249 #[test]
3250 fn zero_gop_is_refused() {
3251 let _knobs = crate::speed::knob_read();
3252 let config = EncoderConfig {
3253 width: 64,
3254 height: 64,
3255 base_q_idx: 100,
3256 gop: 0,
3257 colour: Colour::Bt709Limited,
3258 tile_cols_log2: 0,
3259 tile_rows_log2: 0,
3260 };
3261 let err = Av1Encoder::new(config).unwrap_err();
3262 assert!(err.to_string().contains("gop"), "{err}");
3263 }
3264
3265 /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget`
3266 /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down
3267 /// to this facade's own input size, and re-coded through the facade so the
3268 /// rate-target surface is exercised at the entry point a caller actually
3269 /// drives.
3270 ///
3271 /// lane-av1clipprobe: the ABSENCE of this clip used to be a bare
3272 /// `clip.exists()` -> `None`, and every caller turned that into a `SKIP`
3273 /// line and a return -- so a tree with no root `fixtures/` printed
3274 /// `SKIP the 1080p tile round trip: no fixture` and libtest reported `ok`:
3275 /// green with nothing asserted, and no env that made it RED. The presence
3276 /// check now lives in the crate's one library-fixture probe
3277 /// (`library_fixture::require_at`), which fails under `EC_REQUIRE_FIXTURES` /
3278 /// `EC_AV1_REQUIRE_FFMPEG` / `EC_AV1_REQUIRE_AOMENC` and otherwise prints
3279 /// that ONE line.
3280 fn h264_clip_frames(
3281 what: &str,
3282 width: usize,
3283 height: usize,
3284 frames: usize,
3285 ) -> Option<Vec<Picture>> {
3286 if !have_ffmpeg() {
3287 eprintln!("SKIP {what}: no ffmpeg");
3288 return None;
3289 }
3290 // lane-av1speed3: the wall tables below are read on REAL film as
3291 // well as on the colour-bar fixture (`bars` vs `film` in the BD
3292 // gate's own vocabulary), and the film crop lives outside the repo --
3293 // `EC_AV1_WALL_CLIP` names it. Unset everywhere else, so every other
3294 // caller still gets the fixture.
3295 //
3296 // lane-av1clipprobe: the default path resolves through `EC_FIXTURES`
3297 // first, which is the root `scripts/verify-fixture-library.sh`
3298 // validates -- so the preflight's verdict and these bytes are the same
3299 // tree, and GREEN-with-an-absent-root is no longer reachable by
3300 // pointing EC_FIXTURES somewhere the gates do not read.
3301 let clip = match std::env::var("EC_AV1_WALL_CLIP") {
3302 Ok(p) => std::path::PathBuf::from(p),
3303 Err(_) => crate::library_fixture::path("video/h264-1080p-23.976-8bit.mp4"),
3304 };
3305 // `what` is the CALLING GATE's name, carried in so that both exits from
3306 // this function print exactly one line naming it: the ffmpeg line
3307 // above, and the probe's line naming the resolved path. Callers
3308 // therefore `return` on `None` WITHOUT printing a second one -- the
3309 // second "no fixture" line per gate was the noise that hid this defect.
3310 let Some(clip) = crate::library_fixture::require_at(clip, what) else {
3311 return None;
3312 };
3313 let out = Command::new("ffmpeg")
3314 .args(["-v", "error", "-i", clip.to_str().unwrap()])
3315 .args(["-frames:v", &frames.to_string()])
3316 .args(["-vf", &format!("scale={width}:{height}")])
3317 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
3318 .output()
3319 .expect("ffmpeg failed to run");
3320 assert!(
3321 out.status.success(),
3322 "{}",
3323 String::from_utf8_lossy(&out.stderr)
3324 );
3325 let (luma, chroma) = (width * height, width * height / 4);
3326 let frame_len = luma + 2 * chroma;
3327 assert_eq!(
3328 out.stdout.len(),
3329 frame_len * frames,
3330 "expected {frames} 4:2:0 frames"
3331 );
3332 Some(
3333 (0..frames)
3334 .map(|i| {
3335 let bytes = &out.stdout[i * frame_len..][..frame_len];
3336 Picture {
3337 width,
3338 height,
3339 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
3340 u: bytes[luma..luma + chroma]
3341 .iter()
3342 .map(|&v| u16::from(v))
3343 .collect(),
3344 v: bytes[luma + chroma..]
3345 .iter()
3346 .map(|&v| u16::from(v))
3347 .collect(),
3348 }
3349 })
3350 .collect(),
3351 )
3352 }
3353
3354 /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total
3355 /// coded size within ±20% of `frames * target` once the first few
3356 /// frames' settling has been discarded (the key frame's own reference
3357 /// state and the controller's first couple of steps).
3358 #[test]
3359 fn bytes_per_frame_target_settles_within_20_percent() {
3360 let _knobs = crate::speed::knob_read();
3361 let Some(pictures) = h264_clip_frames(
3362 "bytes_per_frame_target_settles_within_20_percent",
3363 640,
3364 384,
3365 24,
3366 ) else {
3367 return;
3368 };
3369 let target_bytes = 4_000u32;
3370 let config = EncoderConfig {
3371 width: 640,
3372 height: 384,
3373 base_q_idx: 100,
3374 gop: 24,
3375 colour: Colour::Bt709Limited,
3376 tile_cols_log2: 0,
3377 tile_rows_log2: 0,
3378 };
3379 let mut enc =
3380 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
3381 let sizes: Vec<usize> = encode_all(&mut enc, &pictures)
3382 .iter()
3383 .map(|p| p.data.len())
3384 .collect();
3385 // Discard the key frame (always far larger than an inter target) and
3386 // the next 4 inter frames the loop needs to step toward it.
3387 let settled = &sizes[5..];
3388 let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64;
3389 let low = f64::from(target_bytes) * 0.8;
3390 let high = f64::from(target_bytes) * 1.2;
3391 assert!(
3392 mean >= low && mean <= high,
3393 "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}"
3394 );
3395 }
3396
3397 /// One (bitrate, pyramid) arm's tally, built on the worker thread and
3398 /// handed back through the progress channel
3399 /// (`bitrate_target_lands_within_5_percent_over_48_frames`). Per LEVEL,
3400 /// so a miss reads as WHICH level's model is off rather than as one
3401 /// aggregate percentage.
3402 struct ArmResult {
3403 /// [`RateLoop::target`] as the arm's own encoder computed it.
3404 targets: [f64; 3],
3405 coded: usize,
3406 bytes: [usize; 4],
3407 count: [usize; 4],
3408 }
3409
3410 impl ArmResult {
3411 fn take(&mut self, packets: Vec<Packet>) {
3412 for packet in packets {
3413 self.coded += packet.data.len();
3414 let i = match packet.level {
3415 Level::Key => 0,
3416 Level::Arf => 1,
3417 Level::Leaf => 2,
3418 Level::ShowExisting => 3,
3419 };
3420 self.bytes[i] += packet.data.len();
3421 self.count[i] += 1;
3422 }
3423 }
3424 }
3425
3426 /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±5% of the
3427 /// target over 48 frames of a real clip, flat and under a pyramid alike,
3428 /// across a 5x span of bitrates. This is the accuracy claim of the
3429 /// target-bitrate mode: no two-pass, no lookahead, just each frame's size
3430 /// predicted from the previous frame of its own level, one clamped
3431 /// proportional step, and the level model
3432 /// ([`WEIGHT_LEVEL_GAIN`]) that says how the run's budget splits.
3433 ///
3434 /// The tolerance was ±10% and every arm was inside ±3.0% when it was cut
3435 /// to ±5%; the worst arm is the 2 Mbit/s pyramid at -4.4%, which is the
3436 /// ENCODER'S OWN CEILING showing through, not the loop's aim: at that
3437 /// rate the hidden slot already codes at `q_idx` 1 (its 22863 bytes a
3438 /// frame are the same at 1.5 and 2 Mbit/s) and the leaves sit at 1 + 12
3439 /// `leaf_q_offset`, so this clip cannot be made to spend much past
3440 /// 2.4 Mbit/s under the default pyramid however the budget is split.
3441 ///
3442 /// # Bounded
3443 ///
3444 /// Each arm's encode runs on a worker thread under a per-CALL
3445 /// wall-clock ceiling, so this gate FAILS rather than hanging when an
3446 /// encode stops terminating (lane-av1enchang: a 3h20m wedge on one host
3447 /// and 30min on another, both here, both with the test thread spinning
3448 /// and no child process for the crate's child timeout to reap). The cost
3449 /// is real and is why the budget is not tight: the two high bitrate arms
3450 /// walk `q_idx` from the seed 100 down into the 20s to spend an
3451 /// 8000-byte budget on a 640x384 clip, and a frame at `q_idx` 25 costs
3452 /// ~15s in a debug build (~1s optimized) against ~0.5s at `q_idx` 100.
3453 /// lane-av1enchang: the PYRAMID CONSTRUCTORS fit on a tight stack.
3454 ///
3455 /// `Av1Encoder` used to be 139960 bytes BY VALUE, because each of the
3456 /// eight `DpbSlot`s held a 15 KB `CdfSnapshot` inline. The pyramid
3457 /// constructors nest three deep -- `with_pyramid_and_rate_target` ->
3458 /// `with_pyramid` -> `new` -- and each level materialises the struct in
3459 /// an unoptimized build, so ~840 KB of stack was live at the innermost
3460 /// `Ok(Self { .. })`. On libtest's default 2 MiB test thread that aborts:
3461 /// `fatal runtime error: stack overflow, aborting`, reproduced on the
3462 /// pre-fix binary at `crates/ec-av1/src/encoder.rs:1519` via
3463 /// `coredumpctl debug`.
3464 ///
3465 /// Boxing the snapshot brought the struct to 18168 bytes. This gate pins
3466 /// that: it builds BOTH constructors on a thread with a deliberately
3467 /// tight stack, so the old layout ABORTS THE PROCESS and the new one
3468 /// returns. It runs in milliseconds, where proving the same thing through
3469 /// the 48-frame gate takes 6m35s.
3470 ///
3471 /// Both thresholds were swept, in an unoptimized build:
3472 ///
3473 /// | stack | pre-fix (`CdfSnapshot` by value) | post-fix (boxed) |
3474 /// |---|---|---|
3475 /// | 256 KiB | overflow | overflow |
3476 /// | 384 KiB | overflow | ok |
3477 /// | 512 KiB | overflow | ok |
3478 /// | 1 MiB | **overflow** | **ok** |
3479 /// | 2 MiB | **overflow** (libtest's default) | ok |
3480 /// | 3 MiB | ok | ok |
3481 ///
3482 /// 1 MiB is the gate: 2.7x what the boxed layout needs and 2x below what
3483 /// the old one did, so it is nowhere near either threshold and cannot
3484 /// flake. The pre-fix row at 1 MiB is the red -- which is also why
3485 /// `.cargo/config.toml` carries `RUST_MIN_STACK = 67108864`, a
3486 /// workspace-local band-aid this gate makes unnecessary for this struct.
3487 ///
3488 /// `EC_AV1_TIGHT_STACK_BYTES` overrides the size, which is how the sweep
3489 /// above is reproduced.
3490 #[test]
3491 fn the_pyramid_constructors_fit_on_a_tight_stack() {
3492 // 1 MiB: see the threshold table on this test. Red before the Box,
3493 // green after, with 2.7x margin either way.
3494 const STACK: usize = 1024 * 1024;
3495 let stack: usize = std::env::var("EC_AV1_TIGHT_STACK_BYTES")
3496 .ok()
3497 .and_then(|v| v.parse().ok())
3498 .unwrap_or(STACK);
3499 let config = EncoderConfig {
3500 width: 640,
3501 height: 384,
3502 base_q_idx: 100,
3503 gop: 48,
3504 colour: Colour::Bt709Limited,
3505 tile_cols_log2: 0,
3506 tile_rows_log2: 0,
3507 };
3508 let rate = RateTarget::Bitrate {
3509 bits_per_second: 1_536_000,
3510 frames_per_second: 24.0,
3511 };
3512 let handle = std::thread::Builder::new()
3513 .stack_size(stack)
3514 .spawn(move || {
3515 let flat = Av1Encoder::with_rate_target(config, rate)
3516 .expect("with_rate_target")
3517 .rate_loop
3518 .is_some();
3519 let pyr =
3520 Av1Encoder::with_pyramid_and_rate_target(config, Pyramid::default(), rate)
3521 .expect("with_pyramid_and_rate_target")
3522 .pyramid
3523 .is_some();
3524 (flat, pyr)
3525 })
3526 .expect("spawn tight-stack thread");
3527 let (flat, pyr) = handle
3528 .join()
3529 .unwrap_or_else(|_| panic!("the encoder constructors overflowed a {stack}-byte stack"));
3530 assert!(flat, "with_rate_target lost its rate loop");
3531 assert!(pyr, "with_pyramid_and_rate_target lost its pyramid");
3532 eprintln!(
3533 "TIGHTSTACK {stack} bytes: Av1Encoder={} bytes, both constructors returned",
3534 std::mem::size_of::<Av1Encoder>()
3535 );
3536 }
3537
3538 #[test]
3539 fn bitrate_target_lands_within_5_percent_over_48_frames() {
3540 let _knobs = crate::speed::knob_read();
3541 let (width, height, frames) = (640usize, 384usize, 48usize);
3542 let Some(pictures) = h264_clip_frames(
3543 "bitrate_target_lands_within_5_percent_over_48_frames",
3544 width,
3545 height,
3546 frames,
3547 ) else {
3548 return;
3549 };
3550 let fps = 24.0;
3551 let pictures = std::sync::Arc::new(pictures);
3552 for bits_per_second in [384_000u32, 768_000, 1_536_000, 2_000_000] {
3553 let config = EncoderConfig {
3554 width,
3555 height,
3556 base_q_idx: 100,
3557 gop: frames,
3558 colour: Colour::Bt709Limited,
3559 tile_cols_log2: 0,
3560 tile_rows_log2: 0,
3561 };
3562 let rate = RateTarget::Bitrate {
3563 bits_per_second,
3564 frames_per_second: fps,
3565 };
3566 for pyramid in [None, Some(Pyramid::default())] {
3567 let arm = format!("{bits_per_second} bps pyramid {}", pyramid.is_some());
3568 // lane-av1enchang: a BACKSTOP, not a fix. This gate is NOT
3569 // hung and NOT regressed -- it is a ~7 hour test in an
3570 // unoptimized build (measured: the whole `ec-av1` lib suite
3571 // takes 24341s, and this test is the largest single item in
3572 // it), and it PASSES. What it lacked was any way to FAIL: a
3573 // future non-terminating encode would wedge the suite for
3574 // hours with no diagnostic, which is exactly how wave3j and
3575 // wave3h were lost. So the arm runs on a worker thread and
3576 // THIS thread watches a per-CALL deadline, purely so that
3577 // case reports itself.
3578 //
3579 // The budget is PER CALL, not per test, and it is valued from
3580 // a measured run so it cannot turn a correct-but-slow build
3581 // red. Measured on this gate's own workload (48 frames of
3582 // 640x384): one `encode_frames` call is 0.78s..1.04s
3583 // optimized and 8.6s..12.2s debug on the flat arms. A
3584 // PYRAMID call codes a whole mini-GOP at once, so its worst
3585 // single call is `Pyramid::default().mini_gop` frames
3586 // (~9), i.e. ~110s debug. 1800s is therefore ~16x that
3587 // worst honest call: no plausible host trips it, and a real
3588 // non-terminating encode is reported in 30 minutes instead
3589 // of never. `EC_AV1_ENCODE_CALL_BUDGET_SECS` overrides it,
3590 // which is how the backstop is proven to bite.
3591 let budget = std::time::Duration::from_secs(
3592 std::env::var("EC_AV1_ENCODE_CALL_BUDGET_SECS")
3593 .ok()
3594 .and_then(|v| v.parse().ok())
3595 .unwrap_or(1800),
3596 );
3597 let total = pictures.len() + 1;
3598 // Shared, not cloned: the 48 decoded frames are ~35 MB of
3599 // `u16` luma+chroma, and all eight arms want the same ones.
3600 let pictures = std::sync::Arc::clone(&pictures);
3601 // `None` is a progress ticket: THIS call returned. `Some` is
3602 // the arm's result, sent after `flush` -- which is itself a
3603 // call that can spin, so it needs a ticket too, not a bare
3604 // `join` that would block forever.
3605 let (tx, rx) = std::sync::mpsc::channel::<Option<ArmResult>>();
3606 let worker = std::thread::spawn(move || {
3607 let mut enc = match pyramid {
3608 None => Av1Encoder::with_rate_target(config, rate).unwrap(),
3609 Some(p) => {
3610 Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap()
3611 }
3612 };
3613 let targets = enc.rate_loop.as_ref().unwrap().target;
3614 let mut out = ArmResult {
3615 targets,
3616 coded: 0,
3617 bytes: [0; 4],
3618 count: [0; 4],
3619 };
3620 for picture in pictures.iter() {
3621 out.take(enc.encode_frames(picture).unwrap());
3622 if tx.send(None).is_err() {
3623 return;
3624 }
3625 }
3626 out.take(enc.flush().unwrap());
3627 let _ = tx.send(Some(out));
3628 });
3629 let started = std::time::Instant::now();
3630 let mut calls = 0usize;
3631 let out = loop {
3632 match rx.recv_timeout(budget) {
3633 // The result IS the last thing the worker sends, so
3634 // receiving it means every call returned. A worker
3635 // that panicked sends nothing and arrives as
3636 // `Disconnected` below, which re-joins it and
3637 // surfaces the real panic.
3638 Ok(Some(out)) => break out,
3639 Ok(None) => calls += 1,
3640 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => panic!(
3641 "AV1 bitrate gate SLOW, NOT HUNG: the {arm} arm's encode did not \
3642 return within {}s (arm elapsed {:.0}s, stuck on call {} of {total} \
3643 -- the call that never came back). This gate is a ~7 hour test in \
3644 an unoptimized build and it PASSES, so a red here is NOT a slow \
3645 host: the budget is per CALL and the worst honest call measured \
3646 is ~1s optimized / ~110s debug on a pyramid arm, so reaching this \
3647 panic means an encode call that is NOT RETURNING. \
3648 EC_AV1_ENCODE_CALL_BUDGET_SECS raises the budget.",
3649 budget.as_secs(),
3650 started.elapsed().as_secs_f64(),
3651 calls + 1,
3652 ),
3653 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
3654 worker.join().expect("encode worker panicked");
3655 panic!("AV1 encode worker for {arm} died without a result");
3656 }
3657 }
3658 };
3659 let ArmResult {
3660 targets,
3661 coded,
3662 bytes,
3663 count,
3664 } = out;
3665 let seconds = frames as f64 / fps;
3666 let achieved = coded as f64 * 8.0 / seconds;
3667 let error = achieved / f64::from(bits_per_second) - 1.0;
3668 let per = |i: usize| match count[i] {
3669 0 => "-".to_string(),
3670 n => format!("{n}x{}", bytes[i] / n),
3671 };
3672 eprintln!(
3673 "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \
3674 = {achieved:.0} bps ({:+.1}%) | targets {:.0}/{:.0}/{:.0} \
3675 coded key {} arf {} leaf {}",
3676 pyramid.is_some(),
3677 100.0 * error,
3678 targets[0],
3679 targets[1],
3680 targets[2],
3681 per(0),
3682 per(1),
3683 per(2),
3684 );
3685 assert!(
3686 error.abs() <= 0.05,
3687 "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \
3688 (pyramid {})",
3689 100.0 * error,
3690 pyramid.is_some(),
3691 );
3692 }
3693 }
3694 }
3695 /// The `BytesPerFrame` controller's own windup bound: no frame's coded
3696 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
3697 /// clip's full range of content (so a scene cut can't be the one frame
3698 /// that breaks the bound).
3699 ///
3700 /// The SEEDING frame is the one exemption ([`RateLoop::update`]): a slot
3701 /// that has coded nothing yet is still sitting on the caller's
3702 /// `base_q_idx` guess, and its first step is the acquisition jump, not
3703 /// windup. Exactly one frame is exempt -- the loop below asserts the
3704 /// bound on every frame after it, which is where a scene cut would
3705 /// break it.
3706 #[test]
3707 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
3708 let _knobs = crate::speed::knob_read();
3709 let Some(pictures) = h264_clip_frames(
3710 "bytes_per_frame_controller_never_oscillates_past_its_clamp",
3711 640,
3712 384,
3713 24,
3714 ) else {
3715 return;
3716 };
3717 let config = EncoderConfig {
3718 width: 640,
3719 height: 384,
3720 base_q_idx: 100,
3721 gop: 24,
3722 colour: Colour::Bt709Limited,
3723 tile_cols_log2: 0,
3724 tile_rows_log2: 0,
3725 };
3726 let mut enc =
3727 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
3728 let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
3729 // The first frame this encoder EMITS is several `encode_frames` calls
3730 // in (the lookahead queue holds the earlier ones), so the seeding
3731 // step is not frame zero -- it is the first frame `q` moves at all.
3732 let mut seeded = false;
3733 let mut seed_frame = None;
3734 for (frame, picture) in pictures.iter().enumerate() {
3735 enc.encode_frames(picture).unwrap();
3736 let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
3737 let step = (i32::from(q) - i32::from(prev_q)).abs();
3738 if step > 0 && !seeded {
3739 seeded = true;
3740 seed_frame = Some(frame);
3741 } else {
3742 assert!(
3743 f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
3744 "frame {frame}: q stepped from {prev_q} to {q}, past the {} clamp",
3745 RateLoop::STEP_CLAMP
3746 );
3747 }
3748 prev_q = q;
3749 }
3750 assert!(
3751 seed_frame.is_some(),
3752 "the controller never steered at all -- the bound below is vacuous"
3753 );
3754 }
3755
3756 fn psnr(a: &[u16], b: &[u16]) -> f64 {
3757 let squared: f64 = a
3758 .iter()
3759 .zip(b)
3760 .map(|(&x, &y)| {
3761 let d = f64::from(x) - f64::from(y);
3762 d * d
3763 })
3764 .sum();
3765 if squared == 0.0 {
3766 return f64::INFINITY;
3767 }
3768 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
3769 }
3770
3771 /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one
3772 /// entry per coded frame, in order — this facade's own equivalent of
3773 /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
3774 /// PSNR check needs the decoded pixels, not just the coded byte count.
3775 fn ffmpeg_decode_planes(
3776 stream: &[u8],
3777 width: usize,
3778 height: usize,
3779 ) -> Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> {
3780 let path = std::env::temp_dir().join(format!(
3781 "ec-av1-facade-rate-decode-{}-{}.obu",
3782 std::process::id(),
3783 std::ptr::addr_of!(stream) as usize
3784 ));
3785 std::fs::write(&path, stream).expect("writing the decode probe stream");
3786 let out = Command::new("ffmpeg")
3787 .args(["-v", "error", "-f", "obu", "-i"])
3788 .arg(&path)
3789 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
3790 .output()
3791 .expect("ffmpeg failed to run");
3792 let _ = std::fs::remove_file(&path);
3793 assert!(
3794 out.status.success(),
3795 "{}",
3796 String::from_utf8_lossy(&out.stderr)
3797 );
3798 let (luma, chroma) = (width * height, width * height / 4);
3799 let frame_len = luma + 2 * chroma;
3800 out.stdout
3801 .chunks_exact(frame_len)
3802 .map(|f| {
3803 (
3804 f[..luma].to_vec(),
3805 f[luma..luma + chroma].to_vec(),
3806 f[luma + chroma..].to_vec(),
3807 )
3808 })
3809 .collect()
3810 }
3811
3812 /// [`ffmpeg_decode_planes`]' luma half, which is what most rows compare.
3813 fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
3814 ffmpeg_decode_planes(stream, width, height)
3815 .into_iter()
3816 .map(|(y, _, _)| y)
3817 .collect()
3818 }
3819
3820 /// lane-palw: OUR encoder's own witness for the writer half of the
3821 /// palette on-screen defect. `screen_card` at 384x152 is 38 mi rows tall,
3822 /// so the bottom superblock row's palette blocks hang 8 luma rows off the
3823 /// mi grid: spec 5.11.50 codes their colour-index map over the ON-SCREEN
3824 /// corner only and replicates it outward, and the writer used to code the
3825 /// full block grid -- symbols a conformant decoder never reads, so
3826 /// ffmpeg/dav1d desynced the rest of the tile while our own trial decode
3827 /// (unclamped on both sides) agreed with itself. Class
3828 /// `writer-phantom-units-past-edge`.
3829 ///
3830 /// Driven through the ENTRY SURFACE, `Av1Encoder` (what the editor's
3831 /// export calls), and compared on EVERY plane -- a chroma palette map is
3832 /// cut by the same edge. `palette_cut_maps_written` is asserted non-zero
3833 /// so the row cannot pass on a stream that cuts no palette map (class
3834 /// gate-blind-to-feature).
3835 #[test]
3836 fn a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg() {
3837 const NAME: &str = "a_palette_block_cut_by_the_frame_edge_decodes_exactly_through_ffmpeg";
3838 let _knobs = crate::speed::knob_read();
3839 let _gate_lock = crate::stream::tests::lock_gate_counters();
3840 let (width, height) = (384usize, 152usize);
3841 // A 16-px two-tone checkerboard: every 16x16 and 32x32 block holds at
3842 // most two luma values, so the palette arm wins across the WHOLE
3843 // frame -- including the bottom superblock row, whose 16x16 blocks at
3844 // y=144 and 32x32 blocks at y=128 hang past the 152-row mi grid.
3845 // `screen_card`'s 4-px bands fire only 9 palettes here and none of
3846 // them at the cut edge (class gate-blind-to-feature).
3847 let card = |shift: usize| -> Picture {
3848 let mut picture = Picture::grey(width, height);
3849 for y in 0..height {
3850 for x in 0..width {
3851 let cell = ((x + shift) / 8 + y / 8) % 2;
3852 picture.y[y * width + x] = if cell == 0 { 40 } else { 200 };
3853 }
3854 }
3855 picture
3856 };
3857 let sources: Vec<Picture> = (0..2).map(|t| card(t * 16)).collect();
3858 let config = EncoderConfig {
3859 width,
3860 height,
3861 base_q_idx: 60,
3862 gop: 2,
3863 colour: Colour::Bt709Limited,
3864 tile_cols_log2: 0,
3865 tile_rows_log2: 0,
3866 };
3867 let mut enc = Av1Encoder::new(config).unwrap();
3868 crate::tile::reset_palette_cut_maps_written();
3869 let mut stream = Vec::new();
3870 for packet in encode_all(&mut enc, &sources) {
3871 stream.extend_from_slice(&packet.data);
3872 }
3873 eprintln!(
3874 "{NAME}: {} cut colour-index maps written",
3875 crate::tile::palette_cut_maps_written()
3876 );
3877 assert!(
3878 crate::tile::palette_cut_maps_written() > 0,
3879 "{NAME}: no palette block is cut by the frame edge here -- the gate would pass blind"
3880 );
3881 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
3882 assert_eq!(ours.len(), sources.len(), "{NAME}: our decoder's frames");
3883 if !have_ffmpeg() {
3884 eprintln!("SKIP the ffmpeg half of {NAME}: no ffmpeg");
3885 return;
3886 }
3887 let theirs = ffmpeg_decode_planes(&stream, width, height);
3888 assert_eq!(theirs.len(), sources.len(), "{NAME}: ffmpeg's frames");
3889 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
3890 for (plane, got, want) in [("luma", &a.y, &b.0), ("U", &a.u, &b.1), ("V", &a.v, &b.2)] {
3891 let got: Vec<u8> = got.iter().map(|&v| v as u8).collect();
3892 if let Some(at) = got.iter().zip(want).position(|(x, y)| x != y) {
3893 let w = if plane == "luma" { width } else { width / 2 };
3894 panic!(
3895 "{NAME}: frame {i} {plane} differs first at ({}, {}): ours {} vs ffmpeg {}",
3896 at % w,
3897 at / w,
3898 got[at],
3899 want[at],
3900 );
3901 }
3902 assert_eq!(
3903 got.len(),
3904 want.len(),
3905 "{NAME}: frame {i} {plane} is {} samples, ffmpeg's is {}",
3906 got.len(),
3907 want.len()
3908 );
3909 }
3910 }
3911 }
3912
3913 /// A pyramid stream reorders pictures: the hidden `ALTREF` of each
3914 /// mini-GOP is coded before the leaves that precede it in display order,
3915 /// and a `show_existing_frame` header puts it back. This pins the shape
3916 /// (one packet per source picture plus one `show_existing_frame` per
3917 /// group, `dts` monotone, `order` NOT monotone) and then decodes the
3918 /// whole stream through OUR decoder and through ffmpeg/dav1d and requires
3919 /// the two display-order outputs to agree sample for sample — the
3920 /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never
3921 /// output, or output twice, or output in the wrong position, changes the
3922 /// display-order list and fails here.
3923 #[test]
3924 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
3925 // `take_ref_frame_hits` is a process-global counter: a reader-locked
3926 // sibling encoding at the same time zeroes it between our encode and
3927 // our read (seen once: LAST 0 GOLDEN 0 ALTREF 0), so this takes the
3928 // exclusive lock.
3929 let _knobs = crate::speed::knob_write();
3930 pyramid_round_trip(
3931 Pyramid {
3932 mini_gop: 4,
3933 mid_q_offset: None,
3934 ..Pyramid::default()
3935 },
3936 2,
3937 );
3938 }
3939
3940 /// The same round trip over a THREE-level group (`mid_q_offset`): each
3941 /// mini-GOP now codes two hidden frames -- the top ARF at the group's
3942 /// last picture and the mid ARF at the middle of the leaf run -- and
3943 /// re-outputs both with `show_existing_frame`, so a mid frame emitted in
3944 /// the wrong display position, or twice, fails the display-order compare
3945 /// against ffmpeg exactly as a top ARF does.
3946 #[test]
3947 fn a_three_level_pyramid_stream_decodes_in_display_order() {
3948 let _knobs = crate::speed::knob_write();
3949 pyramid_round_trip(
3950 Pyramid {
3951 mini_gop: 8,
3952 mid_q_offset: Some(-8),
3953 ..Pyramid::default()
3954 },
3955 2,
3956 );
3957 }
3958
3959 /// The same round trip over a FOUR-level group
3960 /// ([`Pyramid::quarter_q_offset`]): a mini-GOP of eight now codes four
3961 /// hidden frames -- the top ARF at picture 8, the mid at 4 and the two
3962 /// quarters at 2 and 6 -- each re-output by its own
3963 /// `show_existing_frame`. Every leaf reads a different pair of DPB slots
3964 /// than it did at three levels, so a slot map that lets one level
3965 /// overwrite a picture another is still reading shows up here as a
3966 /// display-order mismatch against ffmpeg.
3967 #[test]
3968 fn a_four_level_pyramid_stream_decodes_in_display_order() {
3969 let _knobs = crate::speed::knob_write();
3970 pyramid_round_trip(
3971 Pyramid {
3972 mini_gop: 8,
3973 mid_q_offset: Some(-8),
3974 quarter_q_offset: Some(4),
3975 ..Pyramid::default()
3976 },
3977 4,
3978 );
3979 }
3980
3981 /// [`Pyramid::key_q_offset`] reaches the key frame: the whole run reads
3982 /// the key, so an offset that never arrived would be invisible in the BD
3983 /// table except as "no change" (class symbol-consumption-gap). A finer
3984 /// key must cost strictly more bytes than the same picture at base q.
3985 #[test]
3986 fn the_key_q_offset_reaches_the_key_frame() {
3987 let _knobs = crate::speed::knob_read();
3988 crate::encode::force_screen(Some(false));
3989 let key_bytes = |offset: i16| {
3990 let config = EncoderConfig {
3991 width: 128,
3992 height: 128,
3993 base_q_idx: 120,
3994 gop: 32,
3995 colour: Colour::Bt709Limited,
3996 tile_cols_log2: 0,
3997 tile_rows_log2: 0,
3998 };
3999 let pyramid = Pyramid {
4000 key_q_offset: offset,
4001 ..Pyramid::default()
4002 };
4003 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
4004 let packets = enc.encode_frames(&test_card(128, 128, 0)).unwrap();
4005 let key = packets
4006 .iter()
4007 .find(|p| p.level == Level::Key)
4008 .expect("key frame");
4009 key.data.len()
4010 };
4011 let (base, finer) = (key_bytes(0), key_bytes(-48));
4012 eprintln!("key at base q {base} bytes, at base q - 48 {finer} bytes");
4013 assert!(
4014 finer > base,
4015 "key_q_offset -48 did not reach the key frame ({finer} <= {base})"
4016 );
4017 }
4018
4019 /// lane-last2's witness: a clip whose pictures ALTERNATE between two
4020 /// textures, so for every leaf the picture two back is an exact match and
4021 /// the one before it (`LAST_FRAME`) is not. With the lever on, the leaf
4022 /// chain alternates its refresh over [`LEAF_SLOTS`] and names the older
4023 /// slot `LAST2_FRAME`; blocks must actually be CODED off it
4024 /// ([[gate-blind-to-feature]]: a slot that is retained but never chosen
4025 /// proves only that the bookkeeping compiles), the stream must decode
4026 /// sample-exact through OUR decoder and through ffmpeg, and the hidden
4027 /// frames must still come out in display order. With the lever OFF the
4028 /// same clip codes ZERO `LAST2` blocks, which is what makes the counter a
4029 /// measurement of this lane and not of the reference set we already had.
4030 #[test]
4031 fn a_leaf_predicts_off_last2_when_the_picture_two_back_matches() {
4032 let _knobs = crate::speed::knob_write();
4033 crate::encode::force_screen(Some(false));
4034 let (width, height) = (128usize, 128usize);
4035 let sources: Vec<Picture> = (0..9)
4036 .map(|t| test_card(width, height, (t % 2) * 24))
4037 .collect();
4038 let run = |on: bool| -> ([usize; 8], Vec<u8>, Vec<Packet>) {
4039 set_last2(Some(on));
4040 let config = EncoderConfig {
4041 width,
4042 height,
4043 base_q_idx: 120,
4044 gop: 32,
4045 colour: Colour::Bt709Limited,
4046 tile_cols_log2: 0,
4047 tile_rows_log2: 0,
4048 };
4049 let pyramid = Pyramid {
4050 mini_gop: 4,
4051 mid_q_offset: None,
4052 ..Pyramid::default()
4053 };
4054 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
4055 let _ = crate::encode::take_ref_frame_hits();
4056 let mut packets = Vec::new();
4057 for picture in &sources {
4058 packets.extend(enc.encode_frames(picture).unwrap());
4059 }
4060 packets.extend(enc.flush().unwrap());
4061 let hits = crate::encode::take_ref_frame_hits();
4062 (hits, concat(&packets), packets)
4063 };
4064 let (off_hits, off_stream, _) = run(false);
4065 let (on_hits, stream, packets) = run(true);
4066 set_last2(None);
4067 eprintln!(
4068 "LAST2 off: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B); \
4069 on: LAST {} LAST2 {} GOLDEN {} ALTREF {} ({} B)",
4070 off_hits[1],
4071 off_hits[2],
4072 off_hits[4],
4073 off_hits[7],
4074 off_stream.len(),
4075 on_hits[1],
4076 on_hits[2],
4077 on_hits[4],
4078 on_hits[7],
4079 stream.len(),
4080 );
4081 assert_eq!(off_hits[2], 0, "LAST2 was coded with the lever OFF");
4082 assert!(
4083 on_hits[2] >= 8,
4084 "the picture two back matches exactly and only {} blocks were coded off LAST2",
4085 on_hits[2],
4086 );
4087
4088 // Display order and sample-exactness, both decoders (the same shape
4089 // `pyramid_round_trip` gates the hidden frames with).
4090 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4091 assert_eq!(
4092 ours.len(),
4093 sources.len(),
4094 "our decoder's display-order count"
4095 );
4096 if !have_ffmpeg() {
4097 eprintln!("SKIP the ffmpeg half of the LAST2 witness: no ffmpeg");
4098 return;
4099 }
4100 let theirs = ffmpeg_decode_luma(&stream, width, height);
4101 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
4102 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4103 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4104 assert_eq!(got.len(), b.len(), "frame {i}: luma size");
4105 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
4106 panic!(
4107 "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4108 at % width,
4109 at / width,
4110 got[at],
4111 b[at],
4112 );
4113 }
4114 }
4115 // The reordering itself is unchanged by the second leaf slot.
4116 let shown = packets
4117 .iter()
4118 .filter(|p| p.level == Level::ShowExisting)
4119 .count();
4120 let arfs = packets.iter().filter(|p| p.level == Level::Arf).count();
4121 assert_eq!(shown, arfs, "one show_existing_frame per hidden frame");
4122 }
4123
4124 /// A picture whose content is a static gradient plus a per-picture
4125 /// pseudo-random +-2 of noise: motion search matches the neighbours
4126 /// almost exactly, so the ARF temporal filter's weights are near 1 and
4127 /// the filter actually changes the source (a moving test card gives every
4128 /// neighbour a large MSE, weight ~0, and the filter is a no-op that would
4129 /// make the future-window witness below pass blind).
4130 fn noisy_card(width: usize, height: usize, t: usize) -> Picture {
4131 let mut picture = Picture::grey(width, height);
4132 let mut seed = (t as u64 + 1).wrapping_mul(0x9e37_79b9_7f4a_7c15);
4133 for y in 0..height {
4134 for x in 0..width {
4135 seed = seed.wrapping_mul(6_364_136_223_846_793_005).wrapping_add(1);
4136 let noise = ((seed >> 33) % 5) as i32 - 2;
4137 let base = 40 + (x + y) as i32 / 2;
4138 picture.y[y * width + x] = base.saturating_add(noise).clamp(0, 255) as u16;
4139 }
4140 }
4141 for i in 0..(width / 2) * (height / 2) {
4142 picture.u[i] = 110;
4143 picture.v[i] = 140;
4144 }
4145 picture
4146 }
4147
4148 /// lane-lookahead's correctness witness. One group of lookahead
4149 /// (`Av1Encoder::drain_pending` hands the closed group to `ready` and
4150 /// codes the group before it) must not change WHAT is coded:
4151 ///
4152 /// * with the future half of the filter window empty AND the top ARF's
4153 /// temporal lambda window pinned to the past (`TPL_FUT=0`) the stream
4154 /// is byte for byte the one the encoder coded without a lookahead, at
4155 /// every run length -- 1 picture (no hidden frame at all), 7 (a short
4156 /// group), 8 (exactly `mini_gop`), 9 (a group plus a tail) and 17 --
4157 /// and at a GOP short enough (8) that key frames drain the buffer
4158 /// mid-run. lane-tplhalf's WIN=11 default also reads that buffer, so
4159 /// the identity arm pins the lambda window off or this witness tests
4160 /// a different lever;
4161 /// * every run decodes to exactly its picture count through OUR decoder
4162 /// and through ffmpeg, sample-exact between the two, so the flush and
4163 /// the `show_existing_frame` order survive the delay;
4164 /// * and with ONE future neighbour the top ARF's source filter actually
4165 /// reads it -- the stream MOVES (class gate-blind-to-feature: a
4166 /// buffered picture nothing consumes would pass every check above).
4167 #[test]
4168 fn the_lookahead_holds_one_group_and_still_codes_every_picture() {
4169 let _knobs = crate::speed::knob_write();
4170 // The preset is PROCESS-GLOBAL and another test may have left it
4171 // anywhere: at a high one every block of this fixture codes as skip
4172 // (17 pictures in 493 bytes) and the source filter cannot change a
4173 // byte, which failed the future-half assertion below in the suite and
4174 // passed it standalone (class process-global-knob-races-tests).
4175 let was = crate::speed::speed();
4176 crate::speed::set_speed(0);
4177 crate::encode::force_screen(Some(false));
4178 let (width, height) = (128usize, 128usize);
4179 let run = |n: usize, gop: usize, on: bool, fut: usize| -> (Vec<u8>, Vec<Packet>) {
4180 set_lookahead(Some(on));
4181 set_arf_tf_future(Some(fut));
4182 set_tpl_fut(Some(0));
4183 let config = EncoderConfig {
4184 // FINE (not the 120 the other facade tests use): at a coarse
4185 // quantizer this fixture's ARF codes almost pure skip (17
4186 // pictures in 493 bytes) and a filtered source quantizes back
4187 // to the same bytes, which made the future-half assertion
4188 // below depend on where the suite's other tests had left the
4189 // process-global preset. At q=60 the anchor carries real
4190 // coefficients and the filter must move them.
4191 base_q_idx: 60,
4192 width,
4193 height,
4194 gop,
4195 colour: Colour::Bt709Limited,
4196 tile_cols_log2: 0,
4197 tile_rows_log2: 0,
4198 };
4199 let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
4200 let sources: Vec<Picture> = (0..n).map(|t| noisy_card(width, height, t)).collect();
4201 let packets = encode_all(&mut enc, &sources);
4202 // The content gate is process-global and so is the preset: if
4203 // either has been flipped under this test the pyramid is gone and
4204 // there is no ARF to filter, which is a different failure from
4205 // "the future neighbour changed nothing" (the suite reported the
4206 // second when it meant the first).
4207 assert!(
4208 enc.pyramid().is_some(),
4209 "{n} pictures at gop {gop}: the content gate dropped the pyramid, so no ARF was coded (speed {})",
4210 crate::speed::speed(),
4211 );
4212 (concat(&packets), packets)
4213 };
4214 for gop in [32usize, 8] {
4215 for n in [1usize, 7, 8, 9, 17] {
4216 let (flat, flat_packets) = run(n, gop, false, 0);
4217 let (held, packets) = run(n, gop, true, 0);
4218 assert_eq!(
4219 flat.len(),
4220 held.len(),
4221 "{n} pictures at gop {gop}: the lookahead changed the stream LENGTH"
4222 );
4223 assert!(
4224 flat == held,
4225 "{n} pictures at gop {gop}: the stream is not byte-identical"
4226 );
4227 assert_eq!(
4228 packets
4229 .iter()
4230 .map(|p| (p.order, p.key, p.level))
4231 .collect::<Vec<_>>(),
4232 flat_packets
4233 .iter()
4234 .map(|p| (p.order, p.key, p.level))
4235 .collect::<Vec<_>>(),
4236 "{n} pictures at gop {gop}: coding order/levels moved"
4237 );
4238 let ours = crate::stream::decode_stream(&held).expect("our decoder");
4239 assert_eq!(
4240 ours.len(),
4241 n,
4242 "{n} pictures at gop {gop}: our decoder's count"
4243 );
4244 if !have_ffmpeg() {
4245 continue;
4246 }
4247 let theirs = ffmpeg_decode_luma(&held, width, height);
4248 assert_eq!(theirs.len(), n, "{n} pictures at gop {gop}: ffmpeg's count");
4249 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4250 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4251 assert!(
4252 got == *b,
4253 "{n} pictures at gop {gop}, display frame {i}: ours differs from ffmpeg"
4254 );
4255 }
4256 }
4257 }
4258 // The future half REACHES the filter, and what it produces still
4259 // decodes exactly.
4260 let (base, _) = run(17, 32, true, 0);
4261 let (symmetric, _) = run(17, 32, true, 1);
4262 set_lookahead(None);
4263 set_arf_tf_future(None);
4264 set_tpl_fut(None);
4265 assert!(
4266 base != symmetric,
4267 "one display-future neighbour left the top ARF's filter unchanged \
4268 ({} B vs {} B, preset {})",
4269 base.len(),
4270 symmetric.len(),
4271 crate::speed::speed()
4272 );
4273 let ours = crate::stream::decode_stream(&symmetric).expect("our decoder");
4274 assert_eq!(ours.len(), 17, "the symmetric arm's display-order count");
4275 if have_ffmpeg() {
4276 let theirs = ffmpeg_decode_luma(&symmetric, width, height);
4277 assert_eq!(theirs.len(), 17, "the symmetric arm's ffmpeg count");
4278 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4279 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4280 assert!(
4281 got == *b,
4282 "symmetric arm, display frame {i}: ours differs from ffmpeg"
4283 );
4284 }
4285 }
4286 crate::speed::set_speed(was);
4287 }
4288
4289 /// lane-tplfut's correctness witness, the sibling of
4290 /// [`the_lookahead_holds_one_group_and_still_codes_every_picture`]: with
4291 /// the top ARF's TEMPORAL LAMBDA window taken out of the buffered next
4292 /// group (`speed::TPL_FUT`), every picture is still coded, the streams
4293 /// decode exactly through our decoder and ffmpeg, and the stream MOVES
4294 /// against the knob off wherever a next group exists (class
4295 /// gate-blind-to-feature). Coded at q=60, not 120: at a coarse
4296 /// quantizer this fixture's ARF is almost pure skip and a different
4297 /// lambda map re-quantises to identical bytes.
4298 #[test]
4299 fn the_future_tpl_window_still_codes_every_picture_and_moves_the_stream() {
4300 let _knobs = crate::speed::knob_write();
4301 let was = crate::speed::speed();
4302 crate::speed::set_speed(0);
4303 crate::encode::force_screen(Some(false));
4304 let (width, height) = (128usize, 128usize);
4305 let run = |n: usize, gop: usize, fut: usize| -> (Vec<u8>, Vec<Packet>) {
4306 set_lookahead(Some(true));
4307 set_arf_tf_future(Some(0));
4308 set_tpl_fut(Some(fut));
4309 let config = EncoderConfig {
4310 base_q_idx: 60,
4311 width,
4312 height,
4313 gop,
4314 colour: Colour::Bt709Limited,
4315 tile_cols_log2: 0,
4316 tile_rows_log2: 0,
4317 };
4318 let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
4319 let sources: Vec<Picture> = (0..n).map(|t| noisy_card(width, height, t)).collect();
4320 let packets = encode_all(&mut enc, &sources);
4321 assert!(
4322 enc.pyramid().is_some(),
4323 "{n} pictures at gop {gop}: the content gate dropped the pyramid (speed {})",
4324 crate::speed::speed(),
4325 );
4326 (concat(&packets), packets)
4327 };
4328 for gop in [32usize, 8] {
4329 for n in [1usize, 7, 8, 9, 17] {
4330 let (off, off_packets) = run(n, gop, 0);
4331 for mode in [1usize, 2, 3] {
4332 let (on, packets) = run(n, gop, mode);
4333 assert_eq!(
4334 packets
4335 .iter()
4336 .map(|p| (p.order, p.key, p.level))
4337 .collect::<Vec<_>>(),
4338 off_packets
4339 .iter()
4340 .map(|p| (p.order, p.key, p.level))
4341 .collect::<Vec<_>>(),
4342 "{n} pictures at gop {gop} mode {mode}: coding order/levels moved"
4343 );
4344 let ours = crate::stream::decode_stream(&on).expect("our decoder");
4345 assert_eq!(
4346 ours.len(),
4347 n,
4348 "{n} pictures at gop {gop} mode {mode}: our count"
4349 );
4350 if !have_ffmpeg() {
4351 continue;
4352 }
4353 let theirs = ffmpeg_decode_luma(&on, width, height);
4354 assert_eq!(
4355 theirs.len(),
4356 n,
4357 "{n} pictures at gop {gop} mode {mode}: ffmpeg count"
4358 );
4359 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4360 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4361 assert!(
4362 got == *b,
4363 "{n} pictures at gop {gop} mode {mode}, frame {i}: ours differs from ffmpeg"
4364 );
4365 }
4366 }
4367 let _ = &off;
4368 }
4369 }
4370 // The future window REACHES the lambda map: 17 pictures at gop 32 is
4371 // three groups, so the first two top ARFs each have a next group
4372 // buffered and their windows really are display-future.
4373 let (off, _) = run(17, 32, 0);
4374 // Mode 2 is NOT in this list: at its default split it keeps the three
4375 // NEAREST past neighbours, and those dominate the propagation -- on
4376 // this 128x128 fixture the map moves too little to flip an RD
4377 // decision and the stream comes back byte-identical to mode 0. Not a
4378 // dead knob: the same run with `EC_AV1_TPL_FUT_HALF=1` (one past
4379 // neighbour, six future) does move the stream, and the gate below
4380 // measures mode 2 on real content.
4381 for mode in [1usize, 3] {
4382 let (on, _) = run(17, 32, mode);
4383 assert!(
4384 off != on,
4385 "mode {mode} left the top ARF's temporal lambda map unchanged \
4386 ({} B vs {} B, preset {})",
4387 off.len(),
4388 on.len(),
4389 crate::speed::speed()
4390 );
4391 }
4392 set_lookahead(None);
4393 set_arf_tf_future(None);
4394 set_tpl_fut(None);
4395 crate::speed::set_speed(was);
4396 }
4397
4398 /// lane-arfmode: the top ARF's leaf offer set. Three guards in one
4399 /// witness, over 17 pictures at gop 32 (three groups, so several top
4400 /// ARFs) at q=60 -- the lookahead witness's lesson: at a fine q the
4401 /// anchor carries real coefficients, so a cut that moves only the
4402 /// hidden frame's internal decisions cannot hide behind "everything
4403 /// quantized to the same bytes":
4404 ///
4405 /// 1. OFF (default and explicit `Some(0)`) is byte-identical -- the
4406 /// shipped table is 0 and the lever is bit-exact when off;
4407 /// 2. each armed mode (1 no intra, 2 no 8x8, 4 no compound) really
4408 /// FIRES -- its own [`crate::encode::take_arfmode_hits`] counter
4409 /// moves (class `gate-blind-to-feature`) -- and MOVES THE STREAM;
4410 /// 3. the coding order and levels never change, and every armed stream
4411 /// decodes sample-exact through `decode_stream` AND ffmpeg.
4412 #[test]
4413 fn the_arf_leaf_offer_set_fires_moves_the_stream_and_decodes_sample_exact() {
4414 let _knobs = crate::speed::knob_write();
4415 let was = crate::speed::speed();
4416 crate::speed::set_speed(0);
4417 crate::encode::force_screen(Some(false));
4418 let (width, height) = (128usize, 128usize);
4419 let run = |mode: Option<u8>| -> (Vec<u8>, Vec<Packet>) {
4420 crate::encode::set_arfmode(mode);
4421 let _ = crate::encode::take_arfmode_hits();
4422 let config = EncoderConfig {
4423 base_q_idx: 60,
4424 width,
4425 height,
4426 gop: 32,
4427 colour: Colour::Bt709Limited,
4428 tile_cols_log2: 0,
4429 tile_rows_log2: 0,
4430 };
4431 let mut enc = Av1Encoder::with_pyramid(config, Pyramid::default()).unwrap();
4432 // Groups at three luma LEVELS (the base ramp 40/110/180): the
4433 // middle group's top ARF sits halfway between the two dark/light
4434 // anchors its slots hold, which is exactly where neither
4435 // single-reference prediction nor intra wins by default -- the
4436 // AVERAGE of two references (compound) and the DC of the new
4437 // level (intra) do. Without this the synthetic cards' noise
4438 // quantizes to skip and no arm can move anything (measured:
4439 // 516 intra trials skipped, zero won, stream identical).
4440 let sources: Vec<Picture> = (0..17)
4441 .map(|t| {
4442 let mut p = noisy_card(width, height, t);
4443 let shift = 70i32 * (t / 8) as i32;
4444 for v in p.y.iter_mut() {
4445 *v = (i32::from(*v) + shift).clamp(0, 255) as u16;
4446 }
4447 p
4448 })
4449 .collect();
4450 let packets = encode_all(&mut enc, &sources);
4451 (concat(&packets), packets)
4452 };
4453 let (off, off_packets) = run(None);
4454 let (explicit_off, _) = run(Some(0));
4455 assert_eq!(
4456 off, explicit_off,
4457 "mode 0 is not bit-exact with the default"
4458 );
4459 for (mode, arm) in [(1u8, 0usize), (2, 1), (4, 2)] {
4460 let (on, packets) = run(Some(mode));
4461 let hits = crate::encode::take_arfmode_hits();
4462 assert_eq!(
4463 packets
4464 .iter()
4465 .map(|p| (p.order, p.key, p.level))
4466 .collect::<Vec<_>>(),
4467 off_packets
4468 .iter()
4469 .map(|p| (p.order, p.key, p.level))
4470 .collect::<Vec<_>>(),
4471 "mode {mode}: coding order/levels moved"
4472 );
4473 assert!(
4474 hits[arm] > 0,
4475 "mode {mode}: its counter never fired ({hits:?}) -- the lever is \
4476 gate-blind on this fixture",
4477 );
4478 assert_ne!(
4479 off, on,
4480 "mode {mode} left the stream byte-identical despite {} firing hits",
4481 hits[arm],
4482 );
4483 eprintln!(
4484 "mode {mode}: {} -> {} B, hits {hits:?}",
4485 off.len(),
4486 on.len()
4487 );
4488 let ours = crate::stream::decode_stream(&on).expect("our decoder");
4489 assert_eq!(ours.len(), 17, "mode {mode}: our decoder's picture count");
4490 if !have_ffmpeg() {
4491 continue;
4492 }
4493 let theirs = ffmpeg_decode_luma(&on, width, height);
4494 assert_eq!(theirs.len(), 17, "mode {mode}: ffmpeg's picture count");
4495 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4496 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4497 assert!(
4498 got == *b,
4499 "mode {mode}, frame {i}: ours differs from ffmpeg"
4500 );
4501 }
4502 }
4503 crate::encode::set_arfmode(None);
4504 crate::speed::set_speed(was);
4505 }
4506
4507 fn pyramid_round_trip(pyramid: Pyramid, hidden: usize) {
4508 let (width, height) = (128usize, 128usize);
4509 let config = EncoderConfig {
4510 width,
4511 height,
4512 base_q_idx: 120,
4513 gop: 32,
4514 colour: Colour::Bt709Limited,
4515 tile_cols_log2: 0,
4516 tile_rows_log2: 0,
4517 };
4518 // The content gate ([`Av1Encoder::encode_frames`]) would drop a
4519 // screen-content stream to the flat path, and a synthetic test card
4520 // is exactly the few-colour picture the detector fires on: this gate
4521 // is about the reordering, so it asks for camera content explicitly.
4522 crate::encode::force_screen(Some(false));
4523 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
4524 let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect();
4525 let _ = crate::encode::take_ref_frame_hits();
4526 let mut packets = Vec::new();
4527 for picture in &sources {
4528 packets.extend(enc.encode_frames(picture).unwrap());
4529 }
4530 packets.extend(enc.flush().unwrap());
4531
4532 // Shape: every source picture is coded exactly once, and each closed
4533 // group adds one `show_existing_frame` packet.
4534 let coded: Vec<u64> = packets
4535 .iter()
4536 .filter(|p| p.level != Level::ShowExisting)
4537 .map(|p| p.order)
4538 .collect();
4539 let mut sorted = coded.clone();
4540 sorted.sort_unstable();
4541 assert_eq!(
4542 sorted,
4543 (0..9).collect::<Vec<u64>>(),
4544 "one packet per picture"
4545 );
4546 assert_ne!(coded, sorted, "the pyramid never reordered anything");
4547 let shown = packets
4548 .iter()
4549 .filter(|p| p.level == Level::ShowExisting)
4550 .count();
4551 assert_eq!(shown, hidden, "one show_existing_frame per hidden frame");
4552 for (i, p) in packets.iter().enumerate() {
4553 assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position");
4554 }
4555 let hist = |l: Level| packets.iter().filter(|p| p.level == l).count();
4556 eprintln!(
4557 "pyramid levels: key {} arf {} leaf {} show_existing {}",
4558 hist(Level::Key),
4559 hist(Level::Arf),
4560 hist(Level::Leaf),
4561 hist(Level::ShowExisting),
4562 );
4563 assert_eq!(hist(Level::Arf), hidden, "hidden frames");
4564 let refs = crate::encode::take_ref_frame_hits();
4565 eprintln!(
4566 "blocks per reference: LAST {} GOLDEN {} ALTREF {}",
4567 refs[crate::mvstack::LAST_FRAME as usize],
4568 refs[crate::mvstack::GOLDEN_FRAME as usize],
4569 refs[crate::mvstack::ALTREF_FRAME as usize],
4570 );
4571 // [[gate-blind-to-feature]]: the whole point of the hidden frame is
4572 // that the leaves predict BACKWARD off it, which is also the only
4573 // thing that exercises `ref_frame_sign_bias` in the MV stack. A green
4574 // round trip in which `ALTREF_FRAME` never won a block would prove
4575 // only that a hidden frame can be written and re-output.
4576 assert!(
4577 refs[crate::mvstack::ALTREF_FRAME as usize] > 0,
4578 "no block predicted off the hidden ALTREF"
4579 );
4580
4581 let stream = concat(&packets);
4582 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4583 assert_eq!(
4584 ours.len(),
4585 sources.len(),
4586 "our decoder's display-order count"
4587 );
4588 if !have_ffmpeg() {
4589 eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg");
4590 return;
4591 }
4592 let theirs = ffmpeg_decode_luma(&stream, width, height);
4593 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
4594 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4595 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4596 assert_eq!(got.len(), b.len(), "frame {i}: luma size");
4597 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
4598 panic!(
4599 "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4600 at % width,
4601 at / width,
4602 got[at],
4603 b[at],
4604 );
4605 }
4606 }
4607 }
4608
4609 /// Every tile layout this encoder can write decodes SAMPLE-EXACT
4610 /// through both decoders -- ours and ffmpeg's -- and the frames really
4611 /// carry the tiles the header claims (the OBU parser locates one payload
4612 /// per tile, so a stream that quietly stayed single-tile fails here
4613 /// rather than passing on a green round trip).
4614 ///
4615 /// The bytes are what the gate is on: an encoder that clipped its
4616 /// neighbour availability wrong writes a stream whose two decoders agree
4617 /// with each other and disagree with nothing -- so the ffmpeg half is
4618 /// the one that catches a tile boundary the writer respected and the
4619 /// spec does not, and the parser half catches the reverse.
4620
4621 /// A STATIC clip: every inter frame predicts perfectly from the last, so
4622 /// the search takes the 64x64 root ([`crate::encode::B64_ROOT`]) instead
4623 /// of coding four 32x32 quadrants, and the stream both decoders
4624 /// reconstruct is still sample-exact against the encoder's own
4625 /// reconstruction. The counter is the point (class
4626 /// `gate-blind-to-feature`): without it a green three-way compare says
4627 /// nothing about whether a single 64x64 block was ever written.
4628 /// lane-sb128 step 1: the same static clip under a 128x128 SUPERBLOCK.
4629 /// Every partition decision below the root is the one the 64-superblock
4630 /// encoder makes -- the root itself is always `PARTITION_SPLIT` into the
4631 /// four 64x64 superblocks -- so the only thing this proves is the
4632 /// structural syntax: the root's own partition symbol, its loop
4633 /// restoration read once over the 128 span at the 128 unit size, and
4634 /// libaom's TL/TR/BL/BR visit order. 256x128 is 2x1 128x128 superblocks
4635 /// per frame over three frames, so the root fires 6 times.
4636 ///
4637 /// `#[ignore]`: [`crate::encode::force_sb128`] moves a process-global
4638 /// (the superblock size is a sequence field), so this gate runs alone:
4639 ///
4640 /// cargo test -p ec-av1 --release --lib -- --ignored \
4641 /// a_static_clip_codes_128x128_superblock_roots --nocapture
4642 #[test]
4643 #[ignore = "sets the process-global superblock size: run it alone"]
4644 fn a_static_clip_codes_128x128_superblock_roots_and_decodes_sample_exact() {
4645 let _knobs = crate::speed::knob_write();
4646 let _gate_lock = crate::stream::tests::lock_gate_counters();
4647 crate::encode::force_sb128(true);
4648 let (width, height) = (256usize, 128usize);
4649 let still = test_card(width, height, 0);
4650 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
4651 let config = EncoderConfig {
4652 width,
4653 height,
4654 base_q_idx: 120,
4655 gop: 8,
4656 colour: Colour::Bt709Limited,
4657 tile_cols_log2: 0,
4658 tile_rows_log2: 0,
4659 };
4660 let mut enc = Av1Encoder::new(config).unwrap();
4661 let mut stream = Vec::new();
4662 let _ = crate::tile::take_sb128_root_hits();
4663 for packet in encode_all(&mut enc, &sources) {
4664 stream.extend_from_slice(&packet.data);
4665 }
4666 let roots = crate::tile::take_sb128_root_hits();
4667 assert!(
4668 roots >= 4,
4669 "a 128x128-superblock clip coded {roots} superblock roots, wanted at least 4"
4670 );
4671 eprintln!("128x128 superblock roots: {roots}");
4672
4673 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4674 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4675 assert!(
4676 crate::decode::part128_split_hits() >= 4,
4677 "our decoder read no 128x128 superblock root"
4678 );
4679 if !have_ffmpeg() {
4680 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4681 return;
4682 }
4683 let theirs = ffmpeg_decode_luma(&stream, width, height);
4684 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4685 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4686 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4687 assert_eq!(&got, b, "frame {i}: ffmpeg and our decoder disagree");
4688 }
4689 }
4690
4691 #[test]
4692 fn a_static_clip_codes_64x64_roots_and_decodes_sample_exact() {
4693 let _knobs = crate::speed::knob_write();
4694 let _gate_lock = crate::stream::tests::lock_gate_counters();
4695 let (width, height) = (256usize, 128usize);
4696 let still = test_card(width, height, 0);
4697 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
4698 let config = EncoderConfig {
4699 width,
4700 height,
4701 base_q_idx: 120,
4702 gop: 8,
4703 colour: Colour::Bt709Limited,
4704 tile_cols_log2: 0,
4705 tile_rows_log2: 0,
4706 };
4707 let mut enc = Av1Encoder::new(config).unwrap();
4708 let mut stream = Vec::new();
4709 let _ = crate::encode::take_b64_root_hits();
4710 for packet in encode_all(&mut enc, &sources) {
4711 stream.extend_from_slice(&packet.data);
4712 }
4713 let roots = crate::encode::take_b64_root_hits();
4714 // 8 superblocks per frame, two inter frames.
4715 assert!(
4716 roots > 0,
4717 "a static clip coded no 64x64 root at all (of 16 inter superblocks)"
4718 );
4719 eprintln!("64x64 roots on a static clip: {roots} of 16 inter superblocks");
4720
4721 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4722 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4723 if !have_ffmpeg() {
4724 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4725 return;
4726 }
4727 let theirs = ffmpeg_decode_luma(&stream, width, height);
4728 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4729 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4730 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4731 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
4732 panic!(
4733 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4734 at % width,
4735 at / width,
4736 got[at],
4737 b[at],
4738 );
4739 }
4740 assert_eq!(
4741 got.len(),
4742 b.len(),
4743 "frame {i}: luma is {} samples, ffmpeg's is {}",
4744 got.len(),
4745 b.len()
4746 );
4747 }
4748 }
4749
4750 /// The same clip with a DC step between frames (lane-tx64): the 64x64
4751 /// root still predicts the whole superblock from the last frame, but the
4752 /// prediction is uniformly off, so the root's NON-skip arm -- one
4753 /// TX_64X64 luma transform and two TX_32X32 chroma ones -- prices below
4754 /// its skip arm and a 64x64 residual is really written. The counter is
4755 /// the gate (class `gate-blind-to-feature`; the static clip above cannot
4756 /// reach this arm at all because its prediction is exact), and both
4757 /// decoders have to reconstruct those coefficients sample-exact -- a
4758 /// writer that names the wrong coefficient set or the wrong `txfm_split`
4759 /// desyncs the whole tile here.
4760 #[test]
4761 fn a_dc_stepped_clip_codes_a_64x64_residual_and_decodes_sample_exact() {
4762 let _knobs = crate::speed::knob_write();
4763 let _gate_lock = crate::stream::tests::lock_gate_counters();
4764 let (width, height) = (256usize, 128usize);
4765 let still = test_card(width, height, 0);
4766 let sources: Vec<Picture> = (0..3)
4767 .map(|t| {
4768 let mut p = still.clone();
4769 let step = (t * 6) as u16;
4770 for v in &mut p.y {
4771 *v = (*v + step).min(255);
4772 }
4773 p
4774 })
4775 .collect();
4776 let config = EncoderConfig {
4777 width,
4778 height,
4779 base_q_idx: 120,
4780 gop: 8,
4781 colour: Colour::Bt709Limited,
4782 tile_cols_log2: 0,
4783 tile_rows_log2: 0,
4784 };
4785 let mut enc = Av1Encoder::new(config).unwrap();
4786 let mut stream = Vec::new();
4787 let _ = crate::encode::take_b64_residual_hits();
4788 for packet in encode_all(&mut enc, &sources) {
4789 stream.extend_from_slice(&packet.data);
4790 }
4791 let residuals = crate::encode::take_b64_residual_hits();
4792 assert!(
4793 residuals > 0,
4794 "a DC-stepped clip coded no 64x64 root with a residual at all"
4795 );
4796 eprintln!("64x64 roots with a residual: {residuals} of 16 inter superblocks");
4797
4798 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4799 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4800 if !have_ffmpeg() {
4801 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4802 return;
4803 }
4804 let theirs = ffmpeg_decode_luma(&stream, width, height);
4805 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4806 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
4807 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
4808 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
4809 panic!(
4810 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4811 at % width,
4812 at / width,
4813 got[at],
4814 b[at],
4815 );
4816 }
4817 assert_eq!(
4818 got.len(),
4819 b.len(),
4820 "frame {i}: luma is {} samples, ffmpeg's is {}",
4821 got.len(),
4822 b.len()
4823 );
4824 }
4825 }
4826
4827 /// A frame whose size is NOT a multiple of a superblock (lane-b64b):
4828 /// 232x168 leaves the last superblock column and row cut by the true
4829 /// frame edge, with more than half of each inside -- which is exactly
4830 /// what AV1's `has_cols`/`has_rows` allow to stay whole. Both gate films
4831 /// are superblock-aligned, so nothing but a synthetic size reaches this
4832 /// path at all (class `gate-blind-to-feature`), and the user's own
4833 /// exports are arbitrary sizes.
4834 #[test]
4835 fn a_non_superblock_aligned_clip_codes_edge_64x64_roots_and_decodes_sample_exact() {
4836 let _knobs = crate::speed::knob_write();
4837 let _gate_lock = crate::stream::tests::lock_gate_counters();
4838 let (width, height) = (232usize, 168usize);
4839 let still = test_card(width, height, 0);
4840 let sources: Vec<Picture> = (0..3).map(|_| still.clone()).collect();
4841 let config = EncoderConfig {
4842 width,
4843 height,
4844 base_q_idx: 120,
4845 gop: 8,
4846 colour: Colour::Bt709Limited,
4847 tile_cols_log2: 0,
4848 tile_rows_log2: 0,
4849 };
4850 let mut enc = Av1Encoder::new(config).unwrap();
4851 let mut stream = Vec::new();
4852 let _ = crate::encode::take_b64_edge_hits();
4853 for packet in encode_all(&mut enc, &sources) {
4854 stream.extend_from_slice(&packet.data);
4855 }
4856 let edges = crate::encode::take_b64_edge_hits();
4857 assert!(
4858 edges > 0,
4859 "no 64x64 root was taken at a superblock the frame edge cuts"
4860 );
4861 eprintln!("edge 64x64 roots: {edges}");
4862
4863 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4864 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4865 if !have_ffmpeg() {
4866 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4867 return;
4868 }
4869 let theirs = ffmpeg_decode_luma(&stream, width, height);
4870 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4871 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
4872 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
4873 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
4874 panic!(
4875 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4876 at % width,
4877 at / width,
4878 got[at],
4879 theirs_i[at],
4880 );
4881 }
4882 assert_eq!(
4883 got.len(),
4884 theirs_i.len(),
4885 "frame {i}: luma is {} samples, ffmpeg's is {}",
4886 got.len(),
4887 theirs_i.len()
4888 );
4889 }
4890 }
4891
4892 /// The 1080p SHAPE at a fifth of its size (lane-sse): 384x216 is three
4893 /// whole superblock columns and 1.6875 superblock rows, so the bottom
4894 /// 88-pixel band straddles at EVERY level -- the 64x64 root lane-b64b
4895 /// already clipped, and the 32x32 (216 = 6*32 + 24) and 16x16 (13*16 + 8)
4896 /// leaves it did not. Every one of them is now scored over its inside
4897 /// part alone, and a distortion change that moved a partition or a
4898 /// transform decision the writer did not follow would desync the tile, so
4899 /// both decoders reconstruct it sample-exact.
4900 #[test]
4901 fn a_1080p_shaped_clip_straddles_at_every_block_size_and_decodes_sample_exact() {
4902 let _knobs = crate::speed::knob_write();
4903 let _gate_lock = crate::stream::tests::lock_gate_counters();
4904 let (width, height) = (384usize, 216usize);
4905 let sources: Vec<Picture> = (0..3).map(|i| test_card(width, height, i)).collect();
4906 let config = EncoderConfig {
4907 width,
4908 height,
4909 base_q_idx: 120,
4910 gop: 8,
4911 colour: Colour::Bt709Limited,
4912 tile_cols_log2: 0,
4913 tile_rows_log2: 0,
4914 };
4915 let mut enc = Av1Encoder::new(config).unwrap();
4916 let mut stream = Vec::new();
4917 for packet in encode_all(&mut enc, &sources) {
4918 stream.extend_from_slice(&packet.data);
4919 }
4920 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4921 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4922 if !have_ffmpeg() {
4923 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4924 return;
4925 }
4926 let theirs = ffmpeg_decode_luma(&stream, width, height);
4927 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
4928 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
4929 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
4930 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
4931 panic!(
4932 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
4933 at % width,
4934 at / width,
4935 got[at],
4936 theirs_i[at],
4937 );
4938 }
4939 assert_eq!(
4940 got.len(),
4941 theirs_i.len(),
4942 "frame {i}: luma is {} samples, ffmpeg's is {}",
4943 got.len(),
4944 theirs_i.len()
4945 );
4946 }
4947 }
4948
4949 /// A clip whose inter residual is HIGH-FREQUENCY (lane-b64b): every
4950 /// frame adds a 4-pixel checkerboard, so the 64x64 root's prediction is
4951 /// off by exactly the detail a TX_64X64 throws away (it codes only the
4952 /// top-left 32x32 corner of its coefficient space) and the root's var-tx
4953 /// arm splits its luma into four TX_32X32 units instead. The counter is
4954 /// the gate (class `gate-blind-to-feature`), and a `txfm_split` the
4955 /// reader does not expect desyncs the whole tile, so both decoders have
4956 /// to reconstruct it sample-exact.
4957 #[test]
4958 fn a_high_frequency_clip_splits_the_64x64_roots_luma_and_decodes_sample_exact() {
4959 let _knobs = crate::speed::knob_write();
4960 let _gate_lock = crate::stream::tests::lock_gate_counters();
4961 let (width, height) = (256usize, 128usize);
4962 let still = test_card(width, height, 0);
4963 let sources: Vec<Picture> = (0..4)
4964 .map(|t| {
4965 let mut p = still.clone();
4966 for (i, v) in p.y.iter_mut().enumerate() {
4967 let checker = ((i % width) / 4 + (i / width) / 4) % 2;
4968 let bump = (t * 5 * (checker + 1)) as u16;
4969 *v = (*v + bump).min(255);
4970 }
4971 p
4972 })
4973 .collect();
4974 let config = EncoderConfig {
4975 width,
4976 height,
4977 base_q_idx: 90,
4978 gop: 8,
4979 colour: Colour::Bt709Limited,
4980 tile_cols_log2: 0,
4981 tile_rows_log2: 0,
4982 };
4983 let mut enc = Av1Encoder::new(config).unwrap();
4984 let mut stream = Vec::new();
4985 let _ = crate::encode::take_b64_var_tx_hits();
4986 for packet in encode_all(&mut enc, &sources) {
4987 stream.extend_from_slice(&packet.data);
4988 }
4989 let split = crate::encode::take_b64_var_tx_hits();
4990 assert!(split > 0, "no 64x64 root split its luma transform at all");
4991 eprintln!("64x64 roots with a SPLIT luma transform: {split}");
4992
4993 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
4994 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
4995 if !have_ffmpeg() {
4996 eprintln!("SKIP the ffmpeg half: no ffmpeg");
4997 return;
4998 }
4999 let theirs = ffmpeg_decode_luma(&stream, width, height);
5000 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5001 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
5002 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
5003 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
5004 panic!(
5005 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
5006 at % width,
5007 at / width,
5008 got[at],
5009 theirs_i[at],
5010 );
5011 }
5012 assert_eq!(
5013 got.len(),
5014 theirs_i.len(),
5015 "frame {i}: luma is {} samples, ffmpeg's is {}",
5016 got.len(),
5017 theirs_i.len()
5018 );
5019 }
5020 }
5021
5022 /// A CROSSFADE clip (lane-b64b): each picture is a linear blend of two
5023 /// stills, so on a leaf frame the average of its past (`LAST`) and future
5024 /// (`ALTREF`) references IS the source and neither reference alone is --
5025 /// exactly the content a COMPOUND 64x64 root pays on. The counter is the
5026 /// gate (class `gate-blind-to-feature`): without it a green three-way
5027 /// compare says nothing about whether one compound root was written, and
5028 /// the writer's compound arm (`write_compound_block` at `SB_MI` 16, no
5029 /// `motion_mode` symbol) desyncs the whole tile if it is wrong.
5030 #[test]
5031 fn a_crossfade_clip_codes_a_compound_64x64_root_and_decodes_sample_exact() {
5032 let _knobs = crate::speed::knob_write();
5033 let _gate_lock = crate::stream::tests::lock_gate_counters();
5034 let (width, height) = (256usize, 128usize);
5035 let (a, b) = (test_card(width, height, 0), test_card(width, height, 24));
5036 let sources: Vec<Picture> = (0..9)
5037 .map(|t| {
5038 let mut p = a.clone();
5039 let w = t as u32;
5040 for (v, &other) in p.y.iter_mut().zip(&b.y) {
5041 *v = ((u32::from(*v) * (8 - w) + u32::from(other) * w) / 8) as u16;
5042 }
5043 p
5044 })
5045 .collect();
5046 let config = EncoderConfig {
5047 width,
5048 height,
5049 base_q_idx: 120,
5050 gop: 9,
5051 colour: Colour::Bt709Limited,
5052 tile_cols_log2: 0,
5053 tile_rows_log2: 0,
5054 };
5055 let mut enc = Av1Encoder::new(config).unwrap();
5056 let mut stream = Vec::new();
5057 let _ = crate::encode::take_b64_compound_hits();
5058 for packet in encode_all(&mut enc, &sources) {
5059 stream.extend_from_slice(&packet.data);
5060 }
5061 let compound = crate::encode::take_b64_compound_hits();
5062 assert!(
5063 compound > 0,
5064 "a crossfade clip coded no COMPOUND 64x64 root at all"
5065 );
5066 eprintln!("compound 64x64 roots on a crossfade clip: {compound}");
5067
5068 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5069 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
5070 if !have_ffmpeg() {
5071 eprintln!("SKIP the ffmpeg half: no ffmpeg");
5072 return;
5073 }
5074 let theirs = ffmpeg_decode_luma(&stream, width, height);
5075 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5076 for (i, (ours_i, theirs_i)) in ours.iter().zip(&theirs).enumerate() {
5077 let got: Vec<u8> = ours_i.y.iter().map(|&v| v as u8).collect();
5078 if let Some(at) = got.iter().zip(theirs_i).position(|(x, y)| x != y) {
5079 panic!(
5080 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
5081 at % width,
5082 at / width,
5083 got[at],
5084 theirs_i[at],
5085 );
5086 }
5087 assert_eq!(
5088 got.len(),
5089 theirs_i.len(),
5090 "frame {i}: luma is {} samples, ffmpeg's is {}",
5091 got.len(),
5092 theirs_i.len()
5093 );
5094 }
5095 }
5096
5097 #[test]
5098 fn every_tile_layout_decodes_sample_exact_through_both_decoders() {
5099 let _knobs = crate::speed::knob_read();
5100 let (width, height) = (640usize, 384usize);
5101 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
5102 let mut sizes = Vec::new();
5103 for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] {
5104 let config = EncoderConfig {
5105 width,
5106 height,
5107 base_q_idx: 120,
5108 gop: 4,
5109 colour: Colour::Bt709Limited,
5110 tile_cols_log2: cols_log2,
5111 tile_rows_log2: rows_log2,
5112 };
5113 let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
5114 // lane-b128m: the SPEC's uniform spacing derives the tile count
5115 // from the superblock grid (`tileWidthSb = ceil(sbCols >> log2)`),
5116 // so a frame with fewer superblock columns than the requested
5117 // count codes fewer tiles -- which is what a 128-superblock
5118 // sequence does here. The grid the encoder itself computes is the
5119 // expectation; at 64 superblocks it is `1 << log2` exactly.
5120 let grid = crate::tile::TileLayout::new(
5121 (width as u32).div_ceil(4),
5122 (height as u32).div_ceil(4),
5123 cols_log2,
5124 rows_log2,
5125 );
5126 let (want_cols, want_rows) = (grid.cols(), grid.rows());
5127 let mut enc = Av1Encoder::new(config).unwrap();
5128 let mut stream = Vec::new();
5129 for packet in encode_all(&mut enc, &sources) {
5130 stream.extend_from_slice(&packet.data);
5131 }
5132 sizes.push((layout.clone(), stream.len()));
5133
5134 // The frames carry the tiles their headers claim.
5135 let mut parser = ec_av1_syntax::Av1Parser::new();
5136 let mut frames = 0usize;
5137 let mut offset = 0usize;
5138 while offset < stream.len() {
5139 let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap();
5140 let unit: usize = obus.iter().map(|o| o.total_size).sum();
5141 for obu in &obus {
5142 if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind {
5143 assert_eq!(
5144 (parsed.tile_info.cols, parsed.tile_info.rows),
5145 (want_cols, want_rows),
5146 "{layout}: the header's own tile grid"
5147 );
5148 assert_eq!(
5149 tiles.len(),
5150 (want_cols * want_rows) as usize,
5151 "{layout}: tile payloads located in the tile group"
5152 );
5153 frames += 1;
5154 }
5155 }
5156 offset += unit;
5157 }
5158 assert_eq!(frames, sources.len(), "{layout}: coded frames");
5159
5160 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5161 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
5162 if !have_ffmpeg() {
5163 eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg");
5164 continue;
5165 }
5166 let theirs = ffmpeg_decode_luma(&stream, width, height);
5167 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
5168 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
5169 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
5170 assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size");
5171 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
5172 panic!(
5173 "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
5174 at % width,
5175 at / width,
5176 got[at],
5177 b[at],
5178 );
5179 }
5180 }
5181 }
5182 let base = sizes[0].1 as f64;
5183 for (layout, bytes) in &sizes {
5184 eprintln!(
5185 "{layout}: {bytes} bytes ({:+.2}% vs one tile)",
5186 (*bytes as f64 / base - 1.0) * 100.0
5187 );
5188 }
5189 }
5190
5191 /// lane-deltaq's three-way witness: a clip with a real gradient of tpl
5192 /// factors -- a moving detail region over a flat background, so the
5193 /// superblocks the NEXT picture predicts from are worth more than the
5194 /// ones it does not -- codes at least two distinct per-superblock
5195 /// quantizer levels (the fire count, class `gate-blind-to-feature`), and
5196 /// both decoders reconstruct every frame sample-exact from the
5197 /// `delta_qindex` syntax that carries them.
5198 #[test]
5199 fn a_moving_detail_clip_codes_two_delta_q_levels_both_decoders_read_exactly() {
5200 // `knob_write`, not `knob_read`: the override below is
5201 // process-global and every other test's bytes move under it.
5202 let _knobs = crate::speed::knob_write();
5203 let _gate_lock = crate::stream::tests::lock_gate_counters();
5204 crate::encode::set_deltaq_res(Some(2));
5205 let (width, height) = (640usize, 384usize);
5206 // The gate's own moving test card, with a 128x128 patch of fine
5207 // detail travelling right by 32 samples a frame laid over it: the
5208 // patch is what the tpl pass finds worth propagating and the card
5209 // around it is not, so the map -- and with it the quantizer grid --
5210 // is a gradient and not one flat number.
5211 let sources: Vec<Picture> = (0..4)
5212 .map(|t| {
5213 let mut p = test_card(width, height, t * 3);
5214 let x0 = 32 + t * 32;
5215 for y in 128..256 {
5216 for x in x0..x0 + 128 {
5217 p.y[y * width + x] = if (x / 2 + y / 3) % 2 == 0 { 40 } else { 210 };
5218 }
5219 }
5220 p
5221 })
5222 .collect();
5223 let config = EncoderConfig {
5224 width,
5225 height,
5226 base_q_idx: 120,
5227 gop: 4,
5228 colour: Colour::Bt709Limited,
5229 tile_cols_log2: 0,
5230 tile_rows_log2: 0,
5231 };
5232 let mut enc = Av1Encoder::new(config).unwrap();
5233 let _ = crate::encode::take_deltaq_levels();
5234 let mut stream = Vec::new();
5235 for packet in encode_all(&mut enc, &sources) {
5236 stream.extend_from_slice(&packet.data);
5237 }
5238 let levels = crate::encode::take_deltaq_levels();
5239 // The quantizer grid rides the tpl map, and `speed::TPL_DEPTH` cuts
5240 // the lookahead window to one picture at the top presets, so there IS
5241 // no map -- and no delta_q syntax -- there. The exactness half below
5242 // still runs; only the fire count needs a window (lane-tplwin: the
5243 // predicate is the window, not preset 0, since presets 1..6 have one).
5244 if crate::speed::at(&crate::speed::TPL_DEPTH) > 1 {
5245 assert!(
5246 levels >= 2,
5247 "the quantizer grid was flat ({levels} level(s)): no delta_qindex was coded"
5248 );
5249 } else {
5250 eprintln!(
5251 "SKIP the fire count at preset {}: no tpl map",
5252 crate::speed::speed()
5253 );
5254 }
5255 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5256 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
5257 if have_ffmpeg() {
5258 let theirs = ffmpeg_decode_luma(&stream, width, height);
5259 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5260 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
5261 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
5262 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
5263 panic!(
5264 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
5265 at % width,
5266 at / width,
5267 got[at],
5268 b[at],
5269 );
5270 }
5271 assert_eq!(
5272 got.len(),
5273 b.len(),
5274 "frame {i}: luma is {} samples, ffmpeg's is {}",
5275 got.len(),
5276 b.len()
5277 );
5278 }
5279 } else {
5280 eprintln!("SKIP the ffmpeg half: no ffmpeg");
5281 }
5282 crate::encode::set_deltaq_res(None);
5283 eprintln!(
5284 "delta_q witness: {levels} quantizer levels, {} bytes",
5285 stream.len()
5286 );
5287 }
5288
5289 /// lane-txset's witness: a clip of hard directional edges makes the intra
5290 /// luma search take EVERY type of the five-type reduced set
5291 /// (`TX_SET_INTRA_2`: `DCT_DCT`, `ADST_ADST`, `ADST_DCT`, `DCT_ADST`,
5292 /// `IDTX`) at least once -- the fire count, class `gate-blind-to-feature`
5293 /// -- and both decoders reconstruct every frame sample-exact from the
5294 /// `tx_type` symbols that name them. Before the lane the writer coded
5295 /// `DCT_DCT` for every luma transform unit ever written, so this is also
5296 /// the statement that the other four are REACHABLE at all.
5297 #[test]
5298 fn an_edge_clip_codes_every_reduced_set_tx_type_both_decoders_read_exactly() {
5299 // `knob_write`: the screen override below is process-global, and the
5300 // type search is SCREEN-ONLY (`encode::tx_type_candidates`).
5301 let _knobs = crate::speed::knob_write();
5302 crate::encode::force_screen(Some(true));
5303 let _gate_lock = crate::stream::tests::lock_gate_counters();
5304 let (width, height) = (320usize, 192usize);
5305 // Sharp horizontal and vertical steps: a vertical edge is what an
5306 // `ADST` column pass beats a `DCT` one on, a horizontal edge the
5307 // mirror, and the flat/ramp areas between them are where `IDTX` wins.
5308 let sources: Vec<Picture> = (0..2)
5309 .map(|t| {
5310 let mut p = test_card(width, height, t * 3);
5311 for y in 0..height {
5312 for x in 0..width {
5313 let v = match ((x + t * 4) / 16 % 2, y / 16 % 2) {
5314 (0, 0) => 16u16,
5315 (1, 0) => 235,
5316 (0, 1) => (x % 64 * 3) as u16,
5317 _ => (y % 64 * 3) as u16,
5318 };
5319 p.y[y * width + x] = v;
5320 }
5321 }
5322 p
5323 })
5324 .collect();
5325 let config = EncoderConfig {
5326 width,
5327 height,
5328 base_q_idx: 90,
5329 gop: 2,
5330 colour: Colour::Bt709Limited,
5331 tile_cols_log2: 0,
5332 tile_rows_log2: 0,
5333 };
5334 let mut enc = Av1Encoder::new(config).unwrap();
5335 let _ = crate::encode::take_tx_type_hits();
5336 let mut stream = Vec::new();
5337 for packet in encode_all(&mut enc, &sources) {
5338 stream.extend_from_slice(&packet.data);
5339 }
5340 let hits = crate::encode::take_tx_type_hits();
5341 // The type search is a speed lever (`speed::TX_TYPE_SEARCH`); above
5342 // the presets that carry it only `DCT_DCT` is offered, and the
5343 // exactness half below is what still runs there. The FULL five-type
5344 // fire count is preset 0's to make: a faster preset prunes modes and
5345 // partitions before a type is ever priced on them, so `ADST_ADST` and
5346 // `IDTX` stop winning on this clip at preset 6 (measured: hits
5347 // `[0, 6192, 0, 79, 284, ..]`). Every preset that carries the lever
5348 // still has to reach SOME non-`DCT_DCT` type -- that is the
5349 // "reachable at all" statement, class `gate-blind-to-feature`.
5350 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) {
5351 let non_dct: usize =
5352 hits.iter().sum::<usize>() - hits[crate::transform::TxType::DctDct as usize];
5353 assert!(
5354 non_dct > 0,
5355 "every luma transform unit took DCT_DCT: {hits:?}"
5356 );
5357 }
5358 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 {
5359 for (name, ty) in [
5360 ("DCT_DCT", crate::transform::TxType::DctDct),
5361 ("ADST_ADST", crate::transform::TxType::AdstAdst),
5362 ("ADST_DCT", crate::transform::TxType::AdstDct),
5363 ("DCT_ADST", crate::transform::TxType::DctAdst),
5364 ("IDTX", crate::transform::TxType::Idtx),
5365 ] {
5366 assert!(
5367 hits[ty as usize] > 0,
5368 "no luma transform unit took {name}: {hits:?}"
5369 );
5370 }
5371 } else {
5372 eprintln!(
5373 "SKIP the five-type fire count at preset {}: {hits:?}",
5374 crate::speed::speed()
5375 );
5376 }
5377 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5378 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
5379 if have_ffmpeg() {
5380 let theirs = ffmpeg_decode_luma(&stream, width, height);
5381 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5382 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
5383 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
5384 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
5385 panic!(
5386 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
5387 at % width,
5388 at / width,
5389 got[at],
5390 b[at],
5391 );
5392 }
5393 assert_eq!(
5394 got.len(),
5395 b.len(),
5396 "frame {i}: luma is {} samples, ffmpeg's is {}",
5397 got.len(),
5398 b.len()
5399 );
5400 }
5401 } else {
5402 eprintln!("SKIP the ffmpeg half: no ffmpeg");
5403 }
5404 crate::encode::force_screen(None);
5405 eprintln!("tx_type witness: hits {hits:?}, {} bytes", stream.len());
5406 }
5407
5408 /// lane-txset2's witness: an INTER frame's luma transform units take BOTH
5409 /// types of the two-type inter set the writer already codes a symbol for
5410 /// (`TX_SET_INTER_3`: `IDTX` and `DCT_DCT`) at least once -- the fire
5411 /// count, class `gate-blind-to-feature` -- and both decoders reconstruct
5412 /// every frame sample-exact from the `tx_type` symbols that name them.
5413 /// Before this lane every inter luma unit was coded `DCT_DCT`.
5414 #[test]
5415 fn an_inter_clip_codes_both_inter_set_tx_types_both_decoders_read_exactly() {
5416 // The lever is OFF at every preset (`speed::TX_TYPE_SEARCH_INTER`), so
5417 // this turns it on process-globally under the same exclusive lock the
5418 // presets take.
5419 let _knobs = crate::speed::knob_write();
5420 let _gate_lock = crate::stream::tests::lock_gate_counters();
5421 crate::encode::set_inter_tx_search(Some(true));
5422 let (width, height) = (320usize, 192usize);
5423 // Sharp steps that MOVE: the motion-compensated residual along a
5424 // moving edge is exactly where the identity transform beats a DCT,
5425 // and the flat plateaus between them predict to nothing at all.
5426 let sources: Vec<Picture> = (0..4)
5427 .map(|t| {
5428 let mut p = test_card(width, height, t * 3);
5429 for y in 0..height {
5430 for x in 0..width {
5431 let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) {
5432 (0, 0) => 16u16,
5433 (1, 0) => 235,
5434 (0, 1) => ((x + t) % 64 * 3) as u16,
5435 _ => ((y + t) % 64 * 3) as u16,
5436 };
5437 p.y[y * width + x] = v;
5438 }
5439 }
5440 p
5441 })
5442 .collect();
5443 let config = EncoderConfig {
5444 width,
5445 height,
5446 base_q_idx: 90,
5447 gop: 4,
5448 colour: Colour::Bt709Limited,
5449 tile_cols_log2: 0,
5450 tile_rows_log2: 0,
5451 };
5452 let mut enc = Av1Encoder::new(config).unwrap();
5453 let _ = crate::encode::take_inter_tx_type_hits();
5454 let mut stream = Vec::new();
5455 for packet in encode_all(&mut enc, &sources) {
5456 stream.extend_from_slice(&packet.data);
5457 }
5458 let hits = crate::encode::take_inter_tx_type_hits();
5459 crate::encode::set_inter_tx_search(None);
5460 for (name, ty) in [
5461 ("DCT_DCT", crate::transform::TxType::DctDct),
5462 ("IDTX", crate::transform::TxType::Idtx),
5463 ] {
5464 assert!(
5465 hits[ty as usize] > 0,
5466 "no inter luma transform unit was CODED {name}: {hits:?}"
5467 );
5468 }
5469 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5470 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
5471 if have_ffmpeg() {
5472 let theirs = ffmpeg_decode_luma(&stream, width, height);
5473 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5474 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
5475 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
5476 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
5477 panic!(
5478 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
5479 at % width,
5480 at / width,
5481 got[at],
5482 b[at],
5483 );
5484 }
5485 assert_eq!(
5486 got.len(),
5487 b.len(),
5488 "frame {i}: luma is {} samples, ffmpeg's is {}",
5489 got.len(),
5490 b.len()
5491 );
5492 }
5493 } else {
5494 eprintln!("SKIP the ffmpeg half: no ffmpeg");
5495 }
5496 eprintln!(
5497 "inter tx_type witness: hits {hits:?}, {} bytes",
5498 stream.len()
5499 );
5500 }
5501
5502 /// lane-txi's witness: a `reduced_tx_set = 0` frame codes the WIDER
5503 /// `tx_type` alphabets -- the seven-type `TX_SET_INTRA_1` at intra
5504 /// 8x8/4x4 and the twelve/sixteen-type inter sets at 16x16 and below --
5505 /// and both decoders reconstruct every frame sample-exact from them. The
5506 /// statement is that the types only those alphabets can NAME (`V_DCT`,
5507 /// `H_DCT`, and any inter type outside the two-type `DCT_IDTX`) are
5508 /// reachable at all, and that the header bit, the writer's set map and
5509 /// the search's pricer agree on which alphabet a symbol was coded into
5510 /// (class `wrong-alphabet-same-value`: a disagreement here changes no
5511 /// symbol VALUE and desyncs the arithmetic coder anyway).
5512 #[test]
5513 #[ignore = "sets process-global search levers: run it alone"]
5514 fn a_wide_tx_set_clip_codes_the_new_alphabets_both_decoders_read_exactly() {
5515 // Every lever below is process-global: the same exclusive lock the
5516 // presets take.
5517 let _knobs = crate::speed::knob_write();
5518 let _gate_lock = crate::stream::tests::lock_gate_counters();
5519 crate::encode::set_intra_tx_search(Some(true));
5520 crate::encode::set_inter_tx_search(Some(true));
5521 crate::encode::set_wide_tx_set(Some(true));
5522 let (width, height) = (320usize, 192usize);
5523 // The same moving hard-edge card the two narrow-set witnesses use:
5524 // vertical steps are what a 1-D `V_DCT`/`H_DCT` pass wins on, the
5525 // ramps are `ADST`'s and the moving plateaus `IDTX`'s.
5526 let sources: Vec<Picture> = (0..4)
5527 .map(|t| {
5528 let mut p = test_card(width, height, t * 3);
5529 for y in 0..height {
5530 for x in 0..width {
5531 let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) {
5532 (0, 0) => 16u16,
5533 (1, 0) => 235,
5534 (0, 1) => ((x + t) % 64 * 3) as u16,
5535 _ => ((y + t) % 64 * 3) as u16,
5536 };
5537 p.y[y * width + x] = v;
5538 }
5539 }
5540 p
5541 })
5542 .collect();
5543 let config = EncoderConfig {
5544 width,
5545 height,
5546 base_q_idx: 90,
5547 gop: 4,
5548 colour: Colour::Bt709Limited,
5549 tile_cols_log2: 0,
5550 tile_rows_log2: 0,
5551 };
5552 let mut enc = Av1Encoder::new(config).unwrap();
5553 let _ = crate::encode::take_tx_type_hits();
5554 let _ = crate::encode::take_inter_tx_type_hits();
5555 let mut stream = Vec::new();
5556 for packet in encode_all(&mut enc, &sources) {
5557 stream.extend_from_slice(&packet.data);
5558 }
5559 let (intra, inter) = (
5560 crate::encode::take_tx_type_hits(),
5561 crate::encode::take_inter_tx_type_hits(),
5562 );
5563 crate::encode::set_wide_tx_set(None);
5564 crate::encode::set_inter_tx_search(None);
5565 crate::encode::set_intra_tx_search(None);
5566 eprintln!(
5567 "wide tx_type witness: intra {intra:?} inter {inter:?}, {} bytes",
5568 stream.len()
5569 );
5570 // The fire count is preset 0's, for the reason the five-type witness
5571 // spells out: a faster preset prunes the modes and partitions a type
5572 // wins on before it is ever priced (class `gate-blind-to-feature`).
5573 if crate::speed::at(&crate::speed::TX_TYPE_SEARCH) && crate::speed::speed() == 0 {
5574 use crate::transform::TxType;
5575 let wide_only = |hits: &[usize; 16]| -> usize {
5576 hits[TxType::VDct as usize] + hits[TxType::HDct as usize]
5577 };
5578 assert!(
5579 wide_only(&intra) > 0,
5580 "no intra luma unit took a 1-D DCT, the type only TX_SET_INTRA_1 names: {intra:?}"
5581 );
5582 // The INTER units of this same frame are coded into the
5583 // twelve/sixteen-symbol alphabets too (the header bit widens
5584 // every luma set at once), but their SEARCH still offers the
5585 // two-type list -- see `encode::inter_luma_set`'s note on the
5586 // reference-slot refusal the wider inter candidates trip. So the
5587 // statement here is that those units still decode sample-exact
5588 // out of the wider alphabet, which the two decoders below make.
5589 assert!(
5590 inter.iter().sum::<usize>() > 0,
5591 "the clip coded no inter luma transform unit at all: {inter:?}"
5592 );
5593 } else {
5594 eprintln!(
5595 "SKIP the wide-alphabet fire count at preset {}",
5596 crate::speed::speed()
5597 );
5598 }
5599 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5600 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
5601 if have_ffmpeg() {
5602 let theirs = ffmpeg_decode_luma(&stream, width, height);
5603 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5604 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
5605 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
5606 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
5607 panic!(
5608 "frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
5609 at % width,
5610 at / width,
5611 got[at],
5612 b[at],
5613 );
5614 }
5615 assert_eq!(
5616 got.len(),
5617 b.len(),
5618 "frame {i}: luma is {} samples, ffmpeg's is {}",
5619 got.len(),
5620 b.len()
5621 );
5622 }
5623 } else {
5624 eprintln!("SKIP the ffmpeg half: no ffmpeg");
5625 }
5626 }
5627 /// lane-intertx's witness: on a clip the screen detector calls
5628 /// NON-screen, the inter luma search offers the wider
5629 /// `reduced_tx_set = 0` alphabets and CODES a 1-D `V_DCT`/`H_DCT` unit
5630 /// (a `coded > 0` guard on the committed-winners census, class
5631 /// `gate-blind-to-feature`), the block's chroma transforms inherit that
5632 /// type reduced to the chroma size's set against the frame's own honest
5633 /// header bit, and BOTH decoders reconstruct every frame sample-exact on
5634 /// ALL THREE planes -- chroma is the plane the inheritance desync
5635 /// corrupts, so luma-only comparisons cannot see it.
5636 #[test]
5637 #[ignore = "sets process-global search levers: run it alone"]
5638 fn a_non_screen_inter_clip_codes_a_one_d_type_both_decoders_read_every_plane_exactly() {
5639 let _knobs = crate::speed::knob_write();
5640 let _gate_lock = crate::stream::tests::lock_gate_counters();
5641 crate::encode::set_intra_tx_search(Some(true));
5642 crate::encode::set_inter_tx_search(Some(true));
5643 crate::encode::set_wide_tx_set(Some(true));
5644 crate::encode::force_screen(Some(false));
5645 let (width, height) = (320usize, 192usize);
5646 // The wide witness's moving card: vertical steps (where a 1-D
5647 // `V_DCT`/`H_DCT` beats the 2-D DCT on the motion-compensated
5648 // residual), ramps (`ADST`) and moving plateaus (`IDTX`), translated
5649 // a few samples per frame so the inter search sees real motion.
5650 let sources: Vec<Picture> = (0..4)
5651 .map(|t| {
5652 let mut p = test_card(width, height, t * 3);
5653 for y in 0..height {
5654 for x in 0..width {
5655 let v = match ((x + t * 5) / 16 % 2, (y + t * 3) / 16 % 2) {
5656 (0, 0) => 16u16,
5657 (1, 0) => 235,
5658 (0, 1) => ((x + t) % 64 * 3) as u16,
5659 _ => ((y + t) % 64 * 3) as u16,
5660 };
5661 p.y[y * width + x] = v;
5662 }
5663 }
5664 p
5665 })
5666 .collect();
5667 let config = EncoderConfig {
5668 width,
5669 height,
5670 base_q_idx: 90,
5671 gop: 4,
5672 colour: Colour::Bt709Limited,
5673 tile_cols_log2: 0,
5674 tile_rows_log2: 0,
5675 };
5676 let mut enc = Av1Encoder::new(config).unwrap();
5677 let _ = crate::encode::take_inter_tx_type_hits();
5678 let mut stream = Vec::new();
5679 for packet in encode_all(&mut enc, &sources) {
5680 stream.extend_from_slice(&packet.data);
5681 }
5682 let hits = crate::encode::take_inter_tx_type_hits();
5683 crate::encode::force_screen(None);
5684 crate::encode::set_wide_tx_set(None);
5685 crate::encode::set_inter_tx_search(None);
5686 crate::encode::set_intra_tx_search(None);
5687 use crate::transform::TxType;
5688 eprintln!(
5689 "inter wide-set witness: inter hits {hits:?}, {} bytes",
5690 stream.len()
5691 );
5692 assert!(
5693 hits[TxType::Idtx as usize] > 0,
5694 "no inter luma unit was CODED IDTX: {hits:?}"
5695 );
5696 assert!(
5697 hits[TxType::VDct as usize] + hits[TxType::HDct as usize] > 0,
5698 "no inter luma unit was CODED a 1-D type -- the wider search \
5699 never fired on non-screen content (class gate-blind-to-feature): {hits:?}"
5700 );
5701 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5702 assert_eq!(ours.len(), sources.len(), "our decoder's frames");
5703 if have_ffmpeg() {
5704 let theirs = ffmpeg_decode_planes(&stream, width, height);
5705 assert_eq!(theirs.len(), sources.len(), "ffmpeg's frames");
5706 let (cw, ch) = (width / 2, height / 2);
5707 for (i, (a, (y, u, v))) in ours.iter().zip(&theirs).enumerate() {
5708 for (name, got16, want, w) in [
5709 ("y", &a.y, y, width),
5710 ("u", &a.u, u, cw),
5711 ("v", &a.v, v, ch),
5712 ] {
5713 let got: Vec<u8> = got16.iter().map(|&s| s as u8).collect();
5714 assert_eq!(got.len(), want.len(), "frame {i} {name} plane size");
5715 if let Some(at) = got.iter().zip(want.iter()).position(|(x, y)| x != y) {
5716 panic!(
5717 "frame {i}: {name} differs first at ({}, {}): ours {} vs ffmpeg {}",
5718 at % w,
5719 at / w,
5720 got[at],
5721 want[at],
5722 );
5723 }
5724 }
5725 }
5726 } else {
5727 eprintln!("SKIP the ffmpeg half: no ffmpeg");
5728 }
5729 }
5730
5731 /// Every SHIPPED SPEED PRESET codes a stream both decoders reconstruct
5732 /// sample-exact -- ours and ffmpeg's -- and codes a DIFFERENT stream from
5733 /// its neighbour (a preset that changes no byte is a preset that buys no
5734 /// wall: class `gate-blind-to-feature`). Preset 0's bytes are the
5735 /// full-search ones, which is the cheap in-suite statement of the byte
5736 /// pins' rule.
5737 ///
5738 /// Ignored by default because the preset is PROCESS-GLOBAL
5739 /// ([`crate::speed`]): flipping it while the suite's other tests encode
5740 /// in parallel would move their bytes under them. Run it on its own:
5741 /// `cargo test -p ec-av1 --release -- --ignored every_speed_preset`.
5742 #[test]
5743 #[ignore = "sets the process-global speed preset: run it alone"]
5744 fn every_speed_preset_decodes_sample_exact_through_both_decoders() {
5745 let _knobs = crate::speed::knob_write();
5746 let _gate_lock = crate::stream::tests::lock_gate_counters();
5747 let (width, height) = (640usize, 384usize);
5748 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
5749 let mut sizes: Vec<(u8, usize)> = Vec::new();
5750 for speed in [0u8, 3, 6, 10] {
5751 let config = EncoderConfig {
5752 width,
5753 height,
5754 base_q_idx: 120,
5755 gop: 4,
5756 colour: Colour::Bt709Limited,
5757 tile_cols_log2: 1,
5758 tile_rows_log2: 0,
5759 };
5760 let mut enc = Av1Encoder::with_speed(config, speed).unwrap();
5761 let mut stream = Vec::new();
5762 for packet in encode_all(&mut enc, &sources) {
5763 stream.extend_from_slice(&packet.data);
5764 }
5765 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
5766 assert_eq!(
5767 ours.len(),
5768 sources.len(),
5769 "speed {speed}: our decoder's frames"
5770 );
5771 if have_ffmpeg() {
5772 let theirs = ffmpeg_decode_luma(&stream, width, height);
5773 assert_eq!(
5774 theirs.len(),
5775 sources.len(),
5776 "speed {speed}: ffmpeg's frames"
5777 );
5778 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
5779 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
5780 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
5781 panic!(
5782 "speed {speed} frame {i}: luma differs first at ({}, {}): \
5783 ours {} vs ffmpeg {}",
5784 at % width,
5785 at / width,
5786 got[at],
5787 b[at],
5788 );
5789 }
5790 assert_eq!(
5791 got.len(),
5792 b.len(),
5793 "speed {speed} frame {i}: luma is {} samples, ffmpeg's is {}",
5794 got.len(),
5795 b.len()
5796 );
5797 }
5798 } else {
5799 eprintln!("SKIP the ffmpeg half of speed {speed}: no ffmpeg");
5800 }
5801 eprintln!(
5802 "speed {speed}: {} bytes [{}]",
5803 stream.len(),
5804 crate::speed::levers(speed).join(", ")
5805 );
5806 sizes.push((speed, stream.len()));
5807 }
5808 crate::speed::set_speed(0);
5809 for w in sizes.windows(2) {
5810 assert_ne!(
5811 w[0].1, w[1].1,
5812 "speed {} and {} coded the same bytes: the preset changed no decision",
5813 w[0].0, w[1].0
5814 );
5815 }
5816 }
5817
5818 /// What tiles and tile threads are worth at the size the editor exports
5819 /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall
5820 /// per cell. Ignored by default (minutes).
5821 #[test]
5822 #[ignore = "wall table, 16 cells x 2 passes at 1080p: 27 min measured; needs a host with >=8 cores"]
5823 fn tile_wall_table_at_1080p() {
5824 let _knobs = crate::speed::knob_write();
5825 let _gate_lock = crate::stream::tests::lock_gate_counters();
5826 let (width, height) = (1920usize, 1080usize);
5827 let Some(sources) = h264_clip_frames("tile_wall_table_at_1080p", width, height, 8) else {
5828 return;
5829 };
5830 let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)];
5831 let threadings = [1usize, 2, 4, 8];
5832 let mut table: Vec<(String, usize, f64, usize)> = Vec::new();
5833 for pass in 0..2 {
5834 for &(cols_log2, rows_log2) in &layouts {
5835 for &threads in &threadings {
5836 crate::par::set_tile_threads(threads);
5837 let config = EncoderConfig {
5838 width,
5839 height,
5840 base_q_idx: 120,
5841 gop: 8,
5842 colour: Colour::Bt709Limited,
5843 tile_cols_log2: cols_log2,
5844 tile_rows_log2: rows_log2,
5845 };
5846 let mut enc = Av1Encoder::new(config).unwrap();
5847 let start = std::time::Instant::now();
5848 let mut bytes = 0usize;
5849 for packet in encode_all(&mut enc, &sources) {
5850 bytes += packet.data.len();
5851 }
5852 let wall = start.elapsed().as_secs_f64();
5853 let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2);
5854 match table.iter_mut().find(|r| r.0 == name && r.1 == threads) {
5855 Some(row) => row.2 = row.2.min(wall),
5856 None => table.push((name, threads, wall, bytes)),
5857 }
5858 let _ = pass;
5859 }
5860 }
5861 }
5862 crate::par::set_tile_threads(1);
5863 eprintln!("| tiles | threads | wall (s, best of 2) | bytes |");
5864 for (name, threads, wall, bytes) in &table {
5865 eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |");
5866 }
5867 }
5868
5869 /// The tiles of a frame are entropy-independent, so the bytes must not
5870 /// depend on how many workers wrote them: the same stream at one tile
5871 /// thread and at four, per layout.
5872 #[test]
5873 fn tile_bytes_do_not_depend_on_the_thread_count() {
5874 let _knobs = crate::speed::knob_write();
5875 let _gate_lock = crate::stream::tests::lock_gate_counters();
5876 let (width, height) = (320usize, 192usize);
5877 let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect();
5878 let coded = |threads: usize, cols_log2: u32, rows_log2: u32| {
5879 crate::par::set_tile_threads(threads);
5880 let config = EncoderConfig {
5881 width,
5882 height,
5883 base_q_idx: 120,
5884 gop: 3,
5885 colour: Colour::Bt709Limited,
5886 tile_cols_log2: cols_log2,
5887 tile_rows_log2: rows_log2,
5888 };
5889 let mut enc = Av1Encoder::new(config).unwrap();
5890 let mut stream = Vec::new();
5891 for packet in encode_all(&mut enc, &sources) {
5892 stream.extend_from_slice(&packet.data);
5893 }
5894 stream
5895 };
5896 for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] {
5897 let one = coded(1, cols_log2, rows_log2);
5898 let four = coded(4, cols_log2, rows_log2);
5899 assert_eq!(
5900 one,
5901 four,
5902 "{}x{} tiles: {} bytes at one thread, {} at four",
5903 1 << cols_log2,
5904 1 << rows_log2,
5905 one.len(),
5906 four.len()
5907 );
5908 }
5909 crate::par::set_tile_threads(1);
5910 }
5911
5912 /// What the per-tile search (lane-av1tsearch) is worth in wall and in
5913 /// frames per second at the editor's own export sizes: every tile layout
5914 /// crossed with every tile-thread count, plus librav1e at the matching
5915 /// `tile_cols`/`tile_rows`/`threads` as the reference point. Two passes
5916 /// over the whole table (A,B,A,B... rather than AA,BB) with the best of
5917 /// the two kept, so a thermal drift cannot order the rows.
5918 ///
5919 /// Measurement, not a pass/fail gate: it asserts only that every cell
5920 /// produced a stream.
5921 #[test]
5922 // MEASURED 1243 s in release on a 12-core workstation. A 4-core server
5923 // cannot finish it at all: the same run TIMED OUT at 2400 s there
5924 // (12 frames x 2 passes x 12 cells), so the 8- and 12-thread rows are
5925 // only meaningful on a host with the cores to run them. Do not schedule
5926 // it on a 4-core fleet box.
5927 #[ignore = "wall measurement: 20 min at 1080p and it TIMES OUT on a 4-core host -- run it on >=8 cores"]
5928 fn tile_search_wall_1080p() {
5929 let _knobs = crate::speed::knob_write();
5930 tile_search_wall(
5931 1920,
5932 1080,
5933 12,
5934 &[(0, 0), (1, 0), (1, 1), (2, 1)],
5935 &[1, 2, 4, 8],
5936 );
5937 }
5938
5939 /// The same table at the 4K frame size the editor exports (3840x1608),
5940 /// at the two layouts with enough tiles to fill this box.
5941 #[test]
5942 #[ignore = "wall measurement: 12 min at 4K (732 s measured); run it with --ignored --nocapture"]
5943 fn tile_search_wall_4k() {
5944 let _knobs = crate::speed::knob_write();
5945 tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]);
5946 }
5947
5948 /// lane-av1fpar: the frame-level FILTER stage is banded across the same
5949 /// workers the tile search uses (`par::override_filter_threads`), so the
5950 /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in
5951 /// pieces. Every piece is a disjoint band of the same integers, so the
5952 /// stream must not move -- at a size that crops and is several superblock
5953 /// rows tall, which is what makes the bands non-trivial.
5954 #[test]
5955 fn filter_stage_bytes_do_not_depend_on_the_thread_count() {
5956 let _knobs = crate::speed::knob_write();
5957 let _gate_lock = crate::stream::tests::lock_gate_counters();
5958 let (width, height) = (384usize, 288usize);
5959 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
5960 let coded = |threads: usize| {
5961 crate::par::set_tile_threads(threads);
5962 let config = EncoderConfig {
5963 width,
5964 height,
5965 base_q_idx: 120,
5966 gop: 2,
5967 colour: Colour::Bt709Limited,
5968 tile_cols_log2: 0,
5969 tile_rows_log2: 0,
5970 };
5971 let mut enc = Av1Encoder::new(config).unwrap();
5972 let mut stream = Vec::new();
5973 for packet in encode_all(&mut enc, &sources) {
5974 stream.extend_from_slice(&packet.data);
5975 }
5976 stream
5977 };
5978 // One tile, so only the filter stage can differ between these.
5979 let one = coded(1);
5980 for threads in [2usize, 4, 8] {
5981 assert_eq!(
5982 one,
5983 coded(threads),
5984 "the filter stage moved at {threads} threads"
5985 );
5986 }
5987 crate::par::set_tile_threads(1);
5988 }
5989
5990 /// lane-av1fpar: the filter search scores its ~30 candidates by replaying
5991 /// the loop filters on one captured reconstruction instead of decoding
5992 /// the coded tile again per candidate. The replay must be that decode,
5993 /// byte for byte -- including at a size that CROPS (1080 and 1608 both
5994 /// pad to a superblock row, i.e. every export size the editor uses),
5995 /// which is the arm this lane opened.
5996 #[test]
5997 fn filter_replay_codes_the_same_stream_as_a_full_decode() {
5998 let _knobs = crate::speed::knob_read();
5999 let _gate_lock = crate::stream::tests::lock_gate_counters();
6000 let run = |width: usize, height: usize, off: bool| {
6001 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
6002 crate::decode::set_filter_replay_disabled(off);
6003 let config = EncoderConfig {
6004 width,
6005 height,
6006 base_q_idx: 120,
6007 gop: 2,
6008 colour: Colour::Bt709Limited,
6009 tile_cols_log2: 0,
6010 tile_rows_log2: 0,
6011 };
6012 let mut enc = Av1Encoder::new(config).unwrap();
6013 let mut stream = Vec::new();
6014 for packet in encode_all(&mut enc, &sources) {
6015 stream.extend_from_slice(&packet.data);
6016 }
6017 crate::decode::set_filter_replay_disabled(false);
6018 stream
6019 };
6020 // 320x160 crops (the coding surface is 320x192, one superblock row
6021 // taller); 320x192 is a whole number of superblocks, the shape the
6022 // replay already covered.
6023 for (width, height) in [(320usize, 160usize), (320, 192)] {
6024 let replayed = run(width, height, false);
6025 let decoded = run(width, height, true);
6026 assert_eq!(
6027 replayed,
6028 decoded,
6029 "{width}x{height}: the filter replay is not the decode it stands in for \
6030 ({} bytes replayed, {} decoded)",
6031 replayed.len(),
6032 decoded.len(),
6033 );
6034 }
6035 }
6036
6037 /// lane-av1cap: the filter stage's FINAL replay -- the one that replaced
6038 /// the capture decode -- against that decode. `set_verify_final_replay`
6039 /// makes `encode::pick_and_apply_filters` run both on every frame and
6040 /// assert, per frame, that the spliced picture and the two filter stages
6041 /// the loop-restoration search reads are bit-identical.
6042 #[test]
6043 fn filter_replay_final_matches_the_capture_decode() {
6044 let _knobs = crate::speed::knob_read();
6045 let _gate_lock = crate::stream::tests::lock_gate_counters();
6046 let run = |sources: &[Picture], width: usize, height: usize, tiles: (u32, u32)| {
6047 let config = EncoderConfig {
6048 width,
6049 height,
6050 base_q_idx: 120,
6051 gop: 2,
6052 colour: Colour::Bt709Limited,
6053 tile_cols_log2: tiles.0,
6054 tile_rows_log2: tiles.1,
6055 };
6056 let mut enc = Av1Encoder::new(config).unwrap();
6057 for packet in encode_all(&mut enc, sources) {
6058 assert!(!packet.data.is_empty());
6059 }
6060 };
6061 crate::decode::set_verify_final_replay(true);
6062 // 320x160 crops (its coding surface is one superblock row taller);
6063 // 320x192 is a whole number of superblocks.
6064 for (width, height) in [(320usize, 160usize), (320, 192)] {
6065 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
6066 run(&sources, width, height, (0, 0));
6067 }
6068 // Real gate content, where the CDEF preset search actually chooses
6069 // `bits > 0` and the tile is re-coded, one tile and four.
6070 if let Some(sources) = h264_clip_frames("the gate-clip arm", 640, 384, 3) {
6071 run(&sources, 640, 384, (0, 0));
6072 run(&sources, 640, 384, (1, 1));
6073 }
6074 crate::decode::set_verify_final_replay(false);
6075 }
6076
6077 /// lane-av1fpar: where a frame's wall actually goes, stage by stage --
6078 /// the per-tile search, the tile write, the frame-level filter search
6079 /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture
6080 /// decode the loop-restoration search rides on, and that search itself.
6081 /// Measurement, not a pass/fail gate.
6082 #[test]
6083 #[ignore = "wall measurement: 36 s at 1080p; run it with --ignored --nocapture"]
6084 fn filter_stage_wall_1080p() {
6085 let _knobs = crate::speed::knob_write();
6086 filter_stage_wall(1920, 1080, 8, (2, 1), &[8]);
6087 }
6088
6089 #[test]
6090 #[ignore = "wall measurement: 62 s at 4K; run it with --ignored --nocapture"]
6091 fn filter_stage_wall_4k() {
6092 let _knobs = crate::speed::knob_write();
6093 filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]);
6094 }
6095
6096 /// The same breakdown at the real films' own crop size. With
6097 /// `EC_AV1_WALL_CLIP` pointing at a film window this is the film row; with
6098 /// it unset it is the colour-bar fixture at the same size, which is what
6099 /// makes the pair a comparison rather than a number.
6100 #[test]
6101 // MEASURED 16 s WITHOUT `EC_AV1_WALL_CLIP`, and what it measures then is
6102 // the COLOUR-BAR fixture, not a film: `h264_clip_frames` falls back to
6103 // `fixtures/video/h264-1080p-23.976-8bit.mp4` when the var is unset. A
6104 // reader who takes the name for the content reads a bars number as a
6105 // film number, so the precondition belongs in the reason.
6106 #[ignore = "wall measurement: 16 s; MEASURES THE BARS FIXTURE unless EC_AV1_WALL_CLIP names a real film window"]
6107 fn filter_stage_wall_film() {
6108 let _knobs = crate::speed::knob_write();
6109 filter_stage_wall(1920, 768, 4, (2, 1), &[8]);
6110 }
6111
6112 fn filter_stage_wall(
6113 width: usize,
6114 height: usize,
6115 frames: usize,
6116 (cols_log2, rows_log2): (u32, u32),
6117 threads: &[usize],
6118 ) {
6119 let _gate_lock = crate::stream::tests::lock_gate_counters();
6120 let Some(sources) = h264_clip_frames("the filter-stage breakdown", width, height, frames)
6121 else {
6122 return;
6123 };
6124 crate::par::set_stage_times(true);
6125 for &t in threads {
6126 crate::par::set_tile_threads(t);
6127 let config = EncoderConfig {
6128 width,
6129 height,
6130 base_q_idx: 120,
6131 gop: frames,
6132 colour: Colour::Bt709Limited,
6133 tile_cols_log2: cols_log2,
6134 tile_rows_log2: rows_log2,
6135 };
6136 let mut enc = Av1Encoder::new(config).unwrap();
6137 let _ = crate::par::take_stage_ns();
6138 let start = std::time::Instant::now();
6139 for packet in encode_all(&mut enc, &sources) {
6140 assert!(!packet.data.is_empty());
6141 }
6142 let wall = start.elapsed().as_secs_f64();
6143 let ns = crate::par::take_stage_ns();
6144 let ms = |i: usize| ns[i] as f64 / 1e6;
6145 eprintln!(
6146 "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \
6147 {wall:.2}s wall, {:.2} fps",
6148 1 << cols_log2,
6149 1 << rows_log2,
6150 frames as f64 / wall,
6151 );
6152 eprintln!("| stage | ms | ms/frame | % of wall |");
6153 for (i, name) in crate::par::STAGES.iter().enumerate() {
6154 eprintln!(
6155 "| {name} | {:.0} | {:.1} | {:.1}% |",
6156 ms(i),
6157 ms(i) / frames as f64,
6158 100.0 * ms(i) / (wall * 1e3),
6159 );
6160 }
6161 // Top-level stages only (the deblock/CDEF/SSE rows are inside
6162 // the filter-search total); the rest is per-frame setup, the
6163 // source conversion and the splice.
6164 let top: f64 = [
6165 crate::par::S_TILE_SEARCH,
6166 crate::par::S_TILE_WRITE,
6167 crate::par::S_FILTER,
6168 crate::par::S_CAPTURE,
6169 crate::par::S_LR,
6170 ]
6171 .iter()
6172 .map(|&i| ms(i))
6173 .sum();
6174 eprintln!(
6175 "accounted {:.1}% of wall; outside the tile search {:.1}%",
6176 100.0 * top / (wall * 1e3),
6177 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)),
6178 );
6179 }
6180 crate::par::set_stage_times(false);
6181 crate::par::set_tile_threads(1);
6182 }
6183
6184 fn tile_search_wall(
6185 width: usize,
6186 height: usize,
6187 frames: usize,
6188 layouts: &[(u32, u32)],
6189 threads: &[usize],
6190 ) {
6191 let _gate_lock = crate::stream::tests::lock_gate_counters();
6192 let Some(sources) = h264_clip_frames("the tile-search wall table", width, height, frames)
6193 else {
6194 return;
6195 };
6196 let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) {
6197 crate::par::set_tile_threads(t);
6198 let config = EncoderConfig {
6199 width,
6200 height,
6201 base_q_idx: 120,
6202 gop: frames,
6203 colour: Colour::Bt709Limited,
6204 tile_cols_log2: cols_log2,
6205 tile_rows_log2: rows_log2,
6206 };
6207 let mut enc = Av1Encoder::new(config).unwrap();
6208 let start = std::time::Instant::now();
6209 let mut bytes = 0usize;
6210 for packet in encode_all(&mut enc, &sources) {
6211 bytes += packet.data.len();
6212 }
6213 (start.elapsed(), bytes)
6214 };
6215 let cells: Vec<((u32, u32), usize)> = layouts
6216 .iter()
6217 .flat_map(|&l| threads.iter().map(move |&t| (l, t)))
6218 .collect();
6219 let mut best: Vec<Option<(std::time::Duration, usize)>> = vec![None; cells.len()];
6220 for _pass in 0..2 {
6221 for (i, &((c, r), t)) in cells.iter().enumerate() {
6222 let got = run(c, r, t);
6223 assert!(
6224 got.1 > 0,
6225 "{}x{} tiles at {t} threads: empty stream",
6226 1 << c,
6227 1 << r
6228 );
6229 if best[i].is_none_or(|(w, _)| got.0 < w) {
6230 best[i] = Some(got);
6231 }
6232 }
6233 }
6234 crate::par::set_tile_threads(1);
6235 eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes");
6236 eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |");
6237 let base = best[0].expect("the first cell ran").0.as_secs_f64();
6238 for (i, &((c, r), t)) in cells.iter().enumerate() {
6239 let (wall, bytes) = best[i].expect("every cell ran");
6240 let secs = wall.as_secs_f64();
6241 eprintln!(
6242 "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |",
6243 1 << c,
6244 1 << r,
6245 1 << (c + r),
6246 frames as f64 / secs,
6247 base / secs,
6248 );
6249 }
6250 // Parallel efficiency per layout: what the extra threads actually
6251 // took off that layout's own single-threaded wall, and so what share
6252 // of the added cores sat idle.
6253 for &(c, r) in layouts {
6254 let one = cells
6255 .iter()
6256 .position(|&(l, t)| l == (c, r) && t == threads[0])
6257 .map(|i| best[i].expect("cell").0.as_secs_f64());
6258 let Some(one) = one else { continue };
6259 for &t in &threads[1..] {
6260 let i = cells
6261 .iter()
6262 .position(|&(l, tt)| l == (c, r) && tt == t)
6263 .expect("cell");
6264 let secs = best[i].expect("cell").0.as_secs_f64();
6265 let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64;
6266 let speedup = one / secs;
6267 eprintln!(
6268 "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \
6269 idle share {:.0}%",
6270 1 << c,
6271 1 << r,
6272 threads[0],
6273 100.0 * (1.0 - speedup / workers).max(0.0),
6274 );
6275 }
6276 }
6277 rav1e_wall_reference(width, height, frames, layouts, threads);
6278 }
6279
6280 /// librav1e at the same sizes, layouts and thread counts, through ffmpeg
6281 /// -- the reference the wall table is read against.
6282 fn rav1e_wall_reference(
6283 width: usize,
6284 height: usize,
6285 frames: usize,
6286 layouts: &[(u32, u32)],
6287 threads: &[usize],
6288 ) {
6289 let listed = Command::new("ffmpeg")
6290 .args(["-hide_banner", "-encoders"])
6291 .output();
6292 let has_rav1e = listed
6293 .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e"))
6294 .unwrap_or(false);
6295 // lane-av1clipprobe: this was `!has_rav1e || !clip.exists()` behind ONE
6296 // line, which is how the clip's absence hid inside a tool-absence
6297 // message and could not fail under any require env. The two causes are
6298 // now separate, and only the clip goes through the fixture probe, so
6299 // either way this helper prints exactly ONE line.
6300 if !has_rav1e {
6301 eprintln!("SKIP the rav1e reference: ffmpeg has no librav1e encoder");
6302 return;
6303 }
6304 let Some(clip) = crate::library_fixture::require(
6305 "video/h264-1080p-23.976-8bit.mp4",
6306 "the rav1e reference",
6307 ) else {
6308 return;
6309 };
6310 eprintln!("| rav1e layout | threads | wall | fps | bytes |");
6311 for &(c, r) in layouts {
6312 for &t in threads {
6313 let out =
6314 std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id()));
6315 let params = format!(
6316 "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}",
6317 1 << c,
6318 1 << r
6319 );
6320 let start = std::time::Instant::now();
6321 let status = Command::new("ffmpeg")
6322 .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()])
6323 .args(["-frames:v", &frames.to_string()])
6324 .args(["-vf", &format!("scale={width}:{height}")])
6325 .args(["-c:v", "librav1e", "-rav1e-params", &params])
6326 .arg(out.to_str().unwrap())
6327 .output()
6328 .expect("ffmpeg failed to run");
6329 let secs = start.elapsed().as_secs_f64();
6330 if !status.status.success() {
6331 eprintln!(
6332 "| {}x{} | {t} | FAILED: {} |",
6333 1 << c,
6334 1 << r,
6335 String::from_utf8_lossy(&status.stderr)
6336 .lines()
6337 .last()
6338 .unwrap_or("")
6339 );
6340 continue;
6341 }
6342 let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
6343 let _ = std::fs::remove_file(&out);
6344 eprintln!(
6345 "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |",
6346 1 << c,
6347 1 << r,
6348 frames as f64 / secs
6349 );
6350 }
6351 }
6352 }
6353
6354 /// The same round trip at a real 1920x1080 crop of the gate's own clip
6355 /// -- the size the editor's export actually runs at, where a tile grid
6356 /// is worth having.
6357 ///
6358 /// UN-IGNORED by lane-av1probes: it was `#[ignore]`d only for its wall
6359 /// ("1080p encode: minutes"), and it is the only 1080p arm in the ignored
6360 /// set that actually ASSERTS. Measured 30.6 s in release on the
6361 /// workstation (12 cores) and 64 s on a 4-core server, so it is affordable
6362 /// in the suite. Evidence for the un-ignore: the three tile grids 2x1,
6363 /// 2x2 and 4x2 each decode sample-exact through BOTH our decoder and
6364 /// ffmpeg (84488 / 84208 / 84685 bytes), and the check is a per-frame
6365 /// first-differing-luma-sample comparison, not a length or non-empty
6366 /// smoke.
6367 ///
6368 /// The two skippable halves both route through the crate's EXISTING
6369 /// presence probes, not a new shape: `h264_clip_frames` (which itself asks
6370 /// `have_ffmpeg()` and `library_fixture::require_at`) and `have_ffmpeg()`
6371 /// for the ffmpeg arm. No bare presence check was added.
6372 ///
6373 /// lane-av1clipprobe: with the root `fixtures/` absent this gate printed
6374 /// `SKIP the 1080p tile round trip: no fixture` and libtest reported `ok`
6375 /// — a 1080p gate that asserts nothing on every linked worktree, and no
6376 /// env that made it RED. `library_fixture::require_at` now fails under
6377 /// `EC_REQUIRE_FIXTURES` / `EC_AV1_REQUIRE_FFMPEG` / `EC_AV1_REQUIRE_AOMENC`
6378 /// and otherwise prints exactly ONE line naming the resolved path, and the
6379 /// path it resolves honours `EC_FIXTURES` — the root
6380 /// `scripts/verify-fixture-library.sh` validates — so the preflight's
6381 /// verdict and these bytes cannot be different trees again.
6382 #[test]
6383 fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() {
6384 let _knobs = crate::speed::knob_read();
6385 let (width, height) = (1920usize, 1080usize);
6386 let Some(sources) = h264_clip_frames(
6387 "a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders",
6388 width,
6389 height,
6390 3,
6391 ) else {
6392 return;
6393 };
6394 for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] {
6395 let config = EncoderConfig {
6396 width,
6397 height,
6398 base_q_idx: 120,
6399 gop: 3,
6400 colour: Colour::Bt709Limited,
6401 tile_cols_log2: cols_log2,
6402 tile_rows_log2: rows_log2,
6403 };
6404 let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
6405 let mut enc = Av1Encoder::new(config).unwrap();
6406 let mut stream = Vec::new();
6407 for packet in encode_all(&mut enc, &sources) {
6408 stream.extend_from_slice(&packet.data);
6409 }
6410 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
6411 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
6412 if !have_ffmpeg() {
6413 eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg");
6414 continue;
6415 }
6416 let theirs = ffmpeg_decode_luma(&stream, width, height);
6417 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
6418 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
6419 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
6420 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
6421 panic!(
6422 "1080p {layout} frame {i}: luma differs first at ({}, {})",
6423 at % width,
6424 at / width
6425 );
6426 }
6427 assert_eq!(
6428 got.len(),
6429 b.len(),
6430 "1080p {layout} frame {i}: luma is {} samples, ffmpeg's is {}",
6431 got.len(),
6432 b.len()
6433 );
6434 }
6435 eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len());
6436 }
6437 }
6438
6439 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
6440 /// produces a smaller stream or a worse mean PSNR than a lower one, on
6441 /// the same real clip.
6442 #[test]
6443 fn quality_target_is_monotone_in_bytes_and_psnr() {
6444 let _knobs = crate::speed::knob_read();
6445 if !have_ffmpeg() {
6446 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg");
6447 return;
6448 }
6449 let (width, height) = (640, 384);
6450 let Some(pictures) = h264_clip_frames(
6451 "quality_target_is_monotone_in_bytes_and_psnr",
6452 width,
6453 height,
6454 8,
6455 ) else {
6456 return;
6457 };
6458 let mut prev_bytes = 0usize;
6459 let mut prev_psnr = 0.0f64;
6460 for quality in [20u8, 50, 80] {
6461 let config = EncoderConfig {
6462 width,
6463 height,
6464 base_q_idx: 100,
6465 gop: 8,
6466 colour: Colour::Bt709Limited,
6467 tile_cols_log2: 0,
6468 tile_rows_log2: 0,
6469 };
6470 let mut enc =
6471 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
6472 let mut stream = Vec::new();
6473 let mut total_bytes = 0usize;
6474 for packet in encode_all(&mut enc, &pictures) {
6475 total_bytes += packet.data.len();
6476 stream.extend_from_slice(&packet.data);
6477 }
6478 let decoded = ffmpeg_decode_luma(&stream, width, height);
6479 assert_eq!(
6480 decoded.len(),
6481 pictures.len(),
6482 "quality {quality}: dav1d frame count"
6483 );
6484 let mean_psnr: f64 = decoded
6485 .iter()
6486 .zip(&pictures)
6487 .map(|(d, p)| {
6488 let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect();
6489 psnr(&d16, &p.y)
6490 })
6491 .sum::<f64>()
6492 / decoded.len() as f64;
6493 assert!(
6494 total_bytes >= prev_bytes,
6495 "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}"
6496 );
6497 assert!(
6498 mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours
6499 "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB"
6500 );
6501 prev_bytes = total_bytes;
6502 prev_psnr = mean_psnr;
6503 }
6504 }
6505}