forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.4 MiBcdccbc2Tahinli10 hours ago4263 commits

mod.rs2564 lines, 118.8 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 repay = matches!(self, RateTarget::Bitrate { .. });
129 let target_bytes = match self {
130 RateTarget::QIndex(q) => {
131 config.base_q_idx = q;
132 return None;
133 }
134 RateTarget::Quality(quality) => {
135 config.base_q_idx = quality_to_q_idx(quality);
136 return None;
137 }
138 RateTarget::BytesPerFrame(target_bytes) => f64::from(target_bytes),
139 RateTarget::Bitrate {
140 bits_per_second,
141 frames_per_second,
142 } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0),
143 };
144 let mut rate_loop = RateLoop::new(
145 target_bytes,
146 f64::from(config.base_q_idx),
147 pyramid,
148 config.gop,
149 );
150 rate_loop.repay = repay;
151 Some(rate_loop)
152 }
153}
154
155/// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's
156/// span (`q_idx` 40 at `quality` 100 down to `q_idx` 240 at `quality` 0);
157/// `quality` above 100 clamps to the best point measured, matching a CRF
158/// dial's own saturating ends rather than extrapolating past calibrated
159/// data.
160fn quality_to_q_idx(quality: u8) -> u8 {
161 let quality = f64::from(quality.min(100));
162 (240.0 - quality * 2.0).round() as u8
163}
164
165/// What one coded frame is worth, relative to a leaf, as a function of how
166/// much FINER than the leaf it is coded (`leaf_q_offset - own offset`, in
167/// `q_idx` steps): `exp(WEIGHT_LEVEL_GAIN * delta)`.
168///
169/// This is the level model the byte budget is split by, and it is MEASURED,
170/// not the old flat "a hidden frame is worth two leaves" guess: the long-GOP
171/// census (`lanes/rc.report.md`, films A and B at three quantizers each,
172/// `lanes/census-longgop-v2.md`'s q150 row among them) reads a level's
173/// bytes/frame as very close to log-linear in its own q offset, at
174/// d(ln bytes)/d(q_idx) = -0.0557 -- three and a half times the SLOPE of the
175/// controller's own `RateLoop::GAIN` (0.0154), because a deeper level is not
176/// just quantized finer, it also carries the group's residual for every
177/// frame that predicts off it.
178const WEIGHT_LEVEL_GAIN: f64 = 0.0557;
179
180/// The key frame's own correction on top of `WEIGHT_LEVEL_GAIN`: an intra
181/// frame at the key's offset codes this much of what the level model alone
182/// predicts (the census's key frames are consistently smaller than the pure
183/// exponential, since the exponential is fitted on INTER levels whose size
184/// keeps growing with reference depth).
185const KEY_WEIGHT: f64 = 1.08;
186
187/// `EC_AV1_RL_CENSUS=1` — one stderr line per frame the rate loop steers.
188fn census_on() -> bool {
189 std::env::var("EC_AV1_RL_CENSUS").is_ok_and(|v| v == "1")
190}
191
192/// One level of a run, as the re-plan sees it: how much of the run's weight
193/// it carries, how much of that is still to be coded, and -- once its
194/// effective quantizer has hit the coder's 1..=255 bound -- the leaf-
195/// equivalent bytes it actually spends there.
196#[derive(Debug, Clone, Copy)]
197struct LevelPlan {
198 /// The controller slot this level shares ([`RateLoop::slot`]).
199 slot: usize,
200 /// The level's own `base_q_idx` offset: what tells two hidden levels
201 /// apart inside slot 1.
202 offset: i16,
203 weight: f64,
204 left: f64,
205 bound: bool,
206 rate: f64,
207}
208
209impl LevelPlan {
210 fn new(slot: usize, offset: i16, weight: f64) -> Self {
211 Self {
212 slot,
213 offset,
214 weight,
215 left: weight,
216 bound: false,
217 rate: 0.0,
218 }
219 }
220}
221
222/// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and
223/// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from
224/// the calibration sweep's own log-linear slope (bytes roughly halve every
225/// ~45 `q_idx` steps there, i.e. `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped
226/// per frame. Pure proportional — no accumulated error term — is the windup
227/// bound itself ([[vorbis-rate-loop-windup]]'s class): the only state carried
228/// between frames is `q`, already clamped to `0..=255`, so a quiet lead-in
229/// cannot build a debt a later transient has to repay; each frame's step is
230/// bounded by `STEP_CLAMP` regardless of history.
231///
232/// In pyramid mode the state is kept PER LEVEL: each frame's size is
233/// predicted from the previous frame of its own level, against that level's
234/// own share of the budget, which is the whole "two-pass-free model" this
235/// encoder carries.
236#[derive(Debug, Clone, Copy)]
237struct RateLoop {
238 /// Byte target per level, indexed by [`RateLoop::slot`].
239 target: [f64; 3],
240 /// Quantizer per level, same index.
241 q: [f64; 3],
242 /// Whether each slot has already steered off a real coded frame. The
243 /// FIRST update of a slot is the seeding one and takes the model's whole
244 /// step ([`RateLoop::update`]); every later one is clamped.
245 seeded: [bool; 3],
246 prev_ratio: [f64; 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 repay: bool,
276 /// `EC_AV1_RL_CENSUS=1`: one line per coded frame on stderr.
277 census: bool,
278 coded: usize,
279}
280
281impl RateLoop {
282 /// The steepest a single frame is allowed to move `base_q_idx`, in
283 /// either direction — chosen so one wildly over/under-sized frame
284 /// (a scene cut, a black lead-in) nudges the next frame's quantizer
285 /// rather than slamming it to an extreme.
286 const STEP_CLAMP: f64 = 12.0;
287 /// The calibration sweep's own slope (see the struct doc), inverted to
288 /// convert a bytes ratio into a `q_idx` step.
289 const GAIN: f64 = 1.0 / WEIGHT_LEVEL_GAIN;
290 /// The windup bound on [`RateLoop::replan`]: however much a bound level
291 /// fails to spend, no other level's target may grow past this multiple of
292 /// its opening share. Without it a run whose hidden levels are all at the
293 /// floor would keep piling the whole run's budget onto the leaves.
294 const REPLAN_CLAMP: f64 = 4.0;
295 /// The same bound the other way: a re-plan may not drive a level's target
296 /// below this multiple of its opening share. A target of zero would STOP
297 /// the loop outright ([`RateLoop::update`] returns on a non-positive
298 /// target), which is how the first cut of this fix froze every level of a
299 /// run at whatever quantizer it had reached.
300 const REPLAN_FLOOR: f64 = 0.25;
301 const TINY_FRAME_DIVISOR: f64 = 4.0;
302
303 fn new(target_bytes: f64, start_q: f64, pyramid: Option<Pyramid>, gop: usize) -> Self {
304 // THE LEVEL MODEL. Every coded frame of the run is priced by its own
305 // q offset through `WEIGHT_LEVEL_GAIN`, in units of one leaf, and the
306 // run's `gop` frame targets are shared out in those units. The old
307 // model priced a group as "one hidden frame worth `ARF_WEIGHT` = 2
308 // leaves plus `m - 1` leaves", which was wrong twice over and the two
309 // errors cancelled (lane-pyr6): the group has coded TWO hidden frames
310 // since the mid level landed (four with
311 // [`Pyramid::quarter_q_offset`]), and a hidden frame is worth far
312 // more than two leaves -- the census reads the top ARF at 24x a leaf
313 // and the mid at 5x. Both are fixed here, in one diff.
314 let (key_q_offset, leaf_q_offset, hidden, leaves) = match pyramid {
315 Some(p) => {
316 let (hidden, leaves) = gop_shape(p, gop);
317 (p.key_q_offset, p.leaf_q_offset, hidden, leaves)
318 }
319 None => (0, 0, Vec::new(), gop.saturating_sub(1)),
320 };
321 let w = |offset: i16| {
322 ((f64::from(leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp()
323 };
324 let key = KEY_WEIGHT * w(key_q_offset);
325 let total: f64 =
326 key + leaves as f64 + hidden.iter().map(|&(o, n)| n as f64 * w(o)).sum::<f64>();
327 // One leaf's byte target: the run is worth `gop` frame targets and
328 // `total` leaves.
329 let scale = target_bytes * gop.max(1) as f64 / total.max(f64::EPSILON);
330 // THE HIDDEN SLOT holds every hidden level at once (`Level::Arf` is
331 // the top ARF, the mid and the quarters alike -- one controller,
332 // different q offsets), so its target is kept in LEAF-EQUIVALENT
333 // bytes and [`RateLoop::update`] scales it by the coded frame's own
334 // `w(offset)`. Measuring each hidden frame against its OWN predicted
335 // size is what keeps the shared slot from oscillating between the
336 // levels it mixes.
337 // One plan per level, in coding order: key, hidden levels (at most
338 // three distinct offsets -- top, mid, quarters), leaves.
339 let mut plans = [None; 5];
340 plans[0] = Some(LevelPlan::new(0, key_q_offset, key));
341 let mut i = 1;
342 for &(o, n) in hidden.iter().take(3) {
343 plans[i] = Some(LevelPlan::new(1, o, n as f64 * w(o)));
344 i += 1;
345 }
346 plans[i] = Some(LevelPlan::new(2, leaf_q_offset, leaves as f64));
347 Self {
348 target: [scale * key, scale, scale],
349 q: [start_q; 3],
350 seeded: [false; 3],
351 leaf_q_offset,
352 key_weight: key,
353 run_weight: total,
354 run_bytes: target_bytes * gop.max(1) as f64,
355 left_weight: total,
356 left_bytes: target_bytes * gop.max(1) as f64,
357 plans,
358 scale0: scale,
359 repay: true,
360 prev_ratio: [1.0; 3],
361 census: census_on(),
362 coded: 0,
363 }
364 }
365
366 /// What a frame coded `offset` steps off `base_q_idx` is worth in
367 /// leaf-equivalent bytes ([`WEIGHT_LEVEL_GAIN`]).
368 fn weight(&self, offset: i16) -> f64 {
369 ((f64::from(self.leaf_q_offset) - f64::from(offset)) * WEIGHT_LEVEL_GAIN).exp()
370 }
371
372 /// Which [`LevelPlan`] a coded frame belongs to. Only the hidden slot
373 /// holds more than one level, so only there does the offset decide.
374 fn plan_of(&self, slot: usize, offset: i16) -> Option<usize> {
375 self.plans
376 .iter()
377 .position(|p| p.is_some_and(|p| p.slot == slot && (slot != 1 || p.offset == offset)))
378 }
379
380 fn slot(&self, level: Level) -> usize {
381 match level {
382 Level::Key => 0,
383 Level::Arf => 1,
384 // A `show_existing_frame` packet codes no pixels and never
385 // reaches `update`; it shares the leaf slot so `q_idx` is total.
386 Level::Leaf | Level::ShowExisting => 2,
387 }
388 }
389
390 fn q_idx(&self, level: Level) -> u8 {
391 self.q[self.slot(level)].round().clamp(0.0, 255.0) as u8
392 }
393
394 /// Steers this level's `q` toward its own target from the frame's actual
395 /// coded size.
396 ///
397 /// `raw_q` is the quantizer the frame WANTED (`base_q_idx + offset`,
398 /// before the coder's own 1..=255 clamp): outside that range the level is
399 /// at its bound and its share of the budget has to move elsewhere.
400 fn update(&mut self, level: Level, offset: i16, raw_q: i16, actual_bytes: usize) {
401 let slot = self.slot(level);
402 if self.target[slot] <= 0.0 || actual_bytes == 0 {
403 return;
404 }
405 // A hidden frame is measured against ITS OWN level's predicted size:
406 // slot 1's target is in leaf-equivalent bytes.
407 let frame_weight = match slot {
408 0 => self.key_weight,
409 1 => self.weight(offset),
410 _ => 1.0,
411 };
412 let target = match slot == 1 {
413 true => self.target[slot] * frame_weight,
414 false => self.target[slot],
415 };
416 let ratio = actual_bytes as f64 / target;
417 // `STEP_CLAMP` protects an operating point this slot has not found
418 // yet: its `q` is still the caller's `base_q_idx` guess, and the
419 // clamp makes the loop WALK to the right quantizer at twelve steps a
420 // frame. Measured on the 48-frame bitrate gate, the pyramid's ARF
421 // slot spent five of its twelve frames pinned at `-STEP_CLAMP` and
422 // the stream landed -10.2% under target -- convergence lag, not a
423 // steady-state offset (the fixed point of this loop is `actual ==
424 // target` exactly). So a slot's FIRST frame takes the model's whole
425 // step and seeds `q` where the log-linear slope says it belongs; from
426 // the second frame on the clamp is back, and nothing is accumulated
427 // between frames, so [[vorbis-rate-loop-windup]]'s bound still holds.
428 let seeded = std::mem::replace(&mut self.seeded[slot], true);
429 let smoothed = if seeded && !self.repay {
430 (ratio * self.prev_ratio[slot]).sqrt()
431 } else {
432 ratio
433 };
434 self.prev_ratio[slot] = ratio;
435 let raw = smoothed.ln() * Self::GAIN;
436 let step = if seeded {
437 raw.clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP)
438 } else {
439 raw
440 };
441 let step = match ratio < 1.0 / Self::TINY_FRAME_DIVISOR && step < 0.0 {
442 true => 0.0,
443 false => step,
444 };
445 self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0);
446 let bound = !(1..=255).contains(&raw_q);
447 if let Some(plan) = self
448 .plan_of(slot, offset)
449 .and_then(|i| self.plans[i].as_mut())
450 {
451 plan.bound = bound;
452 plan.rate = actual_bytes as f64 / frame_weight.max(f64::EPSILON);
453 }
454 if self.census {
455 eprintln!(
456 "RLCENSUS n={} level={level:?} slot={slot} target={target:.0} actual={actual_bytes} \
457 base_q={:.1} raw_q={raw_q} eff_q={} bound={} left_bytes={:.0} left_w={:.1}",
458 self.coded,
459 self.q[slot],
460 raw_q.clamp(1, 255),
461 bound,
462 self.left_bytes,
463 self.left_weight,
464 );
465 self.coded += 1;
466 }
467 if self.repay {
468 self.replan(level, slot, offset, frame_weight, actual_bytes as f64);
469 }
470 }
471
472 /// Re-plans the REST OF THE RUN from what it has actually spent: the
473 /// level model says how the budget SPLITS, and nothing but a measurement
474 /// says what a frame of this content costs at all.
475 ///
476 /// Two frames of a run cannot be steered by the loop and both are pure
477 /// model error without this: the KEY, coded once at the caller's seed `q`
478 /// before anything has been measured (the census's key frames run 0.5x to
479 /// 2.7x the model across the two films), and any level whose `q` has hit
480 /// the floor -- at 3 Mbit/s on the gate's clip the hidden slot codes at
481 /// `q_idx` 1 and physically cannot spend its share, which the leaves must
482 /// then absorb or the stream lands a third under target.
483 ///
484 /// It is NOT an accumulated error term in `q` ([[vorbis-rate-loop-windup]]
485 /// is about exactly that): `q` still moves only by this frame's own
486 /// clamped proportional step, the re-plan only moves the TARGET the next
487 /// frame is measured against, and every key frame resets the whole plan,
488 /// so no debt outlives one run.
489 fn replan(
490 &mut self,
491 level: Level,
492 slot: usize,
493 offset: i16,
494 frame_weight: f64,
495 actual_bytes: f64,
496 ) {
497 if level == Level::Key {
498 self.left_weight = self.run_weight;
499 self.left_bytes = self.run_bytes;
500 for plan in self.plans.iter_mut().flatten() {
501 plan.left = plan.weight;
502 }
503 }
504 self.left_weight -= frame_weight;
505 self.left_bytes -= actual_bytes;
506 if let Some(plan) = self
507 .plan_of(slot, offset)
508 .and_then(|i| self.plans[i].as_mut())
509 {
510 plan.left = (plan.left - frame_weight).max(0.0);
511 }
512 // The tail of a run is not re-planned: under a leaf's worth of weight
513 // left, the division is noise.
514 if self.left_weight <= 1.0 {
515 return;
516 }
517 // A BOUND level is held at what it measurably spends and its weight
518 // is taken out of the division, so the bytes it cannot spend land on
519 // the levels that can (and, at the ceiling, the other way round). The
520 // old code divided the whole remainder by the whole remaining weight,
521 // which handed the biggest share of the shortfall straight back to
522 // the level that had just failed to spend it -- at the default
523 // pyramid the hidden levels carry most of the run's weight, so most
524 // of the surplus evaporated there every frame.
525 // ABLATION (`EC_AV1_RL_NOREDIST=1`, this lane's before/after arm):
526 // the old division, whole remainder over whole remaining weight.
527 if std::env::var("EC_AV1_RL_NOREDIST").is_ok_and(|v| v == "1") {
528 let scale = (self.left_bytes / self.left_weight).max(0.0);
529 self.target = [scale * self.key_weight, scale, scale];
530 return;
531 }
532 let (mut bytes, mut weight) = (self.left_bytes, 0.0);
533 for plan in self.plans.iter().flatten() {
534 if plan.bound {
535 bytes -= plan.rate * plan.left;
536 } else {
537 weight += plan.left;
538 }
539 }
540 if weight <= 1.0 {
541 // Every movable level is spent: nothing left to re-solve over.
542 return;
543 }
544 let scale = (bytes / weight).clamp(
545 self.scale0 * Self::REPLAN_FLOOR,
546 self.scale0 * Self::REPLAN_CLAMP,
547 );
548 self.target = [scale * self.key_weight, scale, scale];
549 }
550}
551
552/// What [`Av1Encoder::new`] takes: geometry, rate, key-frame cadence and
553/// colour. `base_q_idx` is picked directly (0..=255, `crate::encode`'s own
554/// unit) rather than a bitrate — a bitrate control loop is not part of this
555/// lane's charter, and a caller that wants one can still derive a
556/// `base_q_idx` from its own target and set that field. A caller who wants
557/// [`RateTarget`]'s quality/size dials instead of picking `base_q_idx`
558/// itself uses [`Av1Encoder::with_rate_target`], which still starts from an
559/// `EncoderConfig` (its `base_q_idx` is the loop's seed/fallback for
560/// [`RateTarget::BytesPerFrame`], and is overwritten outright for the other
561/// two variants).
562#[derive(Debug, Clone, Copy)]
563pub struct EncoderConfig {
564 /// The picture's width in luma samples; must be even and nonzero.
565 pub width: usize,
566 /// The picture's height in luma samples; must be even and nonzero.
567 pub height: usize,
568 /// The quantizer index every frame is coded at (0..=255).
569 pub base_q_idx: u8,
570 /// Pictures between key frames, inclusive of the key frame itself: `1`
571 /// codes every picture as a key frame, `gop` codes picture `gop` (and
572 /// `2*gop`, ...) as a key frame and every other picture inter.
573 pub gop: usize,
574 /// The colour the sequence header signals.
575 pub colour: Colour,
576 /// `TileColsLog2` (spec 5.9.15): the frame is split into `1 <<
577 /// tile_cols_log2` uniformly spaced tile columns, each coded and
578 /// decodable on its own. `0` -- one tile column -- is the default and
579 /// is byte for byte the stream this encoder wrote before tiles existed.
580 pub tile_cols_log2: u32,
581 /// `TileRowsLog2`, the same down the rows.
582 pub tile_rows_log2: u32,
583}
584
585impl EncoderConfig {
586 /// A config at `width`x`height` with one tile, `gop` pictures between
587 /// key frames and no colour signalling -- what every caller that does
588 /// not care about tiles writes, so that adding a field here does not
589 /// rewrite them.
590 #[must_use]
591 pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self {
592 Self {
593 width,
594 height,
595 base_q_idx,
596 gop,
597 colour,
598 tile_cols_log2: 0,
599 tile_rows_log2: 0,
600 }
601 }
602}
603
604/// One coded picture: its OBUs, in the order a demuxer that just wants bytes
605/// on the wire can concatenate them, and the two things a muxer needs to
606/// know without parsing them back out.
607#[derive(Debug, Clone)]
608pub struct Packet {
609 /// A temporal delimiter, a sequence header and the frame OBU for a key
610 /// frame; a temporal delimiter and the frame OBU alone for an inter
611 /// frame (the sequence header is identical across a stream's key
612 /// frames, since only [`EncoderConfig`]'s own fields feed it, so it is
613 /// simplest to let every key frame carry its own copy rather than have
614 /// the facade special-case the first one).
615 pub data: Vec<u8>,
616 /// Whether this picture was coded as a key frame.
617 pub key: bool,
618 /// This picture's position in DISPLAY (presentation) order, starting at
619 /// 0 — a muxer's `pts` in picture units. Without a [`Pyramid`] this is
620 /// also the coding order and equals `dts`.
621 pub order: u64,
622 /// This packet's position in CODING (decode) order, starting at 0 — a
623 /// muxer's `dts` in packet units. With a [`Pyramid`] the hidden frame of
624 /// each mini-GOP is coded before the leaves it precedes in display order,
625 /// so `dts` and `order` diverge, and the `show_existing_frame` packet
626 /// that re-outputs the hidden frame carries the hidden frame's own
627 /// `order` with its own later `dts`.
628 pub dts: u64,
629 /// Which pyramid level this packet is.
630 pub level: Level,
631}
632
633/// One mini-GOP of a two-level coding pyramid, and the quantizer offsets its
634/// two levels are coded at. libaom's `gf_group` shape, cut down to the two
635/// levels this encoder's reference set can carry: the last picture of each
636/// mini-GOP is coded FIRST, hidden (`show_frame == 0`), as the group's
637/// `ALTREF_FRAME`, then the pictures before it are coded as shown leaves that
638/// may predict backward off it, and finally a `show_existing_frame` header
639/// re-outputs the hidden frame in its own display position.
640#[derive(Debug, Clone, Copy, PartialEq, Eq)]
641pub struct Pyramid {
642 /// Pictures per mini-GOP: the hidden frame is `mini_gop` pictures ahead
643 /// of the group's anchor, and `mini_gop - 1` leaves sit between them.
644 /// `1` would leave no leaf at all and is refused. It is the group size a
645 /// long run takes; the last group of a run is up to 1.5x it, since
646 /// [`group_target`] absorbs a tail shorter than half a group rather than
647 /// leaving one behind.
648 pub mini_gop: usize,
649 /// Added to `base_q_idx` for the hidden `ALTREF_FRAME` — negative, since
650 /// every leaf of the group predicts off it.
651 pub arf_q_offset: i16,
652 /// Added to `base_q_idx` for each shown leaf — positive, since nothing
653 /// predicts off a leaf but the next leaf.
654 pub leaf_q_offset: i16,
655 /// THE THIRD LEVEL, or `None` for the two-level pyramid: the offset a
656 /// second hidden frame, at the middle of the mini-GOP, is coded at
657 /// (between [`Pyramid::arf_q_offset`] and [`Pyramid::leaf_q_offset`], so
658 /// the group reads key -> top ARF -> mid ARF -> leaves). The leaves
659 /// before it name it as their `ALTREF_FRAME` and the leaves after it
660 /// start their chain from it, which halves every leaf's distance to its
661 /// nearest good reference. Ignored by a group of fewer than four
662 /// pictures, where there is no leaf on both sides of a midpoint.
663 pub mid_q_offset: Option<i16>,
664 /// THE FOURTH LEVEL, or `None` for the three-level pyramid: the offset
665 /// the two hidden QUARTER-POINT ARFs are coded at (between
666 /// [`Pyramid::mid_q_offset`] and [`Pyramid::leaf_q_offset`], so the group
667 /// reads key -> top ARF -> mid ARF -> quarter ARFs -> leaves). In a group
668 /// of eight they sit at pictures 2 and 6, halving again the distance from
669 /// a leaf to its nearest good reference; every leaf then names the
670 /// nearest hidden frame on each side. Ignored by a group with fewer than
671 /// seven leaves, where a quarter point has no leaf on both sides, and --
672 /// like the mid level -- by a run no longer than one mini-GOP.
673 pub quarter_q_offset: Option<i16>,
674 /// Added to `base_q_idx` for the GOP's KEY FRAME — negative, since every
675 /// frame of the run reads it, directly or through an ARF. The 48-frame
676 /// census (`lanes/census-longgop.md`) found ours coded at base q while
677 /// its own ARFs sat 32 steps finer, where rav1e (key 100 / arf 120 /
678 /// leaf 153) and libaom (63 / 95 / 163) both make the key the best frame
679 /// of the run and spend 22--37% of the stream on it against our 10--11%.
680 pub key_q_offset: i16,
681}
682
683/// How many pictures the mini-GOP now being collected takes, given how many
684/// are left in this run (the pictures before the next key frame) and the
685/// [`Pyramid::mini_gop`] shape.
686///
687/// A fixed `mini_gop` leaves a SHORT TAIL group whenever the run is not a
688/// multiple of it: a 12-picture GOP under `mini_gop` 8 codes 8 + 3, and that
689/// 3-picture tail is the expensive part -- the 12-frame gate preferred one
690/// group of 11 by 7.0 / 20.5 BD points while the 48-frame gate picked 8
691/// (lane-pyr4). The rule here ABSORBS a tail shorter than half a group into
692/// the group before it, so a run takes groups of `mini_gop` until at most
693/// 1.5 x `mini_gop` is left and then one final group of all of it:
694/// remaining 11 under 8 -> 11 (was 8 + 3)
695/// remaining 47 under 8 -> 8, 8, 8, 8, 8, 7 -- what the fixed rule already
696/// coded, so a long GOP is byte-identical
697/// (`the_mini_gop_layout_leaves_no_short_tail`; sweep `lanes/gopad.sweep.txt`).
698///
699/// `EC_AV1_GOP_LAYOUT=fixed` restores the old fixed-size rule for an A/B.
700fn group_target(remaining: usize, mini_gop: usize, absorb_tail: bool) -> usize {
701 match absorb_tail && remaining <= mini_gop + mini_gop / 2 {
702 true => remaining.max(1),
703 false => mini_gop,
704 }
705}
706
707/// How one GOP of `gop` pictures is actually coded, as [`Av1Encoder::encode_frames`]
708/// and [`Av1Encoder::drain_pending`] lay it out: the HIDDEN frames as
709/// `(q offset, count)` (the group's top `ALTREF`, the mid level and the two
710/// quarter-point ARFs, each at its own offset) and the number of shown
711/// leaves. The key frame is the remaining picture and is not listed.
712///
713/// This is what [`RateLoop::new`] prices the run by, so the two must agree on
714/// the gating rules -- a mid level needs three leaves and a run longer than
715/// 1.5 mini-GOPs, quarters need seven leaves and a mid -- which
716/// `the_rate_loop_prices_the_frames_the_pyramid_codes` pins against the real
717/// packet stream.
718fn gop_shape(p: Pyramid, gop: usize) -> (Vec<(i16, usize)>, usize) {
719 let (mut hidden, mut leaves) = (Vec::<(i16, usize)>::new(), 0usize);
720 let mut add = |offset: i16, n: usize| match hidden.iter_mut().find(|(o, _)| *o == offset) {
721 Some((_, c)) => *c += n,
722 None => hidden.push((offset, n)),
723 };
724 let long_run = gop > p.mini_gop + p.mini_gop / 2;
725 let mut left = gop.saturating_sub(1);
726 while left > 0 {
727 let g = group_target(left, p.mini_gop, absorb_tail()).min(left);
728 left -= g;
729 if g == 1 {
730 leaves += 1;
731 continue;
732 }
733 let inner = g - 1;
734 add(p.arf_q_offset, 1);
735 let mid = p.mid_q_offset.filter(|_| inner >= 3 && long_run);
736 let quarters = mid.and(p.quarter_q_offset).filter(|_| inner >= 7);
737 if let Some(o) = mid {
738 add(o, 1);
739 }
740 if let Some(o) = quarters {
741 add(o, 2);
742 }
743 leaves += inner - usize::from(mid.is_some()) - 2 * usize::from(quarters.is_some());
744 }
745 (hidden, leaves)
746}
747
748/// Whether this run absorbs a short tail group (the default) or cuts every
749/// mini-GOP at `mini_gop`: `EC_AV1_GOP_LAYOUT=fixed`, read once.
750fn absorb_tail() -> bool {
751 static ABSORB: std::sync::LazyLock<bool> = std::sync::LazyLock::new(|| {
752 std::env::var("EC_AV1_GOP_LAYOUT").ok().as_deref() != Some("fixed")
753 });
754 *ABSORB
755}
756
757impl Pyramid {
758 /// The pyramid a run asks for through the environment:
759 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>[:<mid>[:<key>]]]`,
760 /// where `<mid>` is the third level's offset or `off` for none, with
761 /// `0` (or anything that is not a mini-GOP of at least 2, e.g. `flat`)
762 /// meaning the flat one-picture-one-frame path. UNSET is
763 /// [`Pyramid::default`]: the pyramid is what
764 /// [`crate::encode::encode_sequence`], the BD gate and `ec-bench` code
765 /// under unless a run turns it off for an A/B.
766 #[must_use]
767 pub fn from_env() -> Option<Self> {
768 let d = Self::default();
769 let Some(spec) = std::env::var("EC_AV1_PYRAMID").ok() else {
770 return Some(d);
771 };
772 let mut f = spec.split(':');
773 let mini_gop: usize = f.next().and_then(|v| v.parse().ok()).unwrap_or(0);
774 if mini_gop < 2 {
775 return None;
776 }
777 Some(Self {
778 mini_gop,
779 arf_q_offset: f
780 .next()
781 .and_then(|v| v.parse().ok())
782 .unwrap_or(d.arf_q_offset),
783 leaf_q_offset: f
784 .next()
785 .and_then(|v| v.parse().ok())
786 .unwrap_or(d.leaf_q_offset),
787 // A fourth field is the mid-level offset; the literal `off` asks
788 // for the two-level pyramid at the same shape (the A/B arm the
789 // sweep needs), and no field at all keeps the default's.
790 mid_q_offset: match f.next() {
791 None => d.mid_q_offset,
792 Some("off") => None,
793 Some(v) => v.parse().ok().or(d.mid_q_offset),
794 },
795 // A fifth field is the key frame's own offset.
796 key_q_offset: f
797 .next()
798 .and_then(|v| v.parse().ok())
799 .unwrap_or(d.key_q_offset),
800 // A sixth field is the quarter level's offset, `off` for none.
801 quarter_q_offset: match f.next() {
802 None => d.quarter_q_offset,
803 Some("off") => None,
804 Some(v) => v.parse().ok().or(d.quarter_q_offset),
805 },
806 })
807 }
808}
809
810impl Default for Pyramid {
811 /// The best point of the offset sweep run through the BD gate's own
812 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` knob
813 /// (`encode::tests::bd_rate_vs_libaom_and_rav1e`, 12 frames of each of
814 /// the three gate clips, BD-rate vs libaom / vs rav1e, wall = the four
815 /// encodes of the ladder together).
816 ///
817 /// First sweep, before the motion-search lane merged (its extra-reference
818 /// `NEWMV` is exactly what a pyramid leaf needs to reach its hidden
819 /// frame), so read it for the OFFSETS, not for the verdict:
820 ///
821 /// | mini_gop:arf:leaf | 1080p | 2160p | screen |
822 /// |---|---|---|---|
823 /// | flat (no pyramid) | +122.7 / +73.4 | +147.3 / +98.5 | +79.4 / +17.2 |
824 /// | 4:0:0 | +152.2 / +97.9 | +214.7 / +158.1 | +91.4 / +26.2 |
825 /// | 4:-16:8 | +139.9 / +87.1 | +201.5 / +143.7 | +78.5 / +19.5 |
826 /// | 4:-24:12 | +141.3 / +85.0 | +190.0 / +132.9 | +84.5 / +22.8 |
827 /// | 2:0:0 | +149.3 / +93.1 | +203.0 / +149.4 | +88.3 / +23.6 |
828 /// | 2:-8:4 | +143.1 / +89.1 | +196.2 / +141.6 | +82.5 / +20.4 |
829 /// | 2:-16:8 | +137.6 / +84.5 | +187.2 / +130.6 | +84.9 / +23.1 |
830 ///
831 /// `0:0` is the worst row at both mini-GOP sizes and `-16/+8` buys 12-16
832 /// BD points over it, in the direction libaom's `gf_group` spends them
833 /// (lowest quantizer on the frame everything else predicts from). Those
834 /// are these defaults.
835 ///
836 /// Re-measured after that lane merged (wall ours, 1080p/2160p/screen):
837 ///
838 /// | arm | 1080p | 2160p | screen | wall |
839 /// |---|---|---|---|---|
840 /// | flat (no pyramid) | +121.1 / +71.8 | +146.1 / +97.5 | +79.3 / +17.2 | 6.3 / 5.8 / 6.2 s |
841 /// | 4:-16:8 | +131.9 / +81.1 | +178.7 / +123.6 | +78.4 / +19.5 | 6.2 / 5.6 / 5.5 s |
842 /// | 2:-16:8 | +125.4 / +76.2 | +173.0 / +119.5 | +84.9 / +23.1 | 6.2 / 5.6 / 6.2 s |
843 ///
844 /// So the pyramid still does NOT pay, and ships OFF: it wins 0.9 points
845 /// on screen capture at `4:-16:8` and loses 11 on 1080p and 33 on 2160p.
846 /// What keeps it from paying, in the order the numbers point at it:
847 ///
848 /// * The hidden frame predicts `mini_gop` pictures ahead of its own
849 /// reference with the SAME forward search a neighbouring frame gets,
850 /// and it is the largest frame in the group (73.8 kB of the 1080p
851 /// ladder's 184 kB at `4:-16:8`). On the 2160p clip, whose motion the
852 /// search only just reaches at distance 1, distance 4 is where it
853 /// falls off — that clip loses twice what 1080p does, and shrinking
854 /// the mini-GOP to 2 recovers most of the gap (+178.7 -> +173.0,
855 /// +131.9 -> +125.4). A distance-scaled search range is the fix, and
856 /// it lives in the motion-search lane, not here.
857 /// * The leaves reach the hidden frame through the extra-reference
858 /// modes only: `ALTREF_FRAME` wins about 13% of blocks
859 /// (`encode::take_ref_frame_hits`, printed by the round-trip test),
860 /// up from 4% before the motion lane merged. A compound
861 /// (`LAST` + `ALTREF`) prediction mode is the other half of what a
862 /// real B frame buys, and this crate codes no compound blocks at all.
863 ///
864 /// Neither is a defect in the pyramid itself: the reordering is exact
865 /// (`encoder::tests::a_pyramid_stream_decodes_in_display_order_through_both_decoders`
866 /// checks every shown frame in display order against ffmpeg AND our own
867 /// decoder, with the hidden frame proven to win blocks), and the
868 /// Re-measured a third time at NATIVE resolution (`encode::tests::
869 /// bd_rate_screen_native`, 1920x1024 crops, 12 frames, four quantizers,
870 /// BD-rate vs libaom / vs rav1e), because every earlier verdict was taken
871 /// on the 4x-downscaled gate (class `gate-recipe-confound`) and because
872 /// leaf compound and the distance-scaled search have landed since:
873 ///
874 /// | arm | film 1080p | film 2160p | screen |
875 /// |---|---|---|---|
876 /// | flat (no pyramid) | +18.7 / +1.4 | +48.1 / +19.8 | +59.4 / -10.0 |
877 /// | 4:-16:8 | +23.2 / +5.3 | +48.1 / +19.7 | +62.7 / -6.5 |
878 /// | 2:-16:8 | +24.9 / +6.9 | +46.9 / +19.5 | +69.0 / -3.8 |
879 /// | 8:-16:8 | +22.6 / +4.6 | +48.7 / +19.8 | +59.3 / -8.2 |
880 /// | 4:-24:12 (before the leaf-compound merge) | +24.3 / +6.3 | +48.5 / +20.2 | +67.2 / -3.7 |
881 ///
882 /// The confound was real -- at native the gap is 5 BD points, not 30 --
883 /// but the sign is not: no arm beats flat on both films, every arm costs
884 /// 4-6 points on 1080p, and the best 2160p arm (`2:-16:8`, -1.1 vs
885 /// libaom) pays +10 on screen. So the pyramid still ships OFF.
886 ///
887 /// A native offset sweep on the 2160p clip alone (mini-GOP 4) says the
888 /// offsets are not what is missing -- the whole 3x3 grid spans 2.9 BD
889 /// points and none of it reaches flat's +48.1:
890 ///
891 /// | arf \ leaf | +4 | +8 | +12 |
892 /// |---|---|---|---|
893 /// | -8 | +48.9 / +20.4 | +49.2 / +20.1 | +50.2 / +20.5 |
894 /// | -16 | +47.8 / +20.0 | +48.1 / +19.7 | +49.2 / +20.2 |
895 /// | -24 | +47.3 / +20.0 | +47.6 / +19.7 | +48.5 / +20.2 |
896 ///
897 /// The gradient is monotone in both knobs (deeper ARF better, shallower
898 /// leaf better), which is the shape of a group whose leaves cannot cash
899 /// in the ARF's extra quality: what the leaves reach the hidden frame
900 /// with is still one forward search per reference. Shrinking the mini-GOP
901 /// helps for the same reason (2:-16:8 is the only arm that beats flat on
902 /// any clip, and it beats it on the clip with the fastest motion).
903 ///
904 /// RE-SWEPT on lane-av1pyrgate, once the content gate below existed and
905 /// on the current defaults (`LAMBDA_SCALE` 0.0275, the 32x32 tx-depth
906 /// search and compound var-tx on): the earlier verdicts were taken with
907 /// the screen capture inside the arm, and it is the one clip a pyramid
908 /// never helps. With the gate, the screen row is the flat row by
909 /// construction, so the sweep is decided on the two real films
910 /// (`encode::tests::bd_rate_screen_native`, BD-rate vs libaom / vs
911 /// rav1e; bars are fixtures, recorded only):
912 ///
913 /// | arm | film A | film B | screen | bars 1080p | bars 2160p |
914 /// |---|---|---|---|---|---|
915 /// | flat (no pyramid) | +62.8 / +32.5 | +86.3 / +50.5 | +50.1 / -15.4 | +16.4 / -1.1 | +48.2 / +20.4 |
916 /// | 2:-16:8 | +60.3 / +29.1 | +83.6 / +50.2 | +50.1 / -15.4 | +24.0 / +5.9 | +47.2 / +20.2 |
917 /// | **4:-16:8** | **+54.1 / +24.2** | **+82.6 / +47.4** | +50.1 / -15.4 | +21.5 / +3.7 | +48.3 / +20.4 |
918 /// | 8:-16:8 | +55.9 / +25.8 | +83.6 / +47.3 | +50.1 / -15.4 | +19.8 / +2.0 | +48.7 / +20.4 |
919 /// | 4:-24:12 | +51.5 / +22.3 | +84.9 / +50.3 | +50.1 / -15.4 | +21.9 / +4.0 | +48.4 / +20.7 |
920 /// | 4:-12:6 | +57.6 / +27.1 | +84.8 / +49.3 | +50.1 / -15.4 | +21.7 / +3.9 | +48.8 / +20.9 |
921 ///
922 /// `4:-16:8` is the only arm that improves BOTH films on BOTH columns by
923 /// several points (-8.7 / -8.3 on film A, -3.7 / -3.1 on film B) and it
924 /// stays these defaults. `4:-24:12` buys another 2.6 on film A and gives
925 /// 2.3 back on film B (where it barely beats flat vs rav1e, -0.2), which
926 /// is the same "leaves cannot cash in the ARF's quality" shape as before,
927 /// now content-dependent rather than uniform. The screen column is
928 /// IDENTICAL in every arm -- that is the content gate, measured, not
929 /// asserted. `EC_AV1_LAMBDA=0.035` on top of `4:-16:8` was re-judged once
930 /// (the pyramid changes the reference structure): +54.5 / +24.5 and
931 /// +85.2 / +49.4, worse on both films, so 0.0275 stands.
932 ///
933 /// SHIPPED AS THE DEFAULT on lane-av1pyrdef. `4:-16:8` is what
934 /// [`crate::encode::encode_sequence`] (through
935 /// [`Av1Encoder::encode_sequence_pyramid`], the one mini-GOP driver both
936 /// paths run), the BD gates and `ec-bench` code a non-screen stream
937 /// under; a screen stream still codes flat, decided once per stream by
938 /// the content gate in [`Av1Encoder::encode_frames`]. `EC_AV1_PYRAMID=0`
939 /// restores the flat path everywhere for an A/B, and
940 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf>:<leaf>]` another shape of it
941 /// ([`Pyramid::from_env`]).
942 ///
943 /// [`Av1Encoder::new`] is unchanged: the one-picture-one-packet facade
944 /// entry point still codes flat, since a picture no longer maps to a
945 /// packet under a pyramid — [`Av1Encoder::with_pyramid`] plus
946 /// [`Av1Encoder::encode_frames`] is the streaming surface that reorders.
947 /// RE-SWEPT on lane-pyr3, on main 503d7aa9 -- `4:-16:8` was chosen when
948 /// the gate's "film" rows were still colour bars, and CfL, the luma
949 /// angle deltas, filter intra, the propagating tpl map and the rate-loop
950 /// step have all landed since (class `unswept decision constants`). The
951 /// axes were swept in the order mini-GOP first at the shipped offsets,
952 /// then both offset axes at the best mini-GOP, then the joint corners
953 /// (`encode::tests::bd_rate_screen_native`, BD-rate vs libaom / vs
954 /// rav1e; the bars rows move by at most 4 points across the WHOLE sweep
955 /// and decide nothing, the screen row is byte-identical in every arm
956 /// because the content gate codes it flat):
957 ///
958 /// | arm | film A | film B |
959 /// |---|---|---|
960 /// | flat (no pyramid) | +61.4 / +31.3 | +85.3 / +49.7 |
961 /// | 2:-16:8 | +59.2 / +28.1 | +82.3 / +49.1 |
962 /// | 4:-16:8 (was shipped) | +52.8 / +23.3 | +81.0 / +46.1 |
963 /// | 8:-16:8 | +54.3 / +24.4 | +81.8 / +45.8 |
964 /// | 16:-16:8 | +50.8 / +21.4 | +73.8 / +38.7 |
965 /// | 8:-8:8 | +58.0 / +27.5 | +83.3 / +46.5 |
966 /// | 8:-24:8 | +52.7 / +23.4 | +83.7 / +48.4 |
967 /// | 8:-32:8 | +52.3 / +23.1 | +86.8 / +51.9 |
968 /// | 8:-16:0 | +60.7 / +30.7 | +85.3 / +51.2 |
969 /// | 8:-16:4 | +57.6 / +27.4 | +84.1 / +48.6 |
970 /// | 8:-16:12 | +51.8 / +22.2 | +80.4 / +43.9 |
971 /// | 8:-16:16 | +50.1 / +20.5 | +80.6 / +43.4 |
972 /// | 16:-24:8 | +47.8 / +19.0 | +71.5 / +37.4 |
973 /// | 16:-16:12 | +48.0 / +18.9 | +71.1 / +35.7 |
974 /// | 16:-16:16 | +45.9 / +17.0 | +69.3 / +34.0 |
975 /// | 16:-24:12 | +45.6 / +17.0 | +70.2 / +35.6 |
976 /// | **16:-24:16** | **+44.2 / +15.7** | **+70.5 / +35.2** |
977 /// | 16:-32:16 | +43.6 / +15.2 | +71.2 / +36.2 |
978 /// | 16:-24:20 (past the swept range) | +42.9 / +14.5 | +70.8 / +34.9 |
979 /// | 16:-24:24 (past the swept range) | +42.6 / +14.1 | +71.3 / +35.7 |
980 ///
981 /// `16:-24:16` ships: it takes 8.6 / 7.6 points off film A and 10.5 /
982 /// 10.9 off film B against the old defaults, and every axis through it
983 /// is at or next to its own minimum. The two arms past the swept leaf
984 /// range were run because leaf `+16` was the range's edge and still
985 /// improving (class `instrument at bound`): film A keeps falling to
986 /// `+24` but film B turns back up at `+20`, so `+16` is where BOTH films
987 /// are minimal and the bound is not the answer. Deeper ARF is the same
988 /// shape -- `-32` buys 0.6 on film A and gives 0.7 back on film B.
989 ///
990 /// WHAT THAT SWEEP COULD NOT SAY, and the LONG-GOP sweep that answers it
991 /// (lane-pyr4, `lanes/pyr4.sweep.txt`). The table above is measured
992 /// against a gate that codes 12 frames with `gop = 12`, and a group is
993 /// cut at every key frame (`encode_frames`), so `16` there is really
994 /// "one hidden ARF per GOP" and ANY mini-GOP over 12 codes the same
995 /// stream (class `instrument at bound`). The user's exports are long
996 /// GOPs, so the shape is decided on
997 /// [`crate::encode::tests::bd_rate_film_long_gop`] -- 48 pictures, `gop
998 /// = 48`, the two real films, four quantizers, vs libaom `cpu-used 6`
999 /// and rav1e `speed=6` at the same key interval:
1000 ///
1001 /// | mini_gop:arf:leaf | film A vs libaom / rav1e | film B vs libaom / rav1e |
1002 /// |---|---|---|
1003 /// | 32:-24:16 | +79.0 / +29.8 | +164.4 / +58.8 |
1004 /// | 16:-24:16 (was the default) | +67.4 / +21.0 | +165.5 / +57.6 |
1005 /// | 8:-16:16 | +63.7 / +19.0 | +167.6 / +58.6 |
1006 /// | 4:-24:16 | +61.9 / +19.5 | +160.8 / +56.7 |
1007 /// | 8:-24:16 | +58.5 / +15.5 | +166.1 / +56.8 |
1008 /// | 8:-24:12 | +60.2 / +17.3 | +166.8 / +58.0 |
1009 /// | 8:-24:20 | +57.1 / +14.0 | +166.2 / +56.6 |
1010 /// | 8:-40:16 | +56.1 / +13.3 | +167.6 / +57.3 |
1011 /// | 8:-32:12 | +56.5 / +14.7 | +163.0 / +56.3 |
1012 /// | 8:-32:20 | +55.4 / +12.9 | +167.9 / +57.4 |
1013 /// | **8:-32:16** | **+55.7 / +13.5** | **+165.1 / +56.6** |
1014 ///
1015 /// `8:-32:16` ships: against the old `16:-24:16` it takes 11.7 / 7.5
1016 /// points off film A and 0.4 / 1.0 off film B -- all four columns down.
1017 /// A real 16- or 32-picture group is WORSE than an 8-picture one on film
1018 /// A once the GOP is long enough for the distinction to exist, which the
1019 /// 12-frame gate could not see; `4` was probed below the swept edge and
1020 /// turns back up on film A. ARF `-32` is an interior optimum (`-40`
1021 /// turns back on both films). The leaf axis has content-opposite optima
1022 /// (film A wants `20`, film B wants `12`, within 1.1 and 4.9 points) so
1023 /// `16` stays, being the only value down on all four columns.
1024 ///
1025 /// THE PRICE THAT WAS, and how it was paid (lane-gopad): on the
1026 /// SHORT-GOP gate (12 frames, `gop = 12`) a fixed mini-GOP of 8 split the
1027 /// run into 8 + 3 and read film A +51.2 / +21.4, film B +91.0 / +53.5,
1028 /// against `16:-24:16`'s +44.2 / +15.7 and +70.5 / +35.2 -- the tail
1029 /// group, not the shape, was the cost. [`group_target`] now absorbs a
1030 /// short tail, so the same 12 pictures code as ONE group of 11 and read
1031 /// film A +43.9 / +15.6 and film B +68.4 / +38.2 (three of the four
1032 /// columns better than `16:-24:16` ever was, film B vs rav1e 3.0 short),
1033 /// while 47 inter pictures still take 8 x 5 + 7 -- the long-GOP table
1034 /// above is coded byte for byte as it was measured.
1035 /// THE THIRD LEVEL (lane-pyr5, `lanes/pyr5.sweep.txt`), swept on the
1036 /// long-GOP gate against a control arm on this very head:
1037 ///
1038 /// | mini_gop:arf:leaf:mid | film A vs libaom / rav1e | film B vs libaom / rav1e |
1039 /// |---|---|---|
1040 /// | 8:-32:16 (control, 2-level) | +55.2 / +12.8 | +151.3 / +47.4 |
1041 /// | 8:-32:16:-4 | +51.8 / +11.4 | +146.2 / +45.4 |
1042 /// | **8:-32:16:-8** | **+52.1 / +11.7** | **+145.3 / +45.0** |
1043 /// | 8:-32:16:-16 | +53.4 / +13.0 | +146.0 / +46.1 |
1044 /// | 8:-32:20:-8 | +52.4 / +11.5 | +148.0 / +46.1 |
1045 /// | 16:-32:16:-8 | +55.0 / +12.3 | +146.0 / +44.3 |
1046 /// | 16:-32:16:-16 | +54.6 / +12.1 | +148.7 / +46.0 |
1047 /// | 4:-32:16:-8 | +61.7 / +20.4 | +147.5 / +51.3 |
1048 ///
1049 /// `-4` and `-8` are within a point of each other and split the two
1050 /// films; `-8` ships because film B is the wider gap. A mini-GOP of 4
1051 /// with a mid level -- rav1e's own shape at speed 6 -- is far worse here,
1052 /// so the third level is worth more than a shorter group, and the census
1053 /// (`lanes/census-longgop.md`) says why: at 8 pictures our leaves are
1054 /// already cheap and the bytes sit in the ARFs.
1055 ///
1056 /// The 12-frame gate keeps its numbers exactly (+43.9 / +15.6 and +68.4 /
1057 /// +38.2, byte-identical streams): a GOP that is one single mini-GOP does
1058 /// not code the third level at all (see `drain_pending`).
1059 /// THE LEAF OFFSET, RE-SWEPT ONCE THE ANCHORS MOVED (lane-arfq,
1060 /// `lanes/arfq.sweep.txt`). The table above chose `16` when the key frame
1061 /// still sat at the base quantizer; with [`Pyramid::key_q_offset`] at
1062 /// `-48` the whole run predicts off a much finer anchor and the leaves
1063 /// want to be finer with it. Long-GOP gate, control arm on the same head:
1064 ///
1065 /// | mini_gop:arf:leaf:mid:key | film A vs libaom / rav1e | film B vs libaom / rav1e |
1066 /// |---|---|---|
1067 /// | 8:-32:8:-8:-48 | +43.4 / +5.1 | +127.6 / +34.1 |
1068 /// | **8:-32:12:-8:-48** | **+43.1 / +4.6** | **+129.0 / +34.3** |
1069 /// | 8:-32:16:-8:-48 (control) | +43.5 / +4.6 | +131.3 / +35.0 |
1070 /// | 8:-32:24:-8:-48 | +45.6 / +5.6 | +138.8 / +38.4 |
1071 /// | 8:-32:12:-12:-48 | +43.4 / +5.0 | +128.1 / +33.8 |
1072 /// | 8:-32:12:-16:-48 | +44.0 / +5.6 | +127.7 / +34.1 |
1073 /// | 8:-24:12:-8:-48 | +44.5 / +5.2 | +128.6 / +33.3 |
1074 /// | 16:-32:12:-8:-48 | +47.2 / +6.3 | +134.7 / +35.6 |
1075 ///
1076 /// `12` ships: film B 2.3 / 0.7 down, film A 0.4 down against libaom and
1077 /// flat against rav1e. `8` is past the optimum (it buys film B and gives
1078 /// film A back), `24` is worse on all four. The other two axes were
1079 /// re-swept at `12` and did not move: a deeper mid (`-12`, `-16`) and a
1080 /// shallower ARF (`-24`) both trade film A away for film B, so the top
1081 /// ARF keeps its `-32` and the mid its `-8`. A 16-picture mini-GOP is
1082 /// worse on all four -- the pyramid has exactly three levels, so one mid
1083 /// frame cannot carry fifteen leaves.
1084 ///
1085 /// Unlike the third level this is NOT gated on GOP length: the 12-frame
1086 /// gate improves on every row too (film A +38.5 / +8.2 -> +37.5 / +7.6,
1087 /// film B +58.2 / +26.5 -> +54.1 / +23.9, both bars rows down, the screen
1088 /// capture byte-identical).
1089 fn default() -> Self {
1090 Self {
1091 mini_gop: 8,
1092 arf_q_offset: -32,
1093 leaf_q_offset: 12,
1094 mid_q_offset: MID_DEFAULT,
1095 key_q_offset: KEY_DEFAULT,
1096 quarter_q_offset: QUARTER_DEFAULT,
1097 }
1098 }
1099}
1100
1101/// Which level of the pyramid a coded frame sits at, reported on every
1102/// [`Packet`] so a caller (and the BD gate's histogram) can tell them apart
1103/// without parsing the frame headers back out.
1104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1105pub enum Level {
1106 /// A key frame.
1107 Key,
1108 /// A hidden `ALTREF_FRAME`, coded ahead of its display position.
1109 Arf,
1110 /// A shown leaf.
1111 Leaf,
1112 /// A `show_existing_frame` header re-outputting a hidden frame: no coded
1113 /// pixels at all, four bits of header.
1114 ShowExisting,
1115}
1116
1117/// The DPB slot the group anchors alternate between (see
1118/// [`Av1Encoder::encode_frames`]): the hidden frame of group `g` refreshes
1119/// `ANCHOR_SLOTS[(g + 1) % 2]`, which is the slot the leaves of group `g`
1120/// name as `ALTREF_FRAME` and which group `g + 1` reads as its own anchor.
1121/// Two slots alternate because a group's leaves must still be able to read
1122/// the previous anchor while the new one is already written.
1123const ANCHOR_SLOTS: [u8; 2] = [3, 4];
1124
1125/// The slot the leaf chain refreshes and reads as `LAST_FRAME`.
1126const LEAF_SLOT: u8 = 0;
1127
1128/// lane-last2: the two slots the leaf chain alternates its refresh between
1129/// once [`last2`] is on, so that the shown frame BEFORE `LAST_FRAME` is still
1130/// in the DPB and can be named `LAST2_FRAME`. Slot 7 is the one the key frame
1131/// writes and nothing has ever read back, so this costs no other level a slot;
1132/// leaf `k` refreshes `LEAF_SLOTS[k % 2]`, which is the slot leaf `k - 2`
1133/// wrote -- read before write, spec 7.20's decode order.
1134const LEAF_SLOTS: [u8; 2] = [LEAF_SLOT, 7];
1135
1136/// Whether the leaf chain retains that second past picture and offers it to
1137/// the block search as `LAST2_FRAME` (`EC_AV1_LAST2=0` / `=1`). The census
1138/// that priced the lever is `lanes/refs.report.md` §1; what it buys on the
1139/// gate is `lanes/last2.report.md`.
1140fn last2() -> bool {
1141 match LAST2_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
1142 0 => return false,
1143 1 => return true,
1144 _ => {}
1145 }
1146 match std::env::var("EC_AV1_LAST2").ok() {
1147 Some(v) => v != "0",
1148 None => LAST2,
1149 }
1150}
1151
1152/// A PROCESS-GLOBAL [`last2`] override that wins over the environment
1153/// (`u8::MAX` = unset), the shape `crate::encode::set_frame_interp` has --
1154/// this crate's tests never call `set_var` (`crate::envflags`), so the
1155/// witness turns the lever on through this while holding
1156/// [`crate::speed::knob_write`].
1157static LAST2_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
1158
1159/// Sets [`LAST2_OVERRIDE`]; `None` clears it.
1160#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
1161pub(crate) fn set_last2(on: Option<bool>) {
1162 LAST2_OVERRIDE.store(
1163 on.map_or(u8::MAX, u8::from),
1164 std::sync::atomic::Ordering::Relaxed,
1165 );
1166}
1167
1168/// [`last2`]'s default.
1169const LAST2: bool = false;
1170
1171/// The slot the mid-level hidden frame of a three-level group refreshes
1172/// ([`Pyramid::mid_q_offset`]): free of the two anchors (3, 4), of the leaf
1173/// chain (0) and of `GOLDEN_SLOT` (1), so all four levels are live at once.
1174const MID_SLOT: u8 = 2;
1175
1176/// The two slots the QUARTER-POINT hidden frames refresh
1177/// ([`Pyramid::quarter_q_offset`]). THE WHOLE SLOT MAP, with all four levels
1178/// live at once:
1179///
1180/// | slot | holds | written by | read as |
1181/// |---|---|---|---|
1182/// | 0 (`LEAF_SLOT`) | the previous shown leaf | every leaf | `LAST_FRAME` of the next leaf |
1183/// | 1 (`GOLDEN_SLOT`) | the key frame | the key | `GOLDEN_FRAME` everywhere |
1184/// | 2 (`MID_SLOT`) | the mid ARF | the mid ARF | `LAST_FRAME` / `ALTREF_FRAME` of the leaves and quarters around it |
1185/// | 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` |
1186/// | 5, 6 (`QUARTER_SLOTS`) | the first and second quarter ARF | the quarter ARFs | `LAST_FRAME` / `ALTREF_FRAME` of the leaves beside them |
1187/// | 7 | unused (the key's copy is never read back) | the key | -- |
1188///
1189/// A frame names exactly two of them plus `GOLDEN_SLOT`
1190/// ([`Av1Encoder::encode_pyramid_inter`] fills all seven `ref_frame_idx`
1191/// entries from `last_slot`/`altref_slot`), and `refresh_frame_flags` is the
1192/// single `self_slot` bit, so no level ever overwrites a slot another level
1193/// is still reading.
1194const QUARTER_SLOTS: [u8; 2] = [5, 6];
1195
1196/// [`Pyramid::default`]'s fourth level (`None` = the three-level pyramid).
1197/// The long-GOP sweep's winner (`lanes/pyr6.sweep.txt`).
1198const QUARTER_DEFAULT: Option<i16> = None;
1199
1200/// [`Pyramid::default`]'s third level (`None` = the two-level pyramid), the
1201/// long-GOP sweep's winner (`lanes/pyr5.sweep.txt`): every one of the four
1202/// long-GOP columns improves against the two-level shape, film B (the wider
1203/// gap) by 6.0 / 2.4 BD points.
1204const MID_DEFAULT: Option<i16> = Some(-8);
1205
1206/// [`Pyramid::default`]'s key-frame offset: the long-GOP sweep's winner
1207/// (`lanes/keyq.sweep.txt`, 48 pictures, gop 48, BD-rate vs libaom cpu-used 6
1208/// / vs rav1e speed 6), which the 12-frame gate agrees with, so it is NOT
1209/// gated on GOP length the way the third level is:
1210///
1211/// | key offset | film A (48) | film B (48) | film A (12) | film B (12) |
1212/// |---|---|---|---|---|
1213/// | 0 (base q) | +52.0 / +11.7 | +144.5 / +44.3 | +43.3 / +15.0 | +66.9 / +35.1 |
1214/// | -16 | +48.8 / +9.4 | +138.0 / +40.2 | | |
1215/// | -32 | +45.3 / +6.7 | +132.8 / +36.8 | | |
1216/// | -48 | +43.5 / +4.6 | +131.3 / +35.0 | +38.5 / +8.2 | +58.2 / +26.5 |
1217/// | -64 | +44.9 / +3.8 | +140.7 / +37.5 | | |
1218///
1219/// `-64` overshoots on film B, and a deeper ARF (`-40`) under the same key
1220/// gives bytes back on both films (+44.4 / +5.1, +137.4 / +38.6), so what the
1221/// group was short of is the ANCHOR, not more ARF. The bars rows move by
1222/// 0.3 / 0.6 BD points and the screen capture is byte-identical (its pyramid
1223/// is gated off).
1224const KEY_DEFAULT: i16 = -48;
1225
1226/// Whether the pyramid path hands each frame a lookahead window, i.e.
1227/// whether the temporal lambda map (`encode::tpl_lambda_factors`) runs on
1228/// the DEFAULT stream at all. It did not until lane-arfcen: the pyramid
1229/// reorders pictures, so this path passed `&[]` and the map -- measured and
1230/// shipped on the flat path -- was inert on every frame of every pyramid
1231/// stream, including the ARFs that carry 54% of a long-GOP stream's bytes
1232/// (class `tool disabled in every gate recipe`).
1233/// lane-arfpred: the top ARF source temporal filter's strength
1234/// ([`crate::speed::ARF_TF`]), `EC_AV1_ARF_TF=<strength>` overriding it;
1235/// `0` is off.
1236fn arf_tf_strength() -> f64 {
1237 std::env::var("EC_AV1_ARF_TF")
1238 .ok()
1239 .and_then(|v| v.parse().ok())
1240 .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF))
1241}
1242
1243/// lane-arftf: the same filter's strength on the MID ARF, whose own window
1244/// is the display-FUTURE leaves of its group (`tpl_window(at, false)`).
1245/// `EC_AV1_ARF_TF_MID=<strength>` overrides [`crate::speed::ARF_TF_MID`];
1246/// `0` is off.
1247fn arf_tf_mid_strength() -> f64 {
1248 std::env::var("EC_AV1_ARF_TF_MID")
1249 .ok()
1250 .and_then(|v| v.parse().ok())
1251 .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_MID))
1252}
1253
1254/// lane-arftf: how many of the window's pictures the filter averages in
1255/// ([`crate::speed::ARF_TF_WIN`], `EC_AV1_ARF_TF_WIN=<n>`). The top ARF's
1256/// window holds only DISPLAY-PAST neighbours -- it is the group's last
1257/// picture and the next group's sources are not buffered when it is coded --
1258/// so this widens the filter backwards only.
1259pub(crate) fn arf_tf_window() -> usize {
1260 std::env::var("EC_AV1_ARF_TF_WIN")
1261 .ok()
1262 .and_then(|v| v.parse().ok())
1263 .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_WIN))
1264}
1265
1266/// lane-lookahead: how many DISPLAY-FUTURE neighbours the top ARF's filter
1267/// takes out of the buffered next group ([`crate::speed::ARF_TF_WIN_FUT`],
1268/// `EC_AV1_ARF_TF_WIN_FUT=<n>`). Inert without [`lookahead`].
1269pub(crate) fn arf_tf_window_future() -> usize {
1270 match ARF_TF_FUT_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
1271 usize::MAX => {}
1272 n => return n,
1273 }
1274 std::env::var("EC_AV1_ARF_TF_WIN_FUT")
1275 .ok()
1276 .and_then(|v| v.parse().ok())
1277 .unwrap_or_else(|| crate::speed::at(&crate::speed::ARF_TF_WIN_FUT))
1278}
1279
1280/// PROCESS-GLOBAL overrides of the two lane-lookahead knobs, the shape
1281/// [`set_last2`] has (this crate's tests never call `set_var`); `u8::MAX` /
1282/// `usize::MAX` is unset, and a witness holds [`crate::speed::knob_write`]
1283/// while it uses them.
1284static LOOKAHEAD_OVERRIDE: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(u8::MAX);
1285static ARF_TF_FUT_OVERRIDE: std::sync::atomic::AtomicUsize =
1286 std::sync::atomic::AtomicUsize::new(usize::MAX);
1287static TPL_FUT_OVERRIDE: std::sync::atomic::AtomicUsize =
1288 std::sync::atomic::AtomicUsize::new(usize::MAX);
1289
1290/// Sets [`LOOKAHEAD_OVERRIDE`]; `None` clears it.
1291#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
1292pub(crate) fn set_lookahead(on: Option<bool>) {
1293 LOOKAHEAD_OVERRIDE.store(
1294 on.map_or(u8::MAX, u8::from),
1295 std::sync::atomic::Ordering::Relaxed,
1296 );
1297}
1298
1299/// Sets [`ARF_TF_FUT_OVERRIDE`]; `None` clears it.
1300#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
1301pub(crate) fn set_arf_tf_future(n: Option<usize>) {
1302 ARF_TF_FUT_OVERRIDE.store(
1303 n.unwrap_or(usize::MAX),
1304 std::sync::atomic::Ordering::Relaxed,
1305 );
1306}
1307
1308/// Sets [`TPL_FUT_OVERRIDE`]; `None` clears it.
1309#[allow(dead_code)] // set only from the `#[cfg(test)]` witness
1310pub(crate) fn set_tpl_fut(n: Option<usize>) {
1311 TPL_FUT_OVERRIDE.store(
1312 n.unwrap_or(usize::MAX),
1313 std::sync::atomic::Ordering::Relaxed,
1314 );
1315}
1316
1317/// lane-tplfut: which window the TOP ARF's temporal lambda map propagates
1318/// back through ([`crate::speed::TPL_FUT`], `EC_AV1_TPL_FUT=<n>`). Inert
1319/// without [`lookahead`] -- mode 0 is the shipped past window.
1320pub(crate) fn tpl_fut() -> usize {
1321 match TPL_FUT_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
1322 usize::MAX => {}
1323 n => return n,
1324 }
1325 std::env::var("EC_AV1_TPL_FUT")
1326 .ok()
1327 .and_then(|v| v.parse().ok())
1328 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_FUT))
1329}
1330
1331/// lane-tplhalf: mode 2's split -- how many display-PAST neighbours the top
1332/// ARF's window opens with, the rest of the budget coming from the buffered
1333/// future ([`crate::speed::TPL_FUT_HALF`], `EC_AV1_TPL_FUT_HALF=<n>`).
1334pub(crate) fn tpl_fut_half() -> usize {
1335 std::env::var("EC_AV1_TPL_FUT_HALF")
1336 .ok()
1337 .and_then(|v| v.parse().ok())
1338 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_FUT_HALF))
1339}
1340
1341/// lane-tplhalf: how many entries mode 2's window holds in total, `0` meaning
1342/// `tpl_depth() - 1` -- the ARF window's budget alone, so raising it does not
1343/// deepen every other frame's lambda pass the way `EC_AV1_TPL_D` does
1344/// ([`crate::speed::TPL_FUT_WIN`], `EC_AV1_TPL_FUT_WIN=<n>`).
1345pub(crate) fn tpl_fut_win(depth: usize) -> usize {
1346 match std::env::var("EC_AV1_TPL_FUT_WIN")
1347 .ok()
1348 .and_then(|v| v.parse().ok())
1349 .unwrap_or_else(|| crate::speed::at(&crate::speed::TPL_FUT_WIN))
1350 {
1351 0 => depth - 1,
1352 n => n,
1353 }
1354}
1355
1356/// lane-lookahead: whether the pyramid path holds one group of lookahead
1357/// ([`crate::speed::LOOKAHEAD`], `EC_AV1_LOOKAHEAD=0|1`).
1358fn lookahead() -> bool {
1359 match LOOKAHEAD_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
1360 0 => return false,
1361 1 => return true,
1362 _ => {}
1363 }
1364 match std::env::var("EC_AV1_LOOKAHEAD").ok() {
1365 Some(v) => v != "0",
1366 None => crate::speed::LOOKAHEAD,
1367 }
1368}
1369
1370fn tpl_pyramid() -> bool {
1371 match std::env::var("EC_AV1_TPL_PYRAMID").ok() {
1372 Some(v) => v != "0",
1373 None => TPL_PYRAMID,
1374 }
1375}
1376
1377/// [`tpl_pyramid`]'s default.
1378const TPL_PYRAMID: bool = true;
1379
1380/// Whether a group's TOP ARF names the ARF from TWO groups back as its own
1381/// `ALTREF_FRAME` (lane-arfcen). It has always named `GOLDEN_SLOT` there,
1382/// which for a top ARF is the key frame it already reads as `GOLDEN`, i.e.
1383/// its second reference is the same picture as its first for the first group
1384/// and adds nothing after: the ARF-vs-ARF census reads
1385/// `LAST@-8 GOLDEN@-8` on our first ARF where rav1e's reads two DISTINCT
1386/// anchors. The slot the ARF is about to refresh still holds that older
1387/// anchor while this frame is coded, so naming it costs no extra DPB slot.
1388fn arf_altref() -> bool {
1389 match std::env::var("EC_AV1_ARF_ALTREF").ok() {
1390 Some(v) => v != "0",
1391 None => ARF_ALTREF,
1392 }
1393}
1394
1395/// [`arf_altref`]'s default. ON since its long-GOP arm: film A
1396/// +42.8%/+4.5% -> +40.9%/+3.1% and film B +127.3%/+32.9% -> +125.6%/+32.0%
1397/// (BD vs libaom cpu-used 6 / vs rav1e speed 6), i.e. both films down on both
1398/// columns.
1399const ARF_ALTREF: bool = true;
1400
1401/// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per
1402/// [`Av1Encoder::encode`] call — or, with a [`Pyramid`] configured, a
1403/// coding-order burst of them per [`Av1Encoder::encode_frames`] call plus a
1404/// [`Av1Encoder::flush`] at the end of the stream.
1405#[derive(Debug)]
1406pub struct Av1Encoder {
1407 config: EncoderConfig,
1408 color_config: ColorConfig,
1409 /// The previous picture's own (padded, uncropped) reconstruction — what
1410 /// the next inter frame predicts from — or `None` right after a key
1411 /// frame's turn comes up again, where it is about to be replaced rather
1412 /// than read.
1413 reference: Option<Picture>,
1414 next_index: u64,
1415 /// `Some` only when constructed via
1416 /// [`Av1Encoder::with_rate_target`]`(_, RateTarget::BytesPerFrame(_))`;
1417 /// otherwise every picture is coded at `config.base_q_idx`, unchanged
1418 /// from before this field existed.
1419 rate_loop: Option<RateLoop>,
1420 /// This stream's decode-side per-frame state, owned here so `encode`
1421 /// keeps the public signature it had before the state stopped being
1422 /// thread-local. One per encoder, never per frame: several of its fields
1423 /// (the inter-frame inheritance guards) carry state ACROSS frames.
1424 fctx: crate::decode::FrameCtx,
1425 /// What the last coded frame stored into the reference slot the next
1426 /// inter frame reads (spec 7.20): the tables that frame's tile writer
1427 /// must start from, since the header leaves
1428 /// `disable_frame_end_update_cdf` off. `None` before the first frame.
1429 carried_cdfs: Option<Box<crate::encode::CdfSnapshot>>,
1430 /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`,
1431 /// which stays in DPB slot 1 until the next key frame refreshes it.
1432 golden: Option<Picture>,
1433 /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is
1434 /// about to refresh (`encode_inter_frame`'s 0/2 alternation).
1435 prev2: Option<Picture>,
1436 /// `Some` puts the encoder in pyramid mode: [`Av1Encoder::encode`] then
1437 /// refuses (a picture no longer maps to one packet) and the state below
1438 /// drives coding order.
1439 pyramid: Option<Pyramid>,
1440 /// The eight DPB slots, modelled exactly as the decoder does (spec 7.20):
1441 /// what picture each holds, the order hint it was coded at, and the CDF
1442 /// tables it stored. Only pyramid mode reads these; the flat path keeps
1443 /// `reference`/`golden`/`prev2` so its bytes are unchanged.
1444 dpb: [Option<DpbSlot>; 8],
1445 /// Pictures held back waiting for their mini-GOP's hidden frame.
1446 pending: Vec<(u64, Picture)>,
1447 /// lane-lookahead: the CLOSED group waiting for the next group's sources
1448 /// before it is coded, so its top ARF -- the group's last picture in
1449 /// display order -- has display-future neighbours available. Always empty
1450 /// with [`lookahead`] off.
1451 ready: Vec<(u64, Picture)>,
1452 /// The flat path's delay queue: pictures whose packets later calls
1453 /// return, each coded with the ones behind it as its lookahead window
1454 /// (lane-av1facade, deepened to [`crate::encode::tpl_depth`] - 1 on
1455 /// lane-av1tpl2). Unused in pyramid mode, which buffers in `pending`.
1456 held: std::collections::VecDeque<Picture>,
1457 /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its
1458 /// anchor.
1459 anchor: usize,
1460 /// lane-last2: the [`LEAF_SLOTS`] the last two SHOWN leaves refreshed,
1461 /// most recent first, across mini-GOP boundaries (the first leaf of a
1462 /// group reads the anchor as `LAST_FRAME`, so its `LAST2_FRAME` is the
1463 /// previous group's last leaf). Cleared by every key frame.
1464 leaf_hist: Vec<u8>,
1465 /// Coding-order position of the next packet — a packet's `dts`.
1466 next_dts: u64,
1467 /// Set by [`Av1Encoder::encode_sequence_pyramid`]: every coded frame's
1468 /// own cropped [`Encoded`] (its display position and its reconstruction),
1469 /// which is what [`crate::encode::EncodedSequence`] carries and a packet
1470 /// does not. `None` for every other caller, which pays nothing for it.
1471 collected: Option<Vec<(u64, Encoded)>>,
1472}
1473
1474/// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores
1475/// and what a `ref_frame_idx` entry reads back.
1476///
1477/// lane-av1enchang: the `CdfSnapshot` is BOXED, not held by value. Eight
1478/// inline copies made [`Av1Encoder`] 139960 bytes, and that struct is
1479/// returned by value through three nested `Result<Self>` constructors
1480/// ([`Av1Encoder::with_pyramid_and_rate_target`] ->
1481/// [`Av1Encoder::with_pyramid`] -> [`Av1Encoder::new`]), so an unoptimized
1482/// build put several of those on the stack at once: the pyramid path
1483/// overflowed libtest's 2 MiB test thread and aborted the whole crate suite
1484/// with `fatal runtime error: stack overflow`. One heap box per DPB slot
1485/// brings the struct from 139960 bytes down to 18168 (measured). The tables'
1486/// VALUES are untouched.
1487#[derive(Debug, Clone)]
1488struct DpbSlot {
1489 picture: Picture,
1490 order_hint: u32,
1491 cdfs: Box<crate::encode::CdfSnapshot>,
1492}
1493
1494/// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are
1495/// `Send` but `!Sync`): it can move to another thread, it just cannot be
1496/// shared by reference across threads.
1497const _: fn() = || {
1498 fn assert_send<T: Send>() {}
1499 assert_send::<Av1Encoder>();
1500};
1501
1502impl Av1Encoder {
1503 /// [`Av1Encoder::new`] at a SPEED PRESET (`speed` 0..=10, rav1e's scale:
1504 /// 0 is the full search this encoder has always run and is byte for byte
1505 /// identical to [`Av1Encoder::new`]; higher presets switch search levers
1506 /// off, [`crate::speed::levers`] naming which).
1507 ///
1508 /// The preset is process-global (the tile search reads it from worker
1509 /// threads -- see [`crate::speed`]), so it is set here for every encode
1510 /// that follows on this process, and two encoders at different speeds
1511 /// must not run concurrently. `EC_AV1_SPEED=<n>` is the same knob for a
1512 /// caller that does not construct the encoder itself.
1513 ///
1514 /// # Errors
1515 /// [`Av1Encoder::new`]'s.
1516 pub fn with_speed(config: EncoderConfig, speed: u8) -> Result<Self> {
1517 crate::speed::set_speed(speed);
1518 Self::new(config)
1519 }
1520
1521 /// # Errors
1522 /// Returns an error when `config.width`/`config.height` are zero, odd,
1523 /// or larger than the 16-bit frame size an AV1 sequence header carries,
1524 /// or when `config.gop` is zero (there would be no picture to code the
1525 /// next key frame from a cadence of).
1526 pub fn new(config: EncoderConfig) -> Result<Self> {
1527 if config.gop == 0 {
1528 return Err(Error::unsupported("AV1 encode", "gop must be at least 1"));
1529 }
1530 if config.base_q_idx == 0 {
1531 return Err(Error::unsupported(
1532 "AV1 encode",
1533 "base_q_idx 0 is lossless, which this encoder does not code",
1534 ));
1535 }
1536 // Validate the geometry the same way the picture-level entry points
1537 // do, before the first `encode()` call rather than only surfacing it
1538 // then.
1539 Picture::grey(config.width, config.height).check_even()?;
1540 // A tile is a whole number of superblocks, so a frame cannot carry
1541 // more tile columns (rows) than it has 64x64 superblocks across
1542 // (down) -- the header's own `max_log2_tile_cols` bound (spec
1543 // 5.9.15), refused here rather than at the first `encode()` call.
1544 let sb = if crate::encode::sb128_on() { 128 } else { 64 };
1545 let sb_cols = config.width.div_ceil(sb) as u32;
1546 let sb_rows = config.height.div_ceil(sb) as u32;
1547 let tiles = |log2: u32| 1u32.checked_shl(log2).unwrap_or(u32::MAX);
1548 let max_log2 = |n: u32| n.min(64).next_power_of_two().trailing_zeros();
1549 if config.tile_cols_log2 > max_log2(sb_cols) || config.tile_rows_log2 > max_log2(sb_rows) {
1550 return Err(Error::unsupported(
1551 "AV1 encode",
1552 format!(
1553 "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has",
1554 tiles(config.tile_cols_log2),
1555 tiles(config.tile_rows_log2)
1556 ),
1557 ));
1558 }
1559 Ok(Self {
1560 carried_cdfs: None,
1561 golden: None,
1562 prev2: None,
1563 color_config: config.colour.color_config(),
1564 config,
1565 reference: None,
1566 next_index: 0,
1567 rate_loop: None,
1568 fctx: crate::decode::FrameCtx::for_encoder(),
1569 pyramid: None,
1570 dpb: [const { None }; 8],
1571 pending: Vec::new(),
1572 ready: Vec::new(),
1573 held: std::collections::VecDeque::new(),
1574 anchor: 0,
1575 leaf_hist: Vec::new(),
1576 next_dts: 0,
1577 collected: None,
1578 })
1579 }
1580
1581 /// [`Av1Encoder::new`] in pyramid mode: pictures are coded out of display
1582 /// order, so a call to [`Av1Encoder::encode_frames`] returns zero, one or
1583 /// several packets and [`Av1Encoder::flush`] drains whatever is still
1584 /// held at the end of the stream. [`Av1Encoder::encode`]'s one-in-one-out
1585 /// contract cannot hold here and it returns an error instead; a caller
1586 /// that wants the old shape simply does not call this constructor.
1587 ///
1588 /// # Errors
1589 /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be
1590 /// left between the anchor and the hidden frame). A `mini_gop` above
1591 /// `config.gop` is clamped to the run before the next key frame.
1592 pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> {
1593 if pyramid.mini_gop < 2 {
1594 return Err(Error::unsupported(
1595 "AV1 encode",
1596 "a pyramid mini-GOP is at least 2 pictures",
1597 ));
1598 }
1599 let mut encoder = Self::new(config)?;
1600 encoder.pyramid = Some(pyramid);
1601 Ok(encoder)
1602 }
1603
1604 /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it,
1605 /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of
1606 /// `config.base_q_idx` being used as-is.
1607 ///
1608 /// # Errors
1609 /// Same as [`Av1Encoder::new`].
1610 pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> {
1611 let rate_loop = rate.into_loop(&mut config, None);
1612 let mut encoder = Self::new(config)?;
1613 encoder.rate_loop = rate_loop;
1614 Ok(encoder)
1615 }
1616
1617 /// [`Av1Encoder::with_pyramid`] and [`Av1Encoder::with_rate_target`] at
1618 /// once: the rate loop then keeps a separate quantizer per pyramid level,
1619 /// predicting each frame's size from the previous frame of its OWN level
1620 /// (a leaf and a hidden `ALTREF` differ by several times in size, so one
1621 /// shared predictor would swing the quantizer every frame).
1622 ///
1623 /// # Errors
1624 /// As both.
1625 pub fn with_pyramid_and_rate_target(
1626 mut config: EncoderConfig,
1627 pyramid: Pyramid,
1628 rate: RateTarget,
1629 ) -> Result<Self> {
1630 let rate_loop = rate.into_loop(&mut config, Some(pyramid));
1631 let mut encoder = Self::with_pyramid(config, pyramid)?;
1632 encoder.rate_loop = rate_loop;
1633 Ok(encoder)
1634 }
1635
1636 /// The [`Pyramid`] this stream is actually coding under: what
1637 /// [`Av1Encoder::with_pyramid`] asked for, or `None` once the content gate
1638 /// in [`Av1Encoder::encode_frames`] has dropped a screen-content stream
1639 /// back to the flat path. Meaningful after the first picture has been
1640 /// handed in.
1641 #[must_use]
1642 pub fn pyramid(&self) -> Option<Pyramid> {
1643 self.pyramid
1644 }
1645
1646 /// The coded (padded-to-64) frame size every picture in this stream is
1647 /// coded at — what a decoder allocates and what `ffprobe` reports.
1648 #[must_use]
1649 pub fn coded_size(&self) -> (usize, usize) {
1650 (
1651 self.config.width.next_multiple_of(SUPERBLOCK),
1652 self.config.height.next_multiple_of(SUPERBLOCK),
1653 )
1654 }
1655
1656 /// The display (render) size every frame header signals — [`EncoderConfig`]'s
1657 /// own `width`/`height`, always, whatever the coded size pads it to.
1658 #[must_use]
1659 pub fn display_size(&self) -> (usize, usize) {
1660 (self.config.width, self.config.height)
1661 }
1662
1663 /// Takes one picture and returns the PREVIOUS picture's packet, key or
1664 /// inter by this stream's `gop` cadence — the facade's one frame of
1665 /// latency (the picture just handed in is what the previous one is coded
1666 /// against as its lookahead). The FIRST call has no previous picture and
1667 /// returns a packet with an EMPTY `data` (its other fields are
1668 /// placeholders; test `data.is_empty()`), and the last picture's packet
1669 /// comes out of [`Av1Encoder::flush`] — so a caller that concatenates
1670 /// `data` in call order still gets the whole stream, provided it flushes
1671 /// at the end.
1672 ///
1673 /// # Errors
1674 /// Returns an error when `picture`'s size does not match
1675 /// [`EncoderConfig::width`]/[`EncoderConfig::height`], when the encoder
1676 /// was built by [`Av1Encoder::with_pyramid`] (which reorders pictures, so
1677 /// one call cannot return one packet), or under the same conditions
1678 /// [`crate::encode::encode_key_frame`]/[`crate::encode::encode_sequence`]
1679 /// do.
1680 pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {
1681 if self.pyramid.is_some() {
1682 return Err(Error::unsupported(
1683 "AV1 encode",
1684 "a pyramid stream reorders pictures -- use encode_frames()/flush()",
1685 ));
1686 }
1687 let mut packets = self.encode_frames(picture)?;
1688 Ok(packets.pop().unwrap_or(Packet {
1689 data: Vec::new(),
1690 key: false,
1691 order: 0,
1692 dts: 0,
1693 level: Level::Leaf,
1694 }))
1695 }
1696
1697 /// Takes one picture and returns every packet it completed, in coding
1698 /// order. Without a [`Pyramid`] that is one packet — the PREVIOUS
1699 /// picture's, since this one is its lookahead — and none at all on the
1700 /// first call; with one it is
1701 /// empty for most pictures and a whole mini-GOP's worth (the hidden
1702 /// frame, its leaves and the `show_existing_frame` that re-outputs it)
1703 /// for the picture that closes a group.
1704 ///
1705 /// # Errors
1706 /// As [`Av1Encoder::encode`], minus the pyramid refusal.
1707 pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {
1708 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
1709 // lane-split: the split census prints on every exit of this call when
1710 // armed, so no `return` path loses it; the counters are cumulative, so
1711 // the last table a run prints is that run's total.
1712 struct SplitCensusDump;
1713 impl Drop for SplitCensusDump {
1714 fn drop(&mut self) {
1715 if crate::encode::split_census_on() {
1716 crate::encode::dump_split_census();
1717 }
1718 if crate::encode::newmv_census_on() {
1719 crate::encode::dump_newmv_census();
1720 }
1721 }
1722 }
1723 // `then_some` would CONSTRUCT the guard eagerly and drop it when the
1724 // flag is off, which runs `Drop` -- and printed the census header on
1725 // every unarmed encode. `then` builds it only when armed.
1726 let _census = (crate::encode::split_census_on() || crate::encode::newmv_census_on())
1727 .then(|| SplitCensusDump);
1728 if (picture.width, picture.height) != (self.config.width, self.config.height) {
1729 return Err(Error::unsupported(
1730 "AV1 encode",
1731 format!(
1732 "picture is {}x{}, encoder is {}x{}",
1733 picture.width, picture.height, self.config.width, self.config.height
1734 ),
1735 ));
1736 }
1737 // THE CONTENT GATE (lane-av1pyrgate): the pyramid is for camera
1738 // material. A desktop capture is the one content class every pyramid
1739 // sweep measured WORSE under it, and it is exactly the class the
1740 // screen detector separates (`encode::screen_content`: 0/48 frames on
1741 // both real films, 48/48 on the OBS capture), so a stream whose first
1742 // picture reads as screen content drops back to the flat path and
1743 // codes byte for byte what it coded before the pyramid existed.
1744 //
1745 // Decided ONCE, on the first picture, not per mini-GOP: the flat path
1746 // keeps its references in `reference`/`golden`/`prev2` and the pyramid
1747 // path in `dpb`, so a switch after the first frame would read slots
1748 // the other path never filled. Per-GOP re-decision needs the two
1749 // reference sets kept in step first; the gate's own recipe codes one
1750 // GOP per stream, where the two are the same decision.
1751 if self.pyramid.is_some()
1752 && self.next_index == 0
1753 && crate::encode::picture_is_screen(picture)
1754 {
1755 self.pyramid = None;
1756 }
1757 let Some(pyramid) = self.pyramid else {
1758 // The delay queue: the pictures behind this one are the
1759 // lookahead window the one at its head is coded with, which is
1760 // what makes the facade's bytes identical to
1761 // `encode_sequence`'s (lane-av1facade, lane-av1tpl2).
1762 self.held.push_back(picture.clone());
1763 if self.held.len() < crate::encode::tpl_depth() {
1764 return Ok(Vec::new());
1765 }
1766 let previous = self.held.pop_front().expect("queue is over depth");
1767 let window: Vec<Picture> = self.held.iter().cloned().collect();
1768 return Ok(vec![self.encode_flat(&previous, &window)?]);
1769 };
1770 let order = self.next_index;
1771 self.next_index += 1;
1772 if order.is_multiple_of(self.config.gop as u64) {
1773 // A key frame closes whatever group is open (there is nothing for
1774 // its leaves to point forward at across the boundary) and then
1775 // restarts the pyramid from the key itself.
1776 let mut packets = self.drain_all(Some(picture))?;
1777 packets.push(self.encode_key(order, picture)?);
1778 return Ok(packets);
1779 }
1780 self.pending.push((order, picture.clone()));
1781 // The group closes on the size the LAYOUT gives it (which depends on
1782 // how many pictures are left before the next key frame, so no short
1783 // tail group is left behind), or early when the next picture would be
1784 // a key frame.
1785 let run_start = self.pending[0].0;
1786 let remaining = self.config.gop - (run_start % self.config.gop as u64) as usize;
1787 let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64);
1788 if self.pending.len() >= group_target(remaining, pyramid.mini_gop, absorb_tail())
1789 || next_is_key
1790 {
1791 return self.drain_pending();
1792 }
1793 Ok(Vec::new())
1794 }
1795
1796 /// Codes and returns every picture still held back — the last picture of
1797 /// a flat stream (which has no lookahead and is coded without one), or
1798 /// the tail of a pyramid stream whose last mini-GOP never filled up.
1799 /// Empty once there is nothing held.
1800 ///
1801 /// # Errors
1802 /// As [`Av1Encoder::encode_frames`].
1803 pub fn flush(&mut self) -> Result<Vec<Packet>> {
1804 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
1805 if !self.held.is_empty() {
1806 let mut packets = Vec::with_capacity(self.held.len());
1807 while let Some(previous) = self.held.pop_front() {
1808 let window: Vec<Picture> = self.held.iter().cloned().collect();
1809 packets.push(self.encode_flat(&previous, &window)?);
1810 }
1811 return Ok(packets);
1812 }
1813 self.drain_all(None)
1814 }
1815
1816 /// The flat path: one picture and its lookahead (the next source picture,
1817 /// `None` at the end of the stream) in, one packet out — the same inputs
1818 /// [`crate::encode::encode_sequence`] gives each of its inter frames, so
1819 /// the bytes are identical.
1820 fn encode_flat(&mut self, picture: &Picture, lookahead: &[Picture]) -> Result<Packet> {
1821 let render = (self.config.width, self.config.height);
1822 let padded = picture.padded_to(SUPERBLOCK);
1823 let is_key = self.next_index.is_multiple_of(self.config.gop as u64);
1824 let order = self.next_index;
1825 let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| {
1826 r.q_idx(if is_key { Level::Key } else { Level::Leaf }).max(1)
1827 });
1828
1829 let encoded: Encoded = if is_key {
1830 encode_key_frame_inner(
1831 &padded,
1832 base_q_idx,
1833 DEADZONE,
1834 &KEY_FRAME_MODES,
1835 split_blocks(),
1836 render,
1837 self.color_config,
1838 &self.fctx,
1839 )?
1840 } else {
1841 let reference = self.reference.as_ref().ok_or_else(|| {
1842 Error::unsupported(
1843 "AV1 encode",
1844 "an inter frame needs a previous reconstruction",
1845 )
1846 })?;
1847 encode_inter_frame(
1848 &padded,
1849 reference,
1850 base_q_idx,
1851 DEADZONE,
1852 order as u32,
1853 // The flat path's own slot plan, in order hints: the key frame
1854 // of the GOP this picture sits in is what `GOLDEN_FRAME`
1855 // names, and every reference but `ALTREF_FRAME` is the frame
1856 // just coded.
1857 crate::encode::flat_order_hints(
1858 order as u32 & 0x7f,
1859 (order - order % self.config.gop as u64) as u32 & 0x7f,
1860 self.prev2.is_some(),
1861 ),
1862 render,
1863 self.carried_cdfs.as_ref().map(|c| &c.0),
1864 self.golden.as_ref(),
1865 self.prev2.as_ref(),
1866 None,
1867 &self.fctx,
1868 None,
1869 &lookahead
1870 .iter()
1871 .map(|n| n.padded_to(SUPERBLOCK))
1872 .collect::<Vec<_>>(),
1873 )?
1874 };
1875
1876 self.carried_cdfs = Some(encoded.next_cdfs.clone());
1877 if is_key {
1878 self.golden = Some(encoded.reconstruction.clone());
1879 self.prev2 = None;
1880 } else {
1881 self.prev2 = self.reference.take();
1882 }
1883 self.reference = Some(encoded.reconstruction.clone());
1884 self.next_index += 1;
1885 let cropped = crop_encoded(&encoded, render.0, render.1);
1886 let level = if is_key { Level::Key } else { Level::Leaf };
1887 if let Some(rate_loop) = self.rate_loop.as_mut() {
1888 // The flat path codes every frame at the slot's own q, no offset.
1889 rate_loop.update(level, 0, i16::from(base_q_idx), cropped.stream.len());
1890 }
1891 Ok(self.packet(cropped.stream, is_key, order, level))
1892 }
1893
1894 /// THE SHARED MINI-GOP DRIVER: codes a whole sequence — one key frame
1895 /// then all inter, which is [`crate::encode::encode_sequence`]'s only
1896 /// shape — through this very facade, under `pyramid`, and hands back what
1897 /// that path returns. The two are byte-identical BY CONSTRUCTION rather
1898 /// than by a mirrored second implementation: there is one reordering,
1899 /// one DPB/slot policy and one set of per-level quantizer offsets, here
1900 /// (`encoder::tests::the_facade_codes_the_same_bytes_as_encode_sequence`
1901 /// still pins it, now over a pyramid sequence too).
1902 ///
1903 /// The content gate lives in [`Av1Encoder::encode_frames`] and applies
1904 /// unchanged, so a screen-content clip handed in here codes flat.
1905 ///
1906 /// `EncodedSequence::frames` comes back in DISPLAY order, one entry per
1907 /// source picture — the order the flat path's coding order happens to be,
1908 /// and the order every reader of it (the BD gate's sample-exactness
1909 /// assertions against a decoder's output) needs. `stream` stays in coding
1910 /// order, which is the order a decoder reads.
1911 ///
1912 /// # Errors
1913 /// As [`Av1Encoder::encode_frames`].
1914 pub(crate) fn encode_sequence_pyramid(
1915 pictures: &[Picture],
1916 base_q_idx: u8,
1917 pyramid: Pyramid,
1918 tiles: (u32, u32),
1919 ) -> Result<crate::encode::EncodedSequence> {
1920 let first = pictures.first().ok_or_else(|| {
1921 Error::unsupported("AV1 encode", "a sequence needs at least one picture")
1922 })?;
1923 let config = EncoderConfig {
1924 width: first.width,
1925 height: first.height,
1926 base_q_idx,
1927 // One key frame, at picture 0, and inter for the rest.
1928 gop: pictures.len().max(1),
1929 // `encode_sequence` writes an unspecified colour config.
1930 colour: Colour::Unspecified,
1931 tile_cols_log2: tiles.0,
1932 tile_rows_log2: tiles.1,
1933 };
1934 let mut encoder = Self::with_pyramid(config, pyramid)?;
1935 encoder.collected = Some(Vec::with_capacity(pictures.len()));
1936 let mut stream = Vec::new();
1937 for picture in pictures {
1938 for packet in encoder.encode_frames(picture)? {
1939 stream.extend_from_slice(&packet.data);
1940 }
1941 }
1942 for packet in encoder.flush()? {
1943 stream.extend_from_slice(&packet.data);
1944 }
1945 let mut collected = encoder.collected.take().expect("collecting");
1946 // Every source picture is coded exactly once, so a frame's display
1947 // order IS its index once the list is sorted by it.
1948 let coding_order: Vec<usize> = collected.iter().map(|(order, _)| *order as usize).collect();
1949 collected.sort_by_key(|(order, _)| *order);
1950 let frames: Vec<Encoded> = collected.into_iter().map(|(_, encoded)| encoded).collect();
1951 assert!(
1952 coding_order.iter().all(|&i| i < frames.len()),
1953 "a coded frame's display position is outside the sequence"
1954 );
1955 Ok(crate::encode::EncodedSequence {
1956 stream,
1957 frames,
1958 coding_order,
1959 })
1960 }
1961
1962 /// Stamps a packet with its display and coding positions and advances the
1963 /// coding-order clock.
1964 fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet {
1965 let dts = self.next_dts;
1966 self.next_dts += 1;
1967 Packet {
1968 data,
1969 key,
1970 order,
1971 dts,
1972 level,
1973 }
1974 }
1975
1976 /// Stores a coded frame into every DPB slot its `refresh_frame_flags`
1977 /// names (spec 7.20).
1978 fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) {
1979 let slot = DpbSlot {
1980 picture: encoded.reconstruction.clone(),
1981 order_hint,
1982 // `next_cdfs` is already a `Box<CdfSnapshot>` (lane-av1stacksweep),
1983 // so this is a pointer copy rather than a second boxing -- the
1984 // same fix lane-av1enchang made here, now that the producer hands
1985 // over a box instead of an inline 15232-byte `Cdfs`.
1986 cdfs: encoded.next_cdfs.clone(),
1987 };
1988 for &s in slots {
1989 self.dpb[s as usize] = Some(slot.clone());
1990 }
1991 }
1992
1993 /// Codes a key frame in pyramid mode: it refreshes all eight slots, so it
1994 /// becomes the anchor, the `GOLDEN_FRAME` and the CDF source for the
1995 /// whole GOP at once.
1996 fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> {
1997 let render = (self.config.width, self.config.height);
1998 let base = self
1999 .rate_loop
2000 .as_ref()
2001 .map_or(i16::from(self.config.base_q_idx), |r| {
2002 i16::from(r.q_idx(Level::Key))
2003 });
2004 let offset = self.pyramid.map_or(0, |p| p.key_q_offset);
2005 let base_q_idx = (base + offset).clamp(1, 255) as u8;
2006 let encoded = encode_key_frame_inner(
2007 &picture.padded_to(SUPERBLOCK),
2008 base_q_idx,
2009 DEADZONE,
2010 &KEY_FRAME_MODES,
2011 split_blocks(),
2012 render,
2013 self.color_config,
2014 &self.fctx,
2015 )?;
2016 self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0);
2017 self.anchor = 0;
2018 // Every leaf slot now holds the key frame, which `GOLDEN_FRAME`
2019 // already names: the chain starts empty again.
2020 self.leaf_hist.clear();
2021 let cropped = crop_encoded(&encoded, render.0, render.1);
2022 if let Some(rate_loop) = self.rate_loop.as_mut() {
2023 rate_loop.update(Level::Key, 0, base + offset, cropped.stream.len());
2024 }
2025 if let Some(collected) = self.collected.as_mut() {
2026 collected.push((order, cropped.clone()));
2027 }
2028 Ok(self.packet(cropped.stream, true, order, Level::Key))
2029 }
2030
2031 /// Codes one inter frame at `order` from the DPB, in coding order.
2032 #[allow(clippy::too_many_arguments)]
2033 fn encode_pyramid_inter(
2034 &mut self,
2035 order: u64,
2036 picture: &Picture,
2037 last_slot: u8,
2038 self_slot: u8,
2039 altref_slot: u8,
2040 // lane-last2: the slot read as `LAST2_FRAME`. `None` -- and any slot
2041 // holding no picture, or the same one `LAST_FRAME` reads -- leaves
2042 // the reference set exactly as it was before this lane.
2043 last2_slot: Option<u8>,
2044 show_frame: bool,
2045 level: Level,
2046 // The quantizer offset comes from the CALLER, not from `level`: a
2047 // three-level group codes two `Level::Arf` frames (the group's top
2048 // ARF and the mid one) at different offsets, and they share the
2049 // rate-control slot but not the offset.
2050 offset: i16,
2051 // The lookahead window this frame's temporal lambda map is built
2052 // from, already padded (lane-arfcen). Empty codes the frame at one
2053 // lambda, which is what the whole pyramid path used to do.
2054 lookahead: &[Picture],
2055 // lane-lookahead: DISPLAY-FUTURE pictures for the SOURCE temporal
2056 // filter only (the top ARF's, out of the buffered next group), never
2057 // for the temporal lambda map -- keeping the filter's window and the
2058 // tpl window separate levers. Empty everywhere else.
2059 future: &[Picture],
2060 ) -> Result<Packet> {
2061 let render = (self.config.width, self.config.height);
2062 let order_hint = (order & 0x7f) as u32;
2063 let base = self
2064 .rate_loop
2065 .as_ref()
2066 .map_or(i16::from(self.config.base_q_idx), |r| {
2067 i16::from(r.q_idx(level))
2068 });
2069 let base_q_idx = (base + offset).clamp(1, 255) as u8;
2070 // lane-arfq: the top ARF of a mini-GOP is the hidden frame coded at
2071 // the pyramid's OWN `arf_q_offset` (the mid and quarter levels are
2072 // `Level::Arf` too but sit at their own offsets), and it is the level
2073 // the whole group predicts from -- so it reads its own `delta_q`
2074 // strength (`crate::speed::DQ_LEVEL_K`).
2075 let dq_level = match (show_frame, self.pyramid.map(|p| p.arf_q_offset)) {
2076 (true, _) => crate::encode::DqLevel::Leaf,
2077 (false, Some(arf)) if arf == offset => crate::encode::DqLevel::TopArf,
2078 (false, _) => crate::encode::DqLevel::MidArf,
2079 };
2080 // spec 5.9.2's `ref_frame_sign_bias`, derived from what the slots
2081 // this frame names actually hold: a reference whose order hint is
2082 // AHEAD of this frame's is backward-biased, and the MV stack scans
2083 // (writer and decoder alike) flip borrowed candidates across the
2084 // boundary. Only `ALTREF_FRAME` can be ahead here — the leaves of a
2085 // mini-GOP name the group's hidden frame there.
2086 let mut sign_bias = crate::mvstack::NO_SIGN_BIAS;
2087 let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| {
2088 dpb[slot as usize]
2089 .as_ref()
2090 .is_some_and(|s| s.order_hint > order_hint)
2091 };
2092 // A LAST2 slot only counts when it holds a picture that is not the
2093 // one `LAST_FRAME` already names; otherwise the frame codes the
2094 // reference set it always did.
2095 let last2_slot = last2_slot.filter(|&s| s != last_slot && self.dpb[s as usize].is_some());
2096 let slots = [
2097 last_slot,
2098 last2_slot.unwrap_or(last_slot),
2099 last_slot,
2100 GOLDEN_SLOT,
2101 last_slot,
2102 last_slot,
2103 altref_slot,
2104 ];
2105 for (i, slot) in slots.into_iter().enumerate() {
2106 sign_bias[i] = ahead(slot, &self.dpb);
2107 }
2108 // The same seven slots' order hints, for `skipModeAllowed` (spec
2109 // 5.9.22) in the frame-header writer.
2110 let order_hints: [u32; 7] = slots.map(|slot| {
2111 self.dpb[slot as usize]
2112 .as_ref()
2113 .map_or(0, |s| s.order_hint & 0x7f)
2114 });
2115 let reference = self.dpb[last_slot as usize]
2116 .as_ref()
2117 .map(|s| s.picture.clone())
2118 .ok_or_else(|| {
2119 Error::unsupported(
2120 "AV1 encode",
2121 "an inter frame needs a previous reconstruction",
2122 )
2123 })?;
2124 let last2 =
2125 last2_slot.and_then(|s| self.dpb[s as usize].as_ref().map(|d| d.picture.clone()));
2126 let golden = self.dpb[GOLDEN_SLOT as usize]
2127 .as_ref()
2128 .map(|s| s.picture.clone());
2129 let altref = (altref_slot != GOLDEN_SLOT)
2130 .then(|| {
2131 self.dpb[altref_slot as usize]
2132 .as_ref()
2133 .map(|s| s.picture.clone())
2134 })
2135 .flatten();
2136 let start_cdfs = self.dpb[last_slot as usize]
2137 .as_ref()
2138 .map(|s| s.cdfs.0.clone());
2139 // lane-arfpred: the top ARF is coded from a TEMPORALLY FILTERED
2140 // source when `speed::ARF_TF` is non-zero -- the grain it would
2141 // otherwise spend its residual on is averaged out against the
2142 // group's own display neighbours (`lookahead`, already padded).
2143 let source = picture.padded_to(SUPERBLOCK);
2144 // ... and never at the very top of the quality range, where the
2145 // anchor's own quantizer has hit the rate loop's floor
2146 // ([`crate::speed::ARF_TF_QMIN`]).
2147 let tf = match dq_level {
2148 crate::encode::DqLevel::TopArf => arf_tf_strength(),
2149 // lane-arftf: the mid ARF gets its own strength -- its window is
2150 // the group's later leaves, i.e. the filter runs FORWARD there.
2151 crate::encode::DqLevel::MidArf => arf_tf_mid_strength(),
2152 crate::encode::DqLevel::Leaf => 0.0,
2153 };
2154 let tf = match base_q_idx >= crate::speed::ARF_TF_QMIN {
2155 true => tf,
2156 false => 0.0,
2157 };
2158 let source = match tf > 0.0 {
2159 true => {
2160 // lane-lookahead: the filter's window is sized HERE -- up to
2161 // `ARF_TF_WIN` display-past neighbours (nearest first) and
2162 // then the display-future ones the caller buffered.
2163 let window: Vec<Picture> = lookahead
2164 .iter()
2165 .take(arf_tf_window())
2166 .chain(future.iter())
2167 .cloned()
2168 .collect();
2169 crate::encode::arf_temporal_filter(&source, &window, tf)
2170 }
2171 false => source,
2172 };
2173 let encoded = encode_inter_frame(
2174 &source,
2175 &reference,
2176 base_q_idx,
2177 DEADZONE,
2178 order_hint,
2179 order_hints,
2180 render,
2181 start_cdfs.as_ref(),
2182 golden.as_ref(),
2183 altref.as_ref(),
2184 last2.as_ref(),
2185 &self.fctx,
2186 Some(crate::encode::PyramidFrame {
2187 last_slot,
2188 self_slot,
2189 altref_slot,
2190 last2_slot,
2191 show_frame,
2192 sign_bias,
2193 dq_level,
2194 }),
2195 // lane-arfcen: the group's own sources ARE this frame's window
2196 // (`tpl_window`); it was `&[]` here, which switched the temporal
2197 // lambda map off on every frame the default stream codes.
2198 lookahead,
2199 );
2200 // Name the pyramid position in any failure: an error out of the tile
2201 // writer or the filter search is otherwise indistinguishable between
2202 // the hidden frame and the leaves that read it.
2203 let encoded = encoded.map_err(|e| {
2204 Error::unsupported(
2205 "AV1 encode",
2206 format!(
2207 "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \
2208 altref {altref_slot}, last2 {last2_slot:?}, shown {show_frame}, golden {}, \
2209 altref pic {}): {e}",
2210 golden.is_some(),
2211 altref.is_some(),
2212 ),
2213 )
2214 })?;
2215 self.refresh(&[self_slot], &encoded, order_hint);
2216 let cropped = crop_encoded(&encoded, render.0, render.1);
2217 if let Some(rate_loop) = self.rate_loop.as_mut() {
2218 rate_loop.update(level, offset, base + offset, cropped.stream.len());
2219 }
2220 if let Some(collected) = self.collected.as_mut() {
2221 collected.push((order, cropped.clone()));
2222 }
2223 Ok(self.packet(cropped.stream, false, order, level))
2224 }
2225
2226 /// Closes the open mini-GOP. With the lookahead off that codes it
2227 /// straight away, which is byte for byte what this encoder did before
2228 /// lane-lookahead; with it on the open group takes the `ready` slot and
2229 /// the group ALREADY there is coded, with the open one's sources as its
2230 /// display-future window.
2231 fn drain_pending(&mut self) -> Result<Vec<Packet>> {
2232 if !lookahead() {
2233 let group = std::mem::take(&mut self.pending);
2234 return self.code_group(group, &[]);
2235 }
2236 let group = std::mem::take(&mut self.ready);
2237 let next = std::mem::take(&mut self.pending);
2238 let packets = self.code_group(group, &next);
2239 self.ready = next;
2240 packets
2241 }
2242
2243 /// Codes every group still buffered, in coding order -- what a key frame
2244 /// (`next` is the key picture, the last buffered group's own
2245 /// display-future) and the end of stream (`None`) both need. The tail
2246 /// group can be any length, down to the single picture `code_group`
2247 /// codes as one shown leaf.
2248 fn drain_all(&mut self, next: Option<&Picture>) -> Result<Vec<Packet>> {
2249 let tail: Vec<(u64, Picture)> = next
2250 .filter(|_| lookahead())
2251 .map(|p| vec![(self.next_index, p.clone())])
2252 .unwrap_or_default();
2253 let ready = std::mem::take(&mut self.ready);
2254 let pending = std::mem::take(&mut self.pending);
2255 let mut packets = self.code_group(ready, &pending)?;
2256 packets.extend(self.code_group(pending, &tail)?);
2257 Ok(packets)
2258 }
2259
2260 /// Codes one mini-GOP: its hidden frame first, then its leaves, then
2261 /// the `show_existing_frame` header that puts the hidden frame back in
2262 /// display order. `future` is the display-future sources the caller has
2263 /// buffered past this group (lane-lookahead), empty without a lookahead.
2264 fn code_group(
2265 &mut self,
2266 group: Vec<(u64, Picture)>,
2267 future: &[(u64, Picture)],
2268 ) -> Result<Vec<Packet>> {
2269 if group.is_empty() {
2270 return Ok(Vec::new());
2271 }
2272 let mut packets = Vec::with_capacity(group.len() + 1);
2273 // The lookahead window of the group's picture at index `pos`: the
2274 // display-order successors inside this group, or -- for the group's
2275 // top ARF, the last picture, whose successors are not buffered yet --
2276 // the leaves BEHIND it in reverse display order, which are exactly
2277 // the pictures that predict backward from it. Padded like the frame
2278 // itself, as `encode_inter_frame` wants it.
2279 let tpl_window = |pos: usize, back: bool| -> Vec<Picture> {
2280 let depth = crate::encode::tpl_depth();
2281 if !tpl_pyramid() || depth < 2 {
2282 return Vec::new();
2283 }
2284 let window: Vec<&Picture> = match back {
2285 false => group[pos + 1..].iter().map(|(_, p)| p).collect(),
2286 true => group[..pos].iter().rev().map(|(_, p)| p).collect(),
2287 };
2288 window
2289 .into_iter()
2290 .take(depth - 1)
2291 .map(|p| p.padded_to(SUPERBLOCK))
2292 .collect()
2293 };
2294 // lane-last2: the slot a frame reading `last_slot` as `LAST_FRAME`
2295 // names as `LAST2_FRAME` -- the most recent shown leaf that is not
2296 // the one it already reads. `None` with the lever off, or before two
2297 // distinct past pictures exist.
2298 let last2_of = |hist: &[u8], last_slot: u8| -> Option<u8> {
2299 last2()
2300 .then(|| hist.iter().copied().find(|&s| s != last_slot))
2301 .flatten()
2302 };
2303 let anchor_slot = ANCHOR_SLOTS[self.anchor];
2304 let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor];
2305 let (arf_order, arf_picture) = group.last().cloned().expect("non-empty");
2306 let pyramid = self.pyramid.expect("pyramid mode");
2307 if group.len() == 1 {
2308 // Nothing to predict backward, so no hidden frame: one shown leaf
2309 // that also becomes the next group's anchor.
2310 packets.push(self.encode_pyramid_inter(
2311 arf_order,
2312 &arf_picture,
2313 anchor_slot,
2314 next_anchor_slot,
2315 GOLDEN_SLOT,
2316 last2_of(&self.leaf_hist, anchor_slot),
2317 true,
2318 Level::Leaf,
2319 pyramid.leaf_q_offset,
2320 &tpl_window(0, false),
2321 &[],
2322 )?);
2323 self.anchor = 1 - self.anchor;
2324 return Ok(packets);
2325 }
2326 // lane-lookahead: the display-future half of the top ARF's temporal
2327 // filter window, padded like the frame itself. Empty when the
2328 // lookahead is off (`future` is then always empty) or when the filter
2329 // asks for no future neighbours, which is what keeps the default
2330 // stream byte-identical.
2331 let arf_future: Vec<Picture> = future
2332 .iter()
2333 .take(arf_tf_window_future())
2334 .map(|(_, p)| p.padded_to(SUPERBLOCK))
2335 .collect();
2336 // lane-tplfut: the top ARF's TEMPORAL LAMBDA window. Mode 0 (and any
2337 // mode with no buffered future picture) keeps the group's own
2338 // display-PAST sources, reversed -- the only window that exists
2339 // without a lookahead, and the one every measurement so far was
2340 // taken with. The other modes read the next group's sources, which
2341 // is the direction libaom's tpl looks at an ARF.
2342 // `n` of the buffered display-future sources, nearest first, padded
2343 // like the frame being coded.
2344 let arf_tpl_future = |n: usize| -> Vec<Picture> {
2345 future
2346 .iter()
2347 .take(n)
2348 .map(|(_, p)| p.padded_to(SUPERBLOCK))
2349 .collect()
2350 };
2351 let arf_tpl: Vec<Picture> = {
2352 let depth = crate::encode::tpl_depth();
2353 let past = || tpl_window(group.len() - 1, true);
2354 match (tpl_fut(), future.is_empty(), tpl_pyramid() && depth >= 2) {
2355 (_, _, false) => Vec::new(),
2356 (0, _, _) | (_, true, _) => past(),
2357 (1, _, _) => arf_tpl_future(depth - 1),
2358 // Half the budget each side (`EC_AV1_TPL_FUT_HALF=<n>`
2359 // moves the split), past first: the chain then has
2360 // ONE discontinuity in the middle (the coarse pass between
2361 // the nearest past and the nearest future neighbour spans the
2362 // whole group), which is the arm's known cost.
2363 (2, _, _) => {
2364 let budget = tpl_fut_win(depth);
2365 let mut w = past();
2366 w.truncate(tpl_fut_half().max(1));
2367 let room = budget.saturating_sub(w.len());
2368 w.extend(arf_tpl_future(room));
2369 w
2370 }
2371 // Mode 3 and anything above: the WHOLE buffered next group.
2372 (_, _, _) => arf_tpl_future(future.len()),
2373 }
2374 };
2375 // The group's top level: the last picture, hidden, off the anchor.
2376 packets.push(self.encode_pyramid_inter(
2377 arf_order,
2378 &arf_picture,
2379 anchor_slot,
2380 next_anchor_slot,
2381 // lane-arfcen: the slot this ARF refreshes still holds the ARF
2382 // from two groups back, so naming it here gives the frame a
2383 // SECOND, distinct past anchor instead of the key it already
2384 // reads as GOLDEN.
2385 match arf_altref() {
2386 true => next_anchor_slot,
2387 false => GOLDEN_SLOT,
2388 },
2389 // The ARF levels take no LAST2: the anchor pair already gives a
2390 // top ARF two distinct past anchors (`arf_altref`), and the mid
2391 // and quarter frames have only the one past anchor in the DPB.
2392 None,
2393 false,
2394 Level::Arf,
2395 pyramid.arf_q_offset,
2396 &arf_tpl,
2397 // lane-lookahead: the group's top ARF is its LAST picture in
2398 // display order, so every picture of the next group is a
2399 // display-future neighbour of it -- nearest first.
2400 &arf_future,
2401 )?);
2402 let leaves = group.len() - 1;
2403 // THE THIRD LEVEL: a second hidden frame at the middle of the leaf
2404 // run, coded off the anchor with the top ARF as its own backward
2405 // reference. It needs a leaf on both sides of it, so a group of
2406 // three or fewer stays two-level.
2407 //
2408 // AND IT NEEDS A RUN LONG ENOUGH TO AMORTISE IT: a GOP that is one
2409 // single mini-GOP (`group_target` absorbs a tail, so a 12-picture GOP
2410 // under `mini_gop` 8 is ONE group of 11) pays for the second hidden
2411 // frame out of eleven pictures and reads +2.8 BD points worse against
2412 // libaom on film B at every mid offset measured (-4: +71.1, -8:
2413 // +71.2, against the two-level +68.4), while the 48-picture GOP -- six
2414 // groups sharing the same machinery -- is 6.0 points BETTER. So the
2415 // third level is switched on by the RUN's length, not by the group's:
2416 // the same GOP-length dependence `group_target` itself was built for.
2417 let long_run = self.config.gop > pyramid.mini_gop + pyramid.mini_gop / 2;
2418 let mid = pyramid
2419 .mid_q_offset
2420 .filter(|_| leaves >= 3 && long_run)
2421 .map(|offset| {
2422 let at = (leaves - 1) / 2;
2423 (at, offset)
2424 });
2425 if let Some((at, offset)) = mid {
2426 let (order, picture) = group[at].clone();
2427 packets.push(self.encode_pyramid_inter(
2428 order,
2429 &picture,
2430 anchor_slot,
2431 MID_SLOT,
2432 next_anchor_slot,
2433 None,
2434 false,
2435 Level::Arf,
2436 offset,
2437 &tpl_window(at, false),
2438 &[],
2439 )?);
2440 }
2441 // THE FOURTH LEVEL: one hidden frame at the middle of each half of
2442 // the leaf run, so no leaf is more than one picture from a hidden
2443 // reference on either side -- the depth the references run (rav1e
2444 // speed 6 codes 23 hidden frames per 48 pictures, libaom four levels
2445 // per 16-picture group) and the lever three levels had run out of.
2446 // It hangs off the mid level, and it needs a leaf on both sides of
2447 // both quarter points, which a run of fewer than seven leaves cannot
2448 // give.
2449 let quarters = match (mid, pyramid.quarter_q_offset) {
2450 (Some((at, _)), Some(offset)) if leaves >= 7 => {
2451 Some(([(at - 1) / 2, (at + leaves) / 2], offset))
2452 }
2453 _ => None,
2454 };
2455 if let Some((at, offset)) = quarters {
2456 // The first quarter predicts forward off the group's anchor and
2457 // backward off the mid ARF; the second starts FROM the mid ARF
2458 // and reads the group's top ARF backward.
2459 for (i, &pos) in at.iter().enumerate() {
2460 let (order, picture) = group[pos].clone();
2461 let (last_slot, altref_slot) = match i {
2462 0 => (anchor_slot, MID_SLOT),
2463 _ => (MID_SLOT, next_anchor_slot),
2464 };
2465 packets.push(self.encode_pyramid_inter(
2466 order,
2467 &picture,
2468 last_slot,
2469 QUARTER_SLOTS[i],
2470 altref_slot,
2471 None,
2472 false,
2473 Level::Arf,
2474 offset,
2475 &tpl_window(pos, false),
2476 &[],
2477 )?);
2478 }
2479 }
2480 // Every hidden frame INSIDE the leaf run, by leaf index, in display
2481 // order: what a leaf reads forward (the nearest one behind it) and
2482 // backward (the nearest one ahead of it, the group's top ARF when
2483 // there is none).
2484 let mut inner: Vec<(usize, u8)> = Vec::new();
2485 if let Some((at, _)) = mid {
2486 inner.push((at, MID_SLOT));
2487 }
2488 if let Some((at, _)) = quarters {
2489 inner.extend(at.iter().zip(QUARTER_SLOTS).map(|(&at, slot)| (at, slot)));
2490 }
2491 inner.sort_unstable();
2492 let (seq, _) = crate::encode::key_frame_headers(
2493 self.config.width,
2494 self.config.height,
2495 self.config.base_q_idx,
2496 )?;
2497 let show_existing = |encoder: &mut Self, slot: u8, order: u64| -> Result<Packet> {
2498 let mut data = crate::obu::temporal_delimiter();
2499 data.extend_from_slice(&crate::frame::show_existing_frame_obu(&seq, slot)?);
2500 Ok(encoder.packet(data, false, order, Level::ShowExisting))
2501 };
2502 // The leaves, in display order, so every `show_existing_frame` lands
2503 // in its own display position. Each leaf names the nearest hidden
2504 // frame BEHIND it as `LAST_FRAME` (the group's anchor for the first
2505 // leaf, otherwise the previous leaf) and the nearest one AHEAD as
2506 // `ALTREF_FRAME` (the group's top ARF when none is closer).
2507 for (i, (order, picture)) in group[..leaves].iter().enumerate() {
2508 if let Some(&(_, slot)) = inner.iter().find(|(at, _)| *at == i) {
2509 let packet = show_existing(self, slot, *order)?;
2510 packets.push(packet);
2511 continue;
2512 }
2513 // The previous shown leaf's own slot: `LEAF_SLOT` with the
2514 // lever off, and with it on whichever of [`LEAF_SLOTS`] that leaf
2515 // refreshed.
2516 let prev_leaf = self.leaf_hist.first().copied().unwrap_or(LEAF_SLOT);
2517 let last_slot = match i {
2518 0 => anchor_slot,
2519 i => inner
2520 .iter()
2521 .find(|(at, _)| at + 1 == i)
2522 .map_or(prev_leaf, |&(_, slot)| slot),
2523 };
2524 // Alternate the refresh: this leaf takes the leaf slot the
2525 // PREVIOUS leaf did not, which is the one the leaf before that
2526 // wrote and which this frame may still read as `LAST2_FRAME`
2527 // (read before write).
2528 let self_slot = match last2() {
2529 true => LEAF_SLOTS
2530 .into_iter()
2531 .find(|&s| Some(s) != self.leaf_hist.first().copied())
2532 .unwrap_or(LEAF_SLOT),
2533 false => LEAF_SLOT,
2534 };
2535 let last2_slot = last2_of(&self.leaf_hist, last_slot);
2536 let altref_slot = inner
2537 .iter()
2538 .find(|(at, _)| *at > i)
2539 .map_or(next_anchor_slot, |&(_, slot)| slot);
2540 self.leaf_hist.insert(0, self_slot);
2541 self.leaf_hist.truncate(2);
2542 packets.push(self.encode_pyramid_inter(
2543 *order,
2544 picture,
2545 last_slot,
2546 self_slot,
2547 altref_slot,
2548 last2_slot,
2549 true,
2550 Level::Leaf,
2551 pyramid.leaf_q_offset,
2552 &tpl_window(i, false),
2553 &[],
2554 )?);
2555 }
2556 let packet = show_existing(self, next_anchor_slot, arf_order)?;
2557 packets.push(packet);
2558 self.anchor = 1 - self.anchor;
2559 Ok(packets)
2560 }
2561}
2562
2563#[cfg(test)]
2564pub(crate) mod tests;