forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

mod.rs2568 lines, 118.9 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 if config.base_q_idx == 0 {
1535 return Err(Error::unsupported(
1536 "AV1 encode",
1537 "base_q_idx 0 is lossless, which this encoder does not code",
1538 ));
1539 }
1540 // Validate the geometry the same way the picture-level entry points
1541 // do, before the first `encode()` call rather than only surfacing it
1542 // then.
1543 Picture::grey(config.width, config.height).check_even()?;
1544 // A tile is a whole number of superblocks, so a frame cannot carry
1545 // more tile columns (rows) than it has 64x64 superblocks across
1546 // (down) -- the header's own `max_log2_tile_cols` bound (spec
1547 // 5.9.15), refused here rather than at the first `encode()` call.
1548 let sb = if crate::encode::sb128_on() { 128 } else { 64 };
1549 let sb_cols = config.width.div_ceil(sb) as u32;
1550 let sb_rows = config.height.div_ceil(sb) as u32;
1551 let tiles = |log2: u32| 1u32.checked_shl(log2).unwrap_or(u32::MAX);
1552 let max_log2 = |n: u32| n.min(64).next_power_of_two().trailing_zeros();
1553 if config.tile_cols_log2 > max_log2(sb_cols) || config.tile_rows_log2 > max_log2(sb_rows) {
1554 return Err(Error::unsupported(
1555 "AV1 encode",
1556 format!(
1557 "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has",
1558 tiles(config.tile_cols_log2),
1559 tiles(config.tile_rows_log2)
1560 ),
1561 ));
1562 }
1563 Ok(Self {
1564 carried_cdfs: None,
1565 golden: None,
1566 prev2: None,
1567 color_config: config.colour.color_config(),
1568 config,
1569 reference: None,
1570 next_index: 0,
1571 rate_loop: None,
1572 fctx: crate::decode::FrameCtx::for_encoder(),
1573 pyramid: None,
1574 dpb: [const { None }; 8],
1575 pending: Vec::new(),
1576 ready: Vec::new(),
1577 held: std::collections::VecDeque::new(),
1578 anchor: 0,
1579 leaf_hist: Vec::new(),
1580 next_dts: 0,
1581 collected: None,
1582 })
1583 }
1584
1585 /// [`Av1Encoder::new`] in pyramid mode: pictures are coded out of display
1586 /// order, so a call to [`Av1Encoder::encode_frames`] returns zero, one or
1587 /// several packets and [`Av1Encoder::flush`] drains whatever is still
1588 /// held at the end of the stream. [`Av1Encoder::encode`]'s one-in-one-out
1589 /// contract cannot hold here and it returns an error instead; a caller
1590 /// that wants the old shape simply does not call this constructor.
1591 ///
1592 /// # Errors
1593 /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be
1594 /// left between the anchor and the hidden frame). A `mini_gop` above
1595 /// `config.gop` is clamped to the run before the next key frame.
1596 pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> {
1597 if pyramid.mini_gop < 2 {
1598 return Err(Error::unsupported(
1599 "AV1 encode",
1600 "a pyramid mini-GOP is at least 2 pictures",
1601 ));
1602 }
1603 let mut encoder = Self::new(config)?;
1604 encoder.pyramid = Some(pyramid);
1605 Ok(encoder)
1606 }
1607
1608 /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it,
1609 /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of
1610 /// `config.base_q_idx` being used as-is.
1611 ///
1612 /// # Errors
1613 /// Same as [`Av1Encoder::new`].
1614 pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> {
1615 let rate_loop = rate.into_loop(&mut config, None);
1616 let mut encoder = Self::new(config)?;
1617 encoder.rate_loop = rate_loop;
1618 Ok(encoder)
1619 }
1620
1621 /// [`Av1Encoder::with_pyramid`] and [`Av1Encoder::with_rate_target`] at
1622 /// once: the rate loop then keeps a separate quantizer per pyramid level,
1623 /// predicting each frame's size from the previous frame of its OWN level
1624 /// (a leaf and a hidden `ALTREF` differ by several times in size, so one
1625 /// shared predictor would swing the quantizer every frame).
1626 ///
1627 /// # Errors
1628 /// As both.
1629 pub fn with_pyramid_and_rate_target(
1630 mut config: EncoderConfig,
1631 pyramid: Pyramid,
1632 rate: RateTarget,
1633 ) -> Result<Self> {
1634 let rate_loop = rate.into_loop(&mut config, Some(pyramid));
1635 let mut encoder = Self::with_pyramid(config, pyramid)?;
1636 encoder.rate_loop = rate_loop;
1637 Ok(encoder)
1638 }
1639
1640 /// The [`Pyramid`] this stream is actually coding under: what
1641 /// [`Av1Encoder::with_pyramid`] asked for, or `None` once the content gate
1642 /// in [`Av1Encoder::encode_frames`] has dropped a screen-content stream
1643 /// back to the flat path. Meaningful after the first picture has been
1644 /// handed in.
1645 #[must_use]
1646 pub fn pyramid(&self) -> Option<Pyramid> {
1647 self.pyramid
1648 }
1649
1650 /// The coded (padded-to-64) frame size every picture in this stream is
1651 /// coded at — what a decoder allocates and what `ffprobe` reports.
1652 #[must_use]
1653 pub fn coded_size(&self) -> (usize, usize) {
1654 (
1655 self.config.width.next_multiple_of(SUPERBLOCK),
1656 self.config.height.next_multiple_of(SUPERBLOCK),
1657 )
1658 }
1659
1660 /// The display (render) size every frame header signals — [`EncoderConfig`]'s
1661 /// own `width`/`height`, always, whatever the coded size pads it to.
1662 #[must_use]
1663 pub fn display_size(&self) -> (usize, usize) {
1664 (self.config.width, self.config.height)
1665 }
1666
1667 /// Takes one picture and returns the PREVIOUS picture's packet, key or
1668 /// inter by this stream's `gop` cadence — the facade's one frame of
1669 /// latency (the picture just handed in is what the previous one is coded
1670 /// against as its lookahead). The FIRST call has no previous picture and
1671 /// returns a packet with an EMPTY `data` (its other fields are
1672 /// placeholders; test `data.is_empty()`), and the last picture's packet
1673 /// comes out of [`Av1Encoder::flush`] — so a caller that concatenates
1674 /// `data` in call order still gets the whole stream, provided it flushes
1675 /// at the end.
1676 ///
1677 /// # Errors
1678 /// Returns an error when `picture`'s size does not match
1679 /// [`EncoderConfig::width`]/[`EncoderConfig::height`], when the encoder
1680 /// was built by [`Av1Encoder::with_pyramid`] (which reorders pictures, so
1681 /// one call cannot return one packet), or under the same conditions
1682 /// [`crate::encode::encode_key_frame`]/[`crate::encode::encode_sequence`]
1683 /// do.
1684 pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {
1685 if self.pyramid.is_some() {
1686 return Err(Error::unsupported(
1687 "AV1 encode",
1688 "a pyramid stream reorders pictures -- use encode_frames()/flush()",
1689 ));
1690 }
1691 let mut packets = self.encode_frames(picture)?;
1692 Ok(packets.pop().unwrap_or(Packet {
1693 data: Vec::new(),
1694 key: false,
1695 order: 0,
1696 dts: 0,
1697 level: Level::Leaf,
1698 }))
1699 }
1700
1701 /// Takes one picture and returns every packet it completed, in coding
1702 /// order. Without a [`Pyramid`] that is one packet — the PREVIOUS
1703 /// picture's, since this one is its lookahead — and none at all on the
1704 /// first call; with one it is
1705 /// empty for most pictures and a whole mini-GOP's worth (the hidden
1706 /// frame, its leaves and the `show_existing_frame` that re-outputs it)
1707 /// for the picture that closes a group.
1708 ///
1709 /// # Errors
1710 /// As [`Av1Encoder::encode`], minus the pyramid refusal.
1711 pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {
1712 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
1713 // lane-split: the split census prints on every exit of this call when
1714 // armed, so no `return` path loses it; the counters are cumulative, so
1715 // the last table a run prints is that run's total.
1716 struct SplitCensusDump;
1717 impl Drop for SplitCensusDump {
1718 fn drop(&mut self) {
1719 if crate::encode::split_census_on() {
1720 crate::encode::dump_split_census();
1721 }
1722 if crate::encode::newmv_census_on() {
1723 crate::encode::dump_newmv_census();
1724 }
1725 }
1726 }
1727 // `then_some` would CONSTRUCT the guard eagerly and drop it when the
1728 // flag is off, which runs `Drop` -- and printed the census header on
1729 // every unarmed encode. `then` builds it only when armed.
1730 let _census = (crate::encode::split_census_on() || crate::encode::newmv_census_on())
1731 .then(|| SplitCensusDump);
1732 if (picture.width, picture.height) != (self.config.width, self.config.height) {
1733 return Err(Error::unsupported(
1734 "AV1 encode",
1735 format!(
1736 "picture is {}x{}, encoder is {}x{}",
1737 picture.width, picture.height, self.config.width, self.config.height
1738 ),
1739 ));
1740 }
1741 // THE CONTENT GATE (lane-av1pyrgate): the pyramid is for camera
1742 // material. A desktop capture is the one content class every pyramid
1743 // sweep measured WORSE under it, and it is exactly the class the
1744 // screen detector separates (`encode::screen_content`: 0/48 frames on
1745 // both real films, 48/48 on the OBS capture), so a stream whose first
1746 // picture reads as screen content drops back to the flat path and
1747 // codes byte for byte what it coded before the pyramid existed.
1748 //
1749 // Decided ONCE, on the first picture, not per mini-GOP: the flat path
1750 // keeps its references in `reference`/`golden`/`prev2` and the pyramid
1751 // path in `dpb`, so a switch after the first frame would read slots
1752 // the other path never filled. Per-GOP re-decision needs the two
1753 // reference sets kept in step first; the gate's own recipe codes one
1754 // GOP per stream, where the two are the same decision.
1755 if self.pyramid.is_some()
1756 && self.next_index == 0
1757 && crate::encode::picture_is_screen(picture)
1758 {
1759 self.pyramid = None;
1760 }
1761 let Some(pyramid) = self.pyramid else {
1762 // The delay queue: the pictures behind this one are the
1763 // lookahead window the one at its head is coded with, which is
1764 // what makes the facade's bytes identical to
1765 // `encode_sequence`'s (lane-av1facade, lane-av1tpl2).
1766 self.held.push_back(picture.clone());
1767 if self.held.len() < crate::encode::tpl_depth() {
1768 return Ok(Vec::new());
1769 }
1770 let previous = self.held.pop_front().expect("queue is over depth");
1771 let window: Vec<Picture> = self.held.iter().cloned().collect();
1772 return Ok(vec![self.encode_flat(&previous, &window)?]);
1773 };
1774 let order = self.next_index;
1775 self.next_index += 1;
1776 if order.is_multiple_of(self.config.gop as u64) {
1777 // A key frame closes whatever group is open (there is nothing for
1778 // its leaves to point forward at across the boundary) and then
1779 // restarts the pyramid from the key itself.
1780 let mut packets = self.drain_all(Some(picture))?;
1781 packets.push(self.encode_key(order, picture)?);
1782 return Ok(packets);
1783 }
1784 self.pending.push((order, picture.clone()));
1785 // The group closes on the size the LAYOUT gives it (which depends on
1786 // how many pictures are left before the next key frame, so no short
1787 // tail group is left behind), or early when the next picture would be
1788 // a key frame.
1789 let run_start = self.pending[0].0;
1790 let remaining = self.config.gop - (run_start % self.config.gop as u64) as usize;
1791 let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64);
1792 if self.pending.len() >= group_target(remaining, pyramid.mini_gop, absorb_tail())
1793 || next_is_key
1794 {
1795 return self.drain_pending();
1796 }
1797 Ok(Vec::new())
1798 }
1799
1800 /// Codes and returns every picture still held back — the last picture of
1801 /// a flat stream (which has no lookahead and is coded without one), or
1802 /// the tail of a pyramid stream whose last mini-GOP never filled up.
1803 /// Empty once there is nothing held.
1804 ///
1805 /// # Errors
1806 /// As [`Av1Encoder::encode_frames`].
1807 pub fn flush(&mut self) -> Result<Vec<Packet>> {
1808 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
1809 if !self.held.is_empty() {
1810 let mut packets = Vec::with_capacity(self.held.len());
1811 while let Some(previous) = self.held.pop_front() {
1812 let window: Vec<Picture> = self.held.iter().cloned().collect();
1813 packets.push(self.encode_flat(&previous, &window)?);
1814 }
1815 return Ok(packets);
1816 }
1817 self.drain_all(None)
1818 }
1819
1820 /// The flat path: one picture and its lookahead (the next source picture,
1821 /// `None` at the end of the stream) in, one packet out — the same inputs
1822 /// [`crate::encode::encode_sequence`] gives each of its inter frames, so
1823 /// the bytes are identical.
1824 fn encode_flat(&mut self, picture: &Picture, lookahead: &[Picture]) -> Result<Packet> {
1825 let render = (self.config.width, self.config.height);
1826 let padded = picture.padded_to(SUPERBLOCK);
1827 let is_key = self.next_index.is_multiple_of(self.config.gop as u64);
1828 let order = self.next_index;
1829 let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| {
1830 r.q_idx(if is_key { Level::Key } else { Level::Leaf })
1831 });
1832
1833 let encoded: Encoded = if is_key {
1834 encode_key_frame_inner(
1835 &padded,
1836 base_q_idx,
1837 DEADZONE,
1838 &KEY_FRAME_MODES,
1839 split_blocks(),
1840 render,
1841 self.color_config,
1842 &self.fctx,
1843 )?
1844 } else {
1845 let reference = self.reference.as_ref().ok_or_else(|| {
1846 Error::unsupported(
1847 "AV1 encode",
1848 "an inter frame needs a previous reconstruction",
1849 )
1850 })?;
1851 encode_inter_frame(
1852 &padded,
1853 reference,
1854 base_q_idx,
1855 DEADZONE,
1856 order as u32,
1857 // The flat path's own slot plan, in order hints: the key frame
1858 // of the GOP this picture sits in is what `GOLDEN_FRAME`
1859 // names, and every reference but `ALTREF_FRAME` is the frame
1860 // just coded.
1861 crate::encode::flat_order_hints(
1862 order as u32 & 0x7f,
1863 (order - order % self.config.gop as u64) as u32 & 0x7f,
1864 self.prev2.is_some(),
1865 ),
1866 render,
1867 self.carried_cdfs.as_ref().map(|c| &c.0),
1868 self.golden.as_ref(),
1869 self.prev2.as_ref(),
1870 None,
1871 &self.fctx,
1872 None,
1873 &lookahead
1874 .iter()
1875 .map(|n| n.padded_to(SUPERBLOCK))
1876 .collect::<Vec<_>>(),
1877 )?
1878 };
1879
1880 self.carried_cdfs = Some(encoded.next_cdfs.clone());
1881 if is_key {
1882 self.golden = Some(encoded.reconstruction.clone());
1883 self.prev2 = None;
1884 } else {
1885 self.prev2 = self.reference.take();
1886 }
1887 self.reference = Some(encoded.reconstruction.clone());
1888 self.next_index += 1;
1889 let cropped = crop_encoded(&encoded, render.0, render.1);
1890 let level = if is_key { Level::Key } else { Level::Leaf };
1891 if let Some(rate_loop) = self.rate_loop.as_mut() {
1892 // The flat path codes every frame at the slot's own q, no offset.
1893 rate_loop.update(level, 0, i16::from(base_q_idx), cropped.stream.len());
1894 }
1895 Ok(self.packet(cropped.stream, is_key, order, level))
1896 }
1897
1898 /// THE SHARED MINI-GOP DRIVER: codes a whole sequence — one key frame
1899 /// then all inter, which is [`crate::encode::encode_sequence`]'s only
1900 /// shape — through this very facade, under `pyramid`, and hands back what
1901 /// that path returns. The two are byte-identical BY CONSTRUCTION rather
1902 /// than by a mirrored second implementation: there is one reordering,
1903 /// one DPB/slot policy and one set of per-level quantizer offsets, here
1904 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
1905 /// still pins it, now over a pyramid sequence too).
1906 ///
1907 /// The content gate lives in [`Av1Encoder::encode_frames`] and applies
1908 /// unchanged, so a screen-content clip handed in here codes flat.
1909 ///
1910 /// `EncodedSequence::frames` comes back in DISPLAY order, one entry per
1911 /// source picture — the order the flat path's coding order happens to be,
1912 /// and the order every reader of it (the BD gate's sample-exactness
1913 /// assertions against a decoder's output) needs. `stream` stays in coding
1914 /// order, which is the order a decoder reads.
1915 ///
1916 /// # Errors
1917 /// As [`Av1Encoder::encode_frames`].
1918 pub(crate) fn encode_sequence_pyramid(
1919 pictures: &[Picture],
1920 base_q_idx: u8,
1921 pyramid: Pyramid,
1922 tiles: (u32, u32),
1923 ) -> Result<crate::encode::EncodedSequence> {
1924 let first = pictures.first().ok_or_else(|| {
1925 Error::unsupported("AV1 encode", "a sequence needs at least one picture")
1926 })?;
1927 let config = EncoderConfig {
1928 width: first.width,
1929 height: first.height,
1930 base_q_idx,
1931 // One key frame, at picture 0, and inter for the rest.
1932 gop: pictures.len().max(1),
1933 // `encode_sequence` writes an unspecified colour config.
1934 colour: Colour::Unspecified,
1935 tile_cols_log2: tiles.0,
1936 tile_rows_log2: tiles.1,
1937 };
1938 let mut encoder = Self::with_pyramid(config, pyramid)?;
1939 encoder.collected = Some(Vec::with_capacity(pictures.len()));
1940 let mut stream = Vec::new();
1941 for picture in pictures {
1942 for packet in encoder.encode_frames(picture)? {
1943 stream.extend_from_slice(&packet.data);
1944 }
1945 }
1946 for packet in encoder.flush()? {
1947 stream.extend_from_slice(&packet.data);
1948 }
1949 let mut collected = encoder.collected.take().expect("collecting");
1950 // Every source picture is coded exactly once, so a frame's display
1951 // order IS its index once the list is sorted by it.
1952 let coding_order: Vec<usize> = collected.iter().map(|(order, _)| *order as usize).collect();
1953 collected.sort_by_key(|(order, _)| *order);
1954 let frames: Vec<Encoded> = collected.into_iter().map(|(_, encoded)| encoded).collect();
1955 assert!(
1956 coding_order.iter().all(|&i| i < frames.len()),
1957 "a coded frame's display position is outside the sequence"
1958 );
1959 Ok(crate::encode::EncodedSequence {
1960 stream,
1961 frames,
1962 coding_order,
1963 })
1964 }
1965
1966 /// Stamps a packet with its display and coding positions and advances the
1967 /// coding-order clock.
1968 fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet {
1969 let dts = self.next_dts;
1970 self.next_dts += 1;
1971 Packet {
1972 data,
1973 key,
1974 order,
1975 dts,
1976 level,
1977 }
1978 }
1979
1980 /// Stores a coded frame into every DPB slot its `refresh_frame_flags`
1981 /// names (spec 7.20).
1982 fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) {
1983 let slot = DpbSlot {
1984 picture: encoded.reconstruction.clone(),
1985 order_hint,
1986 // `next_cdfs` is already a `Box<CdfSnapshot>` (lane-av1stacksweep),
1987 // so this is a pointer copy rather than a second boxing -- the
1988 // same fix lane-av1enchang made here, now that the producer hands
1989 // over a box instead of an inline 15232-byte `Cdfs`.
1990 cdfs: encoded.next_cdfs.clone(),
1991 };
1992 for &s in slots {
1993 self.dpb[s as usize] = Some(slot.clone());
1994 }
1995 }
1996
1997 /// Codes a key frame in pyramid mode: it refreshes all eight slots, so it
1998 /// becomes the anchor, the `GOLDEN_FRAME` and the CDF source for the
1999 /// whole GOP at once.
2000 fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> {
2001 let render = (self.config.width, self.config.height);
2002 let base = self
2003 .rate_loop
2004 .as_ref()
2005 .map_or(i16::from(self.config.base_q_idx), |r| {
2006 i16::from(r.q_idx(Level::Key))
2007 });
2008 let offset = self.pyramid.map_or(0, |p| p.key_q_offset);
2009 let base_q_idx = (base + offset).clamp(1, 255) as u8;
2010 let encoded = encode_key_frame_inner(
2011 &picture.padded_to(SUPERBLOCK),
2012 base_q_idx,
2013 DEADZONE,
2014 &KEY_FRAME_MODES,
2015 split_blocks(),
2016 render,
2017 self.color_config,
2018 &self.fctx,
2019 )?;
2020 self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0);
2021 self.anchor = 0;
2022 // Every leaf slot now holds the key frame, which `GOLDEN_FRAME`
2023 // already names: the chain starts empty again.
2024 self.leaf_hist.clear();
2025 let cropped = crop_encoded(&encoded, render.0, render.1);
2026 if let Some(rate_loop) = self.rate_loop.as_mut() {
2027 rate_loop.update(Level::Key, 0, base + offset, cropped.stream.len());
2028 }
2029 if let Some(collected) = self.collected.as_mut() {
2030 collected.push((order, cropped.clone()));
2031 }
2032 Ok(self.packet(cropped.stream, true, order, Level::Key))
2033 }
2034
2035 /// Codes one inter frame at `order` from the DPB, in coding order.
2036 #[allow(clippy::too_many_arguments)]
2037 fn encode_pyramid_inter(
2038 &mut self,
2039 order: u64,
2040 picture: &Picture,
2041 last_slot: u8,
2042 self_slot: u8,
2043 altref_slot: u8,
2044 // lane-last2: the slot read as `LAST2_FRAME`. `None` -- and any slot
2045 // holding no picture, or the same one `LAST_FRAME` reads -- leaves
2046 // the reference set exactly as it was before this lane.
2047 last2_slot: Option<u8>,
2048 show_frame: bool,
2049 level: Level,
2050 // The quantizer offset comes from the CALLER, not from `level`: a
2051 // three-level group codes two `Level::Arf` frames (the group's top
2052 // ARF and the mid one) at different offsets, and they share the
2053 // rate-control slot but not the offset.
2054 offset: i16,
2055 // The lookahead window this frame's temporal lambda map is built
2056 // from, already padded (lane-arfcen). Empty codes the frame at one
2057 // lambda, which is what the whole pyramid path used to do.
2058 lookahead: &[Picture],
2059 // lane-lookahead: DISPLAY-FUTURE pictures for the SOURCE temporal
2060 // filter only (the top ARF's, out of the buffered next group), never
2061 // for the temporal lambda map -- keeping the filter's window and the
2062 // tpl window separate levers. Empty everywhere else.
2063 future: &[Picture],
2064 ) -> Result<Packet> {
2065 let render = (self.config.width, self.config.height);
2066 let order_hint = (order & 0x7f) as u32;
2067 let base = self
2068 .rate_loop
2069 .as_ref()
2070 .map_or(i16::from(self.config.base_q_idx), |r| {
2071 i16::from(r.q_idx(level))
2072 });
2073 let base_q_idx = (base + offset).clamp(1, 255) as u8;
2074 // lane-arfq: the top ARF of a mini-GOP is the hidden frame coded at
2075 // the pyramid's OWN `arf_q_offset` (the mid and quarter levels are
2076 // `Level::Arf` too but sit at their own offsets), and it is the level
2077 // the whole group predicts from -- so it reads its own `delta_q`
2078 // strength (`crate::speed::DQ_LEVEL_K`).
2079 let dq_level = match (show_frame, self.pyramid.map(|p| p.arf_q_offset)) {
2080 (true, _) => crate::encode::DqLevel::Leaf,
2081 (false, Some(arf)) if arf == offset => crate::encode::DqLevel::TopArf,
2082 (false, _) => crate::encode::DqLevel::MidArf,
2083 };
2084 // spec 5.9.2's `ref_frame_sign_bias`, derived from what the slots
2085 // this frame names actually hold: a reference whose order hint is
2086 // AHEAD of this frame's is backward-biased, and the MV stack scans
2087 // (writer and decoder alike) flip borrowed candidates across the
2088 // boundary. Only `ALTREF_FRAME` can be ahead here — the leaves of a
2089 // mini-GOP name the group's hidden frame there.
2090 let mut sign_bias = crate::mvstack::NO_SIGN_BIAS;
2091 let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| {
2092 dpb[slot as usize]
2093 .as_ref()
2094 .is_some_and(|s| s.order_hint > order_hint)
2095 };
2096 // A LAST2 slot only counts when it holds a picture that is not the
2097 // one `LAST_FRAME` already names; otherwise the frame codes the
2098 // reference set it always did.
2099 let last2_slot = last2_slot.filter(|&s| s != last_slot && self.dpb[s as usize].is_some());
2100 let slots = [
2101 last_slot,
2102 last2_slot.unwrap_or(last_slot),
2103 last_slot,
2104 GOLDEN_SLOT,
2105 last_slot,
2106 last_slot,
2107 altref_slot,
2108 ];
2109 for (i, slot) in slots.into_iter().enumerate() {
2110 sign_bias[i] = ahead(slot, &self.dpb);
2111 }
2112 // The same seven slots' order hints, for `skipModeAllowed` (spec
2113 // 5.9.22) in the frame-header writer.
2114 let order_hints: [u32; 7] = slots.map(|slot| {
2115 self.dpb[slot as usize]
2116 .as_ref()
2117 .map_or(0, |s| s.order_hint & 0x7f)
2118 });
2119 let reference = self.dpb[last_slot as usize]
2120 .as_ref()
2121 .map(|s| s.picture.clone())
2122 .ok_or_else(|| {
2123 Error::unsupported(
2124 "AV1 encode",
2125 "an inter frame needs a previous reconstruction",
2126 )
2127 })?;
2128 let last2 =
2129 last2_slot.and_then(|s| self.dpb[s as usize].as_ref().map(|d| d.picture.clone()));
2130 let golden = self.dpb[GOLDEN_SLOT as usize]
2131 .as_ref()
2132 .map(|s| s.picture.clone());
2133 let altref = (altref_slot != GOLDEN_SLOT)
2134 .then(|| {
2135 self.dpb[altref_slot as usize]
2136 .as_ref()
2137 .map(|s| s.picture.clone())
2138 })
2139 .flatten();
2140 let start_cdfs = self.dpb[last_slot as usize]
2141 .as_ref()
2142 .map(|s| s.cdfs.0.clone());
2143 // lane-arfpred: the top ARF is coded from a TEMPORALLY FILTERED
2144 // source when `speed::ARF_TF` is non-zero -- the grain it would
2145 // otherwise spend its residual on is averaged out against the
2146 // group's own display neighbours (`lookahead`, already padded).
2147 let source = picture.padded_to(SUPERBLOCK);
2148 // ... and never at the very top of the quality range, where the
2149 // anchor's own quantizer has hit the rate loop's floor
2150 // ([`crate::speed::ARF_TF_QMIN`]).
2151 let tf = match dq_level {
2152 crate::encode::DqLevel::TopArf => arf_tf_strength(),
2153 // lane-arftf: the mid ARF gets its own strength -- its window is
2154 // the group's later leaves, i.e. the filter runs FORWARD there.
2155 crate::encode::DqLevel::MidArf => arf_tf_mid_strength(),
2156 crate::encode::DqLevel::Leaf => 0.0,
2157 };
2158 let tf = match base_q_idx >= crate::speed::ARF_TF_QMIN {
2159 true => tf,
2160 false => 0.0,
2161 };
2162 let source = match tf > 0.0 {
2163 true => {
2164 // lane-lookahead: the filter's window is sized HERE -- up to
2165 // `ARF_TF_WIN` display-past neighbours (nearest first) and
2166 // then the display-future ones the caller buffered.
2167 let window: Vec<Picture> = lookahead
2168 .iter()
2169 .take(arf_tf_window())
2170 .chain(future.iter())
2171 .cloned()
2172 .collect();
2173 crate::encode::arf_temporal_filter(&source, &window, tf)
2174 }
2175 false => source,
2176 };
2177 let encoded = encode_inter_frame(
2178 &source,
2179 &reference,
2180 base_q_idx,
2181 DEADZONE,
2182 order_hint,
2183 order_hints,
2184 render,
2185 start_cdfs.as_ref(),
2186 golden.as_ref(),
2187 altref.as_ref(),
2188 last2.as_ref(),
2189 &self.fctx,
2190 Some(crate::encode::PyramidFrame {
2191 last_slot,
2192 self_slot,
2193 altref_slot,
2194 last2_slot,
2195 show_frame,
2196 sign_bias,
2197 dq_level,
2198 }),
2199 // lane-arfcen: the group's own sources ARE this frame's window
2200 // (`tpl_window`); it was `&[]` here, which switched the temporal
2201 // lambda map off on every frame the default stream codes.
2202 lookahead,
2203 );
2204 // Name the pyramid position in any failure: an error out of the tile
2205 // writer or the filter search is otherwise indistinguishable between
2206 // the hidden frame and the leaves that read it.
2207 let encoded = encoded.map_err(|e| {
2208 Error::unsupported(
2209 "AV1 encode",
2210 format!(
2211 "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \
2212 altref {altref_slot}, last2 {last2_slot:?}, shown {show_frame}, golden {}, \
2213 altref pic {}): {e}",
2214 golden.is_some(),
2215 altref.is_some(),
2216 ),
2217 )
2218 })?;
2219 self.refresh(&[self_slot], &encoded, order_hint);
2220 let cropped = crop_encoded(&encoded, render.0, render.1);
2221 if let Some(rate_loop) = self.rate_loop.as_mut() {
2222 rate_loop.update(level, offset, base + offset, cropped.stream.len());
2223 }
2224 if let Some(collected) = self.collected.as_mut() {
2225 collected.push((order, cropped.clone()));
2226 }
2227 Ok(self.packet(cropped.stream, false, order, level))
2228 }
2229
2230 /// Closes the open mini-GOP. With the lookahead off that codes it
2231 /// straight away, which is byte for byte what this encoder did before
2232 /// lane-lookahead; with it on the open group takes the `ready` slot and
2233 /// the group ALREADY there is coded, with the open one's sources as its
2234 /// display-future window.
2235 fn drain_pending(&mut self) -> Result<Vec<Packet>> {
2236 if !lookahead() {
2237 let group = std::mem::take(&mut self.pending);
2238 return self.code_group(group, &[]);
2239 }
2240 let group = std::mem::take(&mut self.ready);
2241 let next = std::mem::take(&mut self.pending);
2242 let packets = self.code_group(group, &next);
2243 self.ready = next;
2244 packets
2245 }
2246
2247 /// Codes every group still buffered, in coding order -- what a key frame
2248 /// (`next` is the key picture, the last buffered group's own
2249 /// display-future) and the end of stream (`None`) both need. The tail
2250 /// group can be any length, down to the single picture `code_group`
2251 /// codes as one shown leaf.
2252 fn drain_all(&mut self, next: Option<&Picture>) -> Result<Vec<Packet>> {
2253 let tail: Vec<(u64, Picture)> = next
2254 .filter(|_| lookahead())
2255 .map(|p| vec![(self.next_index, p.clone())])
2256 .unwrap_or_default();
2257 let ready = std::mem::take(&mut self.ready);
2258 let pending = std::mem::take(&mut self.pending);
2259 let mut packets = self.code_group(ready, &pending)?;
2260 packets.extend(self.code_group(pending, &tail)?);
2261 Ok(packets)
2262 }
2263
2264 /// Codes one mini-GOP: its hidden frame first, then its leaves, then
2265 /// the `show_existing_frame` header that puts the hidden frame back in
2266 /// display order. `future` is the display-future sources the caller has
2267 /// buffered past this group (lane-lookahead), empty without a lookahead.
2268 fn code_group(
2269 &mut self,
2270 group: Vec<(u64, Picture)>,
2271 future: &[(u64, Picture)],
2272 ) -> Result<Vec<Packet>> {
2273 if group.is_empty() {
2274 return Ok(Vec::new());
2275 }
2276 let mut packets = Vec::with_capacity(group.len() + 1);
2277 // The lookahead window of the group's picture at index `pos`: the
2278 // display-order successors inside this group, or -- for the group's
2279 // top ARF, the last picture, whose successors are not buffered yet --
2280 // the leaves BEHIND it in reverse display order, which are exactly
2281 // the pictures that predict backward from it. Padded like the frame
2282 // itself, as `encode_inter_frame` wants it.
2283 let tpl_window = |pos: usize, back: bool| -> Vec<Picture> {
2284 let depth = crate::encode::tpl_depth();
2285 if !tpl_pyramid() || depth < 2 {
2286 return Vec::new();
2287 }
2288 let window: Vec<&Picture> = match back {
2289 false => group[pos + 1..].iter().map(|(_, p)| p).collect(),
2290 true => group[..pos].iter().rev().map(|(_, p)| p).collect(),
2291 };
2292 window
2293 .into_iter()
2294 .take(depth - 1)
2295 .map(|p| p.padded_to(SUPERBLOCK))
2296 .collect()
2297 };
2298 // lane-last2: the slot a frame reading `last_slot` as `LAST_FRAME`
2299 // names as `LAST2_FRAME` -- the most recent shown leaf that is not
2300 // the one it already reads. `None` with the lever off, or before two
2301 // distinct past pictures exist.
2302 let last2_of = |hist: &[u8], last_slot: u8| -> Option<u8> {
2303 last2()
2304 .then(|| hist.iter().copied().find(|&s| s != last_slot))
2305 .flatten()
2306 };
2307 let anchor_slot = ANCHOR_SLOTS[self.anchor];
2308 let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor];
2309 let (arf_order, arf_picture) = group.last().cloned().expect("non-empty");
2310 let pyramid = self.pyramid.expect("pyramid mode");
2311 if group.len() == 1 {
2312 // Nothing to predict backward, so no hidden frame: one shown leaf
2313 // that also becomes the next group's anchor.
2314 packets.push(self.encode_pyramid_inter(
2315 arf_order,
2316 &arf_picture,
2317 anchor_slot,
2318 next_anchor_slot,
2319 GOLDEN_SLOT,
2320 last2_of(&self.leaf_hist, anchor_slot),
2321 true,
2322 Level::Leaf,
2323 pyramid.leaf_q_offset,
2324 &tpl_window(0, false),
2325 &[],
2326 )?);
2327 self.anchor = 1 - self.anchor;
2328 return Ok(packets);
2329 }
2330 // lane-lookahead: the display-future half of the top ARF's temporal
2331 // filter window, padded like the frame itself. Empty when the
2332 // lookahead is off (`future` is then always empty) or when the filter
2333 // asks for no future neighbours, which is what keeps the default
2334 // stream byte-identical.
2335 let arf_future: Vec<Picture> = future
2336 .iter()
2337 .take(arf_tf_window_future())
2338 .map(|(_, p)| p.padded_to(SUPERBLOCK))
2339 .collect();
2340 // lane-tplfut: the top ARF's TEMPORAL LAMBDA window. Mode 0 (and any
2341 // mode with no buffered future picture) keeps the group's own
2342 // display-PAST sources, reversed -- the only window that exists
2343 // without a lookahead, and the one every measurement so far was
2344 // taken with. The other modes read the next group's sources, which
2345 // is the direction libaom's tpl looks at an ARF.
2346 // `n` of the buffered display-future sources, nearest first, padded
2347 // like the frame being coded.
2348 let arf_tpl_future = |n: usize| -> Vec<Picture> {
2349 future
2350 .iter()
2351 .take(n)
2352 .map(|(_, p)| p.padded_to(SUPERBLOCK))
2353 .collect()
2354 };
2355 let arf_tpl: Vec<Picture> = {
2356 let depth = crate::encode::tpl_depth();
2357 let past = || tpl_window(group.len() - 1, true);
2358 match (tpl_fut(), future.is_empty(), tpl_pyramid() && depth >= 2) {
2359 (_, _, false) => Vec::new(),
2360 (0, _, _) | (_, true, _) => past(),
2361 (1, _, _) => arf_tpl_future(depth - 1),
2362 // Half the budget each side (`EC_AV1_TPL_FUT_HALF=<n>`
2363 // moves the split), past first: the chain then has
2364 // ONE discontinuity in the middle (the coarse pass between
2365 // the nearest past and the nearest future neighbour spans the
2366 // whole group), which is the arm's known cost.
2367 (2, _, _) => {
2368 let budget = tpl_fut_win(depth);
2369 let mut w = past();
2370 w.truncate(tpl_fut_half().max(1));
2371 let room = budget.saturating_sub(w.len());
2372 w.extend(arf_tpl_future(room));
2373 w
2374 }
2375 // Mode 3 and anything above: the WHOLE buffered next group.
2376 (_, _, _) => arf_tpl_future(future.len()),
2377 }
2378 };
2379 // The group's top level: the last picture, hidden, off the anchor.
2380 packets.push(self.encode_pyramid_inter(
2381 arf_order,
2382 &arf_picture,
2383 anchor_slot,
2384 next_anchor_slot,
2385 // lane-arfcen: the slot this ARF refreshes still holds the ARF
2386 // from two groups back, so naming it here gives the frame a
2387 // SECOND, distinct past anchor instead of the key it already
2388 // reads as GOLDEN.
2389 match arf_altref() {
2390 true => next_anchor_slot,
2391 false => GOLDEN_SLOT,
2392 },
2393 // The ARF levels take no LAST2: the anchor pair already gives a
2394 // top ARF two distinct past anchors (`arf_altref`), and the mid
2395 // and quarter frames have only the one past anchor in the DPB.
2396 None,
2397 false,
2398 Level::Arf,
2399 pyramid.arf_q_offset,
2400 &arf_tpl,
2401 // lane-lookahead: the group's top ARF is its LAST picture in
2402 // display order, so every picture of the next group is a
2403 // display-future neighbour of it -- nearest first.
2404 &arf_future,
2405 )?);
2406 let leaves = group.len() - 1;
2407 // THE THIRD LEVEL: a second hidden frame at the middle of the leaf
2408 // run, coded off the anchor with the top ARF as its own backward
2409 // reference. It needs a leaf on both sides of it, so a group of
2410 // three or fewer stays two-level.
2411 //
2412 // AND IT NEEDS A RUN LONG ENOUGH TO AMORTISE IT: a GOP that is one
2413 // single mini-GOP (`group_target` absorbs a tail, so a 12-picture GOP
2414 // under `mini_gop` 8 is ONE group of 11) pays for the second hidden
2415 // frame out of eleven pictures and reads +2.8 BD points worse against
2416 // libaom on film B at every mid offset measured (-4: +71.1, -8:
2417 // +71.2, against the two-level +68.4), while the 48-picture GOP -- six
2418 // groups sharing the same machinery -- is 6.0 points BETTER. So the
2419 // third level is switched on by the RUN's length, not by the group's:
2420 // the same GOP-length dependence `group_target` itself was built for.
2421 let long_run = self.config.gop > pyramid.mini_gop + pyramid.mini_gop / 2;
2422 let mid = pyramid
2423 .mid_q_offset
2424 .filter(|_| leaves >= 3 && long_run)
2425 .map(|offset| {
2426 let at = (leaves - 1) / 2;
2427 (at, offset)
2428 });
2429 if let Some((at, offset)) = mid {
2430 let (order, picture) = group[at].clone();
2431 packets.push(self.encode_pyramid_inter(
2432 order,
2433 &picture,
2434 anchor_slot,
2435 MID_SLOT,
2436 next_anchor_slot,
2437 None,
2438 false,
2439 Level::Arf,
2440 offset,
2441 &tpl_window(at, false),
2442 &[],
2443 )?);
2444 }
2445 // THE FOURTH LEVEL: one hidden frame at the middle of each half of
2446 // the leaf run, so no leaf is more than one picture from a hidden
2447 // reference on either side -- the depth the references run (rav1e
2448 // speed 6 codes 23 hidden frames per 48 pictures, libaom four levels
2449 // per 16-picture group) and the lever three levels had run out of.
2450 // It hangs off the mid level, and it needs a leaf on both sides of
2451 // both quarter points, which a run of fewer than seven leaves cannot
2452 // give.
2453 let quarters = match (mid, pyramid.quarter_q_offset) {
2454 (Some((at, _)), Some(offset)) if leaves >= 7 => {
2455 Some(([(at - 1) / 2, (at + leaves) / 2], offset))
2456 }
2457 _ => None,
2458 };
2459 if let Some((at, offset)) = quarters {
2460 // The first quarter predicts forward off the group's anchor and
2461 // backward off the mid ARF; the second starts FROM the mid ARF
2462 // and reads the group's top ARF backward.
2463 for (i, &pos) in at.iter().enumerate() {
2464 let (order, picture) = group[pos].clone();
2465 let (last_slot, altref_slot) = match i {
2466 0 => (anchor_slot, MID_SLOT),
2467 _ => (MID_SLOT, next_anchor_slot),
2468 };
2469 packets.push(self.encode_pyramid_inter(
2470 order,
2471 &picture,
2472 last_slot,
2473 QUARTER_SLOTS[i],
2474 altref_slot,
2475 None,
2476 false,
2477 Level::Arf,
2478 offset,
2479 &tpl_window(pos, false),
2480 &[],
2481 )?);
2482 }
2483 }
2484 // Every hidden frame INSIDE the leaf run, by leaf index, in display
2485 // order: what a leaf reads forward (the nearest one behind it) and
2486 // backward (the nearest one ahead of it, the group's top ARF when
2487 // there is none).
2488 let mut inner: Vec<(usize, u8)> = Vec::new();
2489 if let Some((at, _)) = mid {
2490 inner.push((at, MID_SLOT));
2491 }
2492 if let Some((at, _)) = quarters {
2493 inner.extend(at.iter().zip(QUARTER_SLOTS).map(|(&at, slot)| (at, slot)));
2494 }
2495 inner.sort_unstable();
2496 let (seq, _) = crate::encode::key_frame_headers(
2497 self.config.width,
2498 self.config.height,
2499 self.config.base_q_idx,
2500 )?;
2501 let show_existing = |encoder: &mut Self, slot: u8, order: u64| -> Result<Packet> {
2502 let mut data = crate::obu::temporal_delimiter();
2503 data.extend_from_slice(&crate::frame::show_existing_frame_obu(&seq, slot)?);
2504 Ok(encoder.packet(data, false, order, Level::ShowExisting))
2505 };
2506 // The leaves, in display order, so every `show_existing_frame` lands
2507 // in its own display position. Each leaf names the nearest hidden
2508 // frame BEHIND it as `LAST_FRAME` (the group's anchor for the first
2509 // leaf, otherwise the previous leaf) and the nearest one AHEAD as
2510 // `ALTREF_FRAME` (the group's top ARF when none is closer).
2511 for (i, (order, picture)) in group[..leaves].iter().enumerate() {
2512 if let Some(&(_, slot)) = inner.iter().find(|(at, _)| *at == i) {
2513 let packet = show_existing(self, slot, *order)?;
2514 packets.push(packet);
2515 continue;
2516 }
2517 // The previous shown leaf's own slot: `LEAF_SLOT` with the
2518 // lever off, and with it on whichever of [`LEAF_SLOTS`] that leaf
2519 // refreshed.
2520 let prev_leaf = self.leaf_hist.first().copied().unwrap_or(LEAF_SLOT);
2521 let last_slot = match i {
2522 0 => anchor_slot,
2523 i => inner
2524 .iter()
2525 .find(|(at, _)| at + 1 == i)
2526 .map_or(prev_leaf, |&(_, slot)| slot),
2527 };
2528 // Alternate the refresh: this leaf takes the leaf slot the
2529 // PREVIOUS leaf did not, which is the one the leaf before that
2530 // wrote and which this frame may still read as `LAST2_FRAME`
2531 // (read before write).
2532 let self_slot = match last2() {
2533 true => LEAF_SLOTS
2534 .into_iter()
2535 .find(|&s| Some(s) != self.leaf_hist.first().copied())
2536 .unwrap_or(LEAF_SLOT),
2537 false => LEAF_SLOT,
2538 };
2539 let last2_slot = last2_of(&self.leaf_hist, last_slot);
2540 let altref_slot = inner
2541 .iter()
2542 .find(|(at, _)| *at > i)
2543 .map_or(next_anchor_slot, |&(_, slot)| slot);
2544 self.leaf_hist.insert(0, self_slot);
2545 self.leaf_hist.truncate(2);
2546 packets.push(self.encode_pyramid_inter(
2547 *order,
2548 picture,
2549 last_slot,
2550 self_slot,
2551 altref_slot,
2552 last2_slot,
2553 true,
2554 Level::Leaf,
2555 pyramid.leaf_q_offset,
2556 &tpl_window(i, false),
2557 &[],
2558 )?);
2559 }
2560 let packet = show_existing(self, next_anchor_slot, arf_order)?;
2561 packets.push(packet);
2562 self.anchor = 1 - self.anchor;
2563 Ok(packets)
2564 }
2565}
2566
2567#[cfg(test)]
2568pub(crate) mod tests;