forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBcbbd6e2Tahinli2 months ago2369 commits

encoder.rs2294 lines, 96.0 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 picture in, one [`Packet`] out, same contract as the repo's other
5//! software encoder shims (`shims/rusty_h264`'s `Encoder::try_encode`,
6//! "nothing is ever held back"): [`Av1Encoder::encode`] never buffers a
7//! picture past its own call, so there is no flush to drain. That contract
8//! still holds for every caller that does not opt into a coding pyramid;
9//! [`Av1Encoder::with_pyramid`] does reorder pictures, and such a stream is
10//! driven through [`Av1Encoder::encode_frames`] (zero or more packets per
11//! picture) and [`Av1Encoder::flush`] instead. Internally it
12//! is [`crate::encode::encode_key_frame_inner`] and
13//! [`crate::encode::encode_inter_frame`] driven by a small state machine —
14//! a key frame every `gop` pictures, an inter frame predicting from the
15//! previous picture's own reconstruction otherwise — which is the same core
16//! [`crate::encode::encode_sequence`] uses for its one-key-frame-then-all-inter
17//! case; both now share it rather than each padding/cropping/refreshing the
18//! reference on their own.
19
20use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig};
21use ec_core::{Error, Result};
22
23use crate::encode::{
24 Encoded, GOLDEN_SLOT, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame,
25 encode_key_frame_inner, split_blocks,
26};
27use crate::intra::KEY_FRAME_MODES;
28
29/// A quantizer step round to nearest: half a step either way costs the same
30/// rate, so this is the deadzone every facade-driven frame is coded with.
31/// (`crate::encode`'s public entry points take a caller-chosen deadzone
32/// instead; the facade has no field for it because nothing downstream of it
33/// picks one.)
34const DEADZONE: f64 = 0.5;
35
36/// The colour a played-back frame is transformed by, named at what a
37/// container/player picks a colour space from (spec 5.5.2's CICP triple plus
38/// range) rather than at the raw integers. `edith_replica`'s rav1e seat sets
39/// limited-range BT.709 or BT.601 (`export.rs:3494-3507`); this crate's
40/// pre-facade sequence header always wrote [`Colour::Unspecified`].
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub enum Colour {
43 /// `color_primaries`/`transfer_characteristics`/`matrix_coefficients` =
44 /// 1 (BT.709, H.273), studio range: consumer HD video's own space, and
45 /// the default a player assumes when nothing is signalled at all.
46 #[default]
47 Bt709Limited,
48 /// The same three fields = 6 (BT.601, H.273), studio range: SD video's
49 /// space.
50 Bt601Limited,
51 /// Every field = 2 ("unspecified", H.273): what this crate wrote before
52 /// any of this was configurable.
53 Unspecified,
54}
55
56impl Colour {
57 fn color_config(self) -> ColorConfig {
58 let (color_primaries, transfer_characteristics, matrix_coefficients) = match self {
59 Colour::Bt709Limited => (1, 1, 1),
60 Colour::Bt601Limited => (6, 6, 6),
61 Colour::Unspecified => (2, 2, 2),
62 };
63 ColorConfig {
64 bit_depth: 8,
65 mono_chrome: false,
66 num_planes: 3,
67 color_primaries,
68 transfer_characteristics,
69 matrix_coefficients,
70 // Every variant here is studio (limited) swing; a full-range
71 // variant would need its own name, not a fourth field on this
72 // enum, since a played-back frame's range is a property of the
73 // pictures fed in, not just a label.
74 color_range: false,
75 subsampling_x: 1,
76 subsampling_y: 1,
77 chroma_sample_position: ChromaSamplePosition::Unknown,
78 separate_uv_delta_q: false,
79 }
80 }
81}
82
83/// A quality/size targeting surface for callers who would rather not pick a
84/// `base_q_idx` themselves, oracled at CRF's own shape (a single "quality"
85/// dial that holds a stable perceptual level across content, `ffmpeg -crf`)
86/// since a from-scratch scheme is not this lane's charter to invent.
87/// [`Av1Encoder::with_rate_target`] is additive: [`EncoderConfig::base_q_idx`]
88/// keeps working exactly as before for every existing caller, this is a
89/// second, opt-in constructor.
90#[derive(Debug, Clone, Copy, PartialEq)]
91pub enum RateTarget {
92 /// Exactly `base_q_idx`, unchanged — the `EncoderConfig` field's own
93 /// value, for a caller that already has one.
94 QIndex(u8),
95 /// A CRF-like single dial, 0 (smallest/worst) to 100 (largest/best),
96 /// mapped to a fixed `base_q_idx` by the calibration in
97 /// `encode::tests::calibration_sweep_base_q_idx` (linear in `q_idx`
98 /// across the sweep's own 40..=240 span, since the measured bytes/PSNR
99 /// curve is close enough to log-linear there that a straight line is
100 /// the "simplest correct" fit this lane's charter asks for). No
101 /// per-frame feedback: one value, picked once at construction.
102 Quality(u8),
103 /// A closed loop that steers `base_q_idx` frame by frame to land each
104 /// coded frame near this many bytes, via [`RateLoop`] — see there for
105 /// the controller and its windup bound.
106 BytesPerFrame(u32),
107 /// A target BITRATE: the same closed loop, with the per-frame byte
108 /// target derived from `bits_per_second` and `frames_per_second`
109 /// (`bits_per_second / 8 / frames_per_second`), and — in pyramid mode —
110 /// split across the levels by their reference weight, since a hidden
111 /// `ALTREF` and a leaf differ by several times in size and one shared
112 /// predictor would swing the quantizer every frame.
113 Bitrate {
114 /// The stream's target bitrate.
115 bits_per_second: u32,
116 /// The frame rate the bitrate is spent at.
117 frames_per_second: f64,
118 },
119}
120
121impl RateTarget {
122 /// Applies this target to `config` and returns the closed loop it needs
123 /// (`None` for the two open-loop variants). `mini_gop` is `Some` in
124 /// pyramid mode, which is what makes the loop keep a quantizer per level.
125 fn into_loop(self, config: &mut EncoderConfig, mini_gop: Option<usize>) -> Option<RateLoop> {
126 let target_bytes = match self {
127 RateTarget::QIndex(q) => {
128 config.base_q_idx = q;
129 return None;
130 }
131 RateTarget::Quality(quality) => {
132 config.base_q_idx = quality_to_q_idx(quality);
133 return None;
134 }
135 RateTarget::BytesPerFrame(target_bytes) => f64::from(target_bytes),
136 RateTarget::Bitrate {
137 bits_per_second,
138 frames_per_second,
139 } => f64::from(bits_per_second) / 8.0 / frames_per_second.max(1.0),
140 };
141 Some(RateLoop::new(
142 target_bytes,
143 f64::from(config.base_q_idx),
144 mini_gop,
145 ))
146 }
147}
148
149/// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's
150/// span (`q_idx` 40 at `quality` 100 down to `q_idx` 240 at `quality` 0);
151/// `quality` above 100 clamps to the best point measured, matching a CRF
152/// dial's own saturating ends rather than extrapolating past calibrated
153/// data.
154fn quality_to_q_idx(quality: u8) -> u8 {
155 let quality = f64::from(quality.min(100));
156 (240.0 - quality * 2.0).round() as u8
157}
158
159/// How much of a mini-GOP's byte budget the hidden `ALTREF` frame is worth
160/// relative to one leaf: every leaf of the group predicts off it, so it is
161/// bought at roughly twice a leaf's size (libaom's `gf_group` spends its
162/// `ARF` the same way, through a lower quantizer rather than a byte target).
163const ARF_WEIGHT: f64 = 2.0;
164
165/// How much a key frame is worth relative to one leaf, same units.
166const KEY_WEIGHT: f64 = 3.0;
167
168/// The closed-loop controller behind [`RateTarget::BytesPerFrame`] and
169/// [`RateTarget::Bitrate`]: a proportional step on `base_q_idx`, sized from
170/// the calibration sweep's own log-linear slope (bytes roughly halve every
171/// ~45 `q_idx` steps there, i.e. `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped
172/// per frame. Pure proportional — no accumulated error term — is the windup
173/// bound itself ([[vorbis-rate-loop-windup]]'s class): the only state carried
174/// between frames is `q`, already clamped to `0..=255`, so a quiet lead-in
175/// cannot build a debt a later transient has to repay; each frame's step is
176/// bounded by `STEP_CLAMP` regardless of history.
177///
178/// In pyramid mode the state is kept PER LEVEL: each frame's size is
179/// predicted from the previous frame of its own level, against that level's
180/// own share of the budget, which is the whole "two-pass-free model" this
181/// encoder carries.
182#[derive(Debug, Clone, Copy)]
183struct RateLoop {
184 /// Byte target per level, indexed by [`RateLoop::slot`].
185 target: [f64; 3],
186 /// Quantizer per level, same index.
187 q: [f64; 3],
188 /// Whether the three slots are actually distinct (pyramid mode) or all
189 /// one shared controller (the flat path, unchanged from before levels
190 /// existed).
191 per_level: bool,
192}
193
194impl RateLoop {
195 /// The steepest a single frame is allowed to move `base_q_idx`, in
196 /// either direction — chosen so one wildly over/under-sized frame
197 /// (a scene cut, a black lead-in) nudges the next frame's quantizer
198 /// rather than slamming it to an extreme.
199 const STEP_CLAMP: f64 = 12.0;
200 /// The calibration sweep's own slope (see the struct doc), inverted to
201 /// convert a bytes ratio into a `q_idx` step.
202 const GAIN: f64 = 1.0 / 0.0154;
203
204 fn new(target_bytes: f64, start_q: f64, mini_gop: Option<usize>) -> Self {
205 let Some(m) = mini_gop.map(|m| m as f64) else {
206 return Self {
207 target: [target_bytes; 3],
208 q: [start_q; 3],
209 per_level: false,
210 };
211 };
212 // A group of `m` pictures gets `m * target_bytes`, split one
213 // `ARF_WEIGHT` share to the hidden frame and one each to the `m - 1`
214 // leaves, so the group's own average is the target exactly.
215 let share = target_bytes * m / (m - 1.0 + ARF_WEIGHT);
216 Self {
217 target: [target_bytes * KEY_WEIGHT, share * ARF_WEIGHT, share],
218 q: [start_q; 3],
219 per_level: true,
220 }
221 }
222
223 /// Which controller a level uses: one shared slot on the flat path, three
224 /// separate ones under a pyramid.
225 fn slot(&self, level: Level) -> usize {
226 if !self.per_level {
227 return 0;
228 }
229 match level {
230 Level::Key => 0,
231 Level::Arf => 1,
232 // A `show_existing_frame` packet codes no pixels and never
233 // reaches `update`; it shares the leaf slot so `q_idx` is total.
234 Level::Leaf | Level::ShowExisting => 2,
235 }
236 }
237
238 fn q_idx(&self, level: Level) -> u8 {
239 self.q[self.slot(level)].round().clamp(0.0, 255.0) as u8
240 }
241
242 /// Steers this level's `q` toward its own target from the frame's actual
243 /// coded size.
244 fn update(&mut self, level: Level, actual_bytes: usize) {
245 let slot = self.slot(level);
246 if self.target[slot] <= 0.0 || actual_bytes == 0 {
247 return;
248 }
249 let ratio = actual_bytes as f64 / self.target[slot];
250 let step = (ratio.ln() * Self::GAIN).clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP);
251 self.q[slot] = (self.q[slot] + step).clamp(0.0, 255.0);
252 }
253}
254
255/// What [`Av1Encoder::new`] takes: geometry, rate, key-frame cadence and
256/// colour. `base_q_idx` is picked directly (0..=255, `crate::encode`'s own
257/// unit) rather than a bitrate — a bitrate control loop is not part of this
258/// lane's charter, and a caller that wants one can still derive a
259/// `base_q_idx` from its own target and set that field. A caller who wants
260/// [`RateTarget`]'s quality/size dials instead of picking `base_q_idx`
261/// itself uses [`Av1Encoder::with_rate_target`], which still starts from an
262/// `EncoderConfig` (its `base_q_idx` is the loop's seed/fallback for
263/// [`RateTarget::BytesPerFrame`], and is overwritten outright for the other
264/// two variants).
265#[derive(Debug, Clone, Copy)]
266pub struct EncoderConfig {
267 /// The picture's width in luma samples; must be even and nonzero.
268 pub width: usize,
269 /// The picture's height in luma samples; must be even and nonzero.
270 pub height: usize,
271 /// The quantizer index every frame is coded at (0..=255).
272 pub base_q_idx: u8,
273 /// Pictures between key frames, inclusive of the key frame itself: `1`
274 /// codes every picture as a key frame, `gop` codes picture `gop` (and
275 /// `2*gop`, ...) as a key frame and every other picture inter.
276 pub gop: usize,
277 /// The colour the sequence header signals.
278 pub colour: Colour,
279 /// `TileColsLog2` (spec 5.9.15): the frame is split into `1 <<
280 /// tile_cols_log2` uniformly spaced tile columns, each coded and
281 /// decodable on its own. `0` -- one tile column -- is the default and
282 /// is byte for byte the stream this encoder wrote before tiles existed.
283 pub tile_cols_log2: u32,
284 /// `TileRowsLog2`, the same down the rows.
285 pub tile_rows_log2: u32,
286}
287
288impl EncoderConfig {
289 /// A config at `width`x`height` with one tile, `gop` pictures between
290 /// key frames and no colour signalling -- what every caller that does
291 /// not care about tiles writes, so that adding a field here does not
292 /// rewrite them.
293 #[must_use]
294 pub fn new(width: usize, height: usize, base_q_idx: u8, gop: usize, colour: Colour) -> Self {
295 Self {
296 width,
297 height,
298 base_q_idx,
299 gop,
300 colour,
301 tile_cols_log2: 0,
302 tile_rows_log2: 0,
303 }
304 }
305}
306
307/// One coded picture: its OBUs, in the order a demuxer that just wants bytes
308/// on the wire can concatenate them, and the two things a muxer needs to
309/// know without parsing them back out.
310#[derive(Debug, Clone)]
311pub struct Packet {
312 /// A temporal delimiter, a sequence header and the frame OBU for a key
313 /// frame; a temporal delimiter and the frame OBU alone for an inter
314 /// frame (the sequence header is identical across a stream's key
315 /// frames, since only [`EncoderConfig`]'s own fields feed it, so it is
316 /// simplest to let every key frame carry its own copy rather than have
317 /// the facade special-case the first one).
318 pub data: Vec<u8>,
319 /// Whether this picture was coded as a key frame.
320 pub key: bool,
321 /// This picture's position in DISPLAY (presentation) order, starting at
322 /// 0 — a muxer's `pts` in picture units. Without a [`Pyramid`] this is
323 /// also the coding order and equals `dts`.
324 pub order: u64,
325 /// This packet's position in CODING (decode) order, starting at 0 — a
326 /// muxer's `dts` in packet units. With a [`Pyramid`] the hidden frame of
327 /// each mini-GOP is coded before the leaves it precedes in display order,
328 /// so `dts` and `order` diverge, and the `show_existing_frame` packet
329 /// that re-outputs the hidden frame carries the hidden frame's own
330 /// `order` with its own later `dts`.
331 pub dts: u64,
332 /// Which pyramid level this packet is.
333 pub level: Level,
334}
335
336/// One mini-GOP of a two-level coding pyramid, and the quantizer offsets its
337/// two levels are coded at. libaom's `gf_group` shape, cut down to the two
338/// levels this encoder's reference set can carry: the last picture of each
339/// mini-GOP is coded FIRST, hidden (`show_frame == 0`), as the group's
340/// `ALTREF_FRAME`, then the pictures before it are coded as shown leaves that
341/// may predict backward off it, and finally a `show_existing_frame` header
342/// re-outputs the hidden frame in its own display position.
343#[derive(Debug, Clone, Copy, PartialEq, Eq)]
344pub struct Pyramid {
345 /// Pictures per mini-GOP: the hidden frame is `mini_gop` pictures ahead
346 /// of the group's anchor, and `mini_gop - 1` leaves sit between them.
347 /// `1` would leave no leaf at all and is refused.
348 pub mini_gop: usize,
349 /// Added to `base_q_idx` for the hidden `ALTREF_FRAME` — negative, since
350 /// every leaf of the group predicts off it.
351 pub arf_q_offset: i16,
352 /// Added to `base_q_idx` for each shown leaf — positive, since nothing
353 /// predicts off a leaf but the next leaf.
354 pub leaf_q_offset: i16,
355}
356
357impl Default for Pyramid {
358 /// The best point of the offset sweep run through the BD gate's own
359 /// `EC_AV1_PYRAMID=<mini_gop>[:<arf_q_offset>:<leaf_q_offset>]` knob
360 /// (`encode::tests::bd_rate_vs_libaom_and_rav1e`, 12 frames of each of
361 /// the three gate clips, BD-rate vs libaom / vs rav1e, wall = the four
362 /// encodes of the ladder together).
363 ///
364 /// First sweep, before the motion-search lane merged (its extra-reference
365 /// `NEWMV` is exactly what a pyramid leaf needs to reach its hidden
366 /// frame), so read it for the OFFSETS, not for the verdict:
367 ///
368 /// | mini_gop:arf:leaf | 1080p | 2160p | screen |
369 /// |---|---|---|---|
370 /// | flat (no pyramid) | +122.7 / +73.4 | +147.3 / +98.5 | +79.4 / +17.2 |
371 /// | 4:0:0 | +152.2 / +97.9 | +214.7 / +158.1 | +91.4 / +26.2 |
372 /// | 4:-16:8 | +139.9 / +87.1 | +201.5 / +143.7 | +78.5 / +19.5 |
373 /// | 4:-24:12 | +141.3 / +85.0 | +190.0 / +132.9 | +84.5 / +22.8 |
374 /// | 2:0:0 | +149.3 / +93.1 | +203.0 / +149.4 | +88.3 / +23.6 |
375 /// | 2:-8:4 | +143.1 / +89.1 | +196.2 / +141.6 | +82.5 / +20.4 |
376 /// | 2:-16:8 | +137.6 / +84.5 | +187.2 / +130.6 | +84.9 / +23.1 |
377 ///
378 /// `0:0` is the worst row at both mini-GOP sizes and `-16/+8` buys 12-16
379 /// BD points over it, in the direction libaom's `gf_group` spends them
380 /// (lowest quantizer on the frame everything else predicts from). Those
381 /// are these defaults.
382 ///
383 /// Re-measured after that lane merged (wall ours, 1080p/2160p/screen):
384 ///
385 /// | arm | 1080p | 2160p | screen | wall |
386 /// |---|---|---|---|---|
387 /// | flat (no pyramid) | +121.1 / +71.8 | +146.1 / +97.5 | +79.3 / +17.2 | 6.3 / 5.8 / 6.2 s |
388 /// | 4:-16:8 | +131.9 / +81.1 | +178.7 / +123.6 | +78.4 / +19.5 | 6.2 / 5.6 / 5.5 s |
389 /// | 2:-16:8 | +125.4 / +76.2 | +173.0 / +119.5 | +84.9 / +23.1 | 6.2 / 5.6 / 6.2 s |
390 ///
391 /// So the pyramid still does NOT pay, and ships OFF: it wins 0.9 points
392 /// on screen capture at `4:-16:8` and loses 11 on 1080p and 33 on 2160p.
393 /// What keeps it from paying, in the order the numbers point at it:
394 ///
395 /// * The hidden frame predicts `mini_gop` pictures ahead of its own
396 /// reference with the SAME forward search a neighbouring frame gets,
397 /// and it is the largest frame in the group (73.8 kB of the 1080p
398 /// ladder's 184 kB at `4:-16:8`). On the 2160p clip, whose motion the
399 /// search only just reaches at distance 1, distance 4 is where it
400 /// falls off — that clip loses twice what 1080p does, and shrinking
401 /// the mini-GOP to 2 recovers most of the gap (+178.7 -> +173.0,
402 /// +131.9 -> +125.4). A distance-scaled search range is the fix, and
403 /// it lives in the motion-search lane, not here.
404 /// * The leaves reach the hidden frame through the extra-reference
405 /// modes only: `ALTREF_FRAME` wins about 13% of blocks
406 /// (`encode::take_ref_frame_hits`, printed by the round-trip test),
407 /// up from 4% before the motion lane merged. A compound
408 /// (`LAST` + `ALTREF`) prediction mode is the other half of what a
409 /// real B frame buys, and this crate codes no compound blocks at all.
410 ///
411 /// Neither is a defect in the pyramid itself: the reordering is exact
412 /// (`encoder::tests::a_pyramid_stream_decodes_in_display_order_through_both_decoders`
413 /// checks every shown frame in display order against ffmpeg AND our own
414 /// decoder, with the hidden frame proven to win blocks), and the
415 /// quantizer offsets behave. Nothing selects the pyramid but an explicit
416 /// [`Av1Encoder::with_pyramid`] call (or `EC_AV1_PYRAMID` on the gate and
417 /// on `ec-bench`); the default one-in-one-out path is byte-identical to
418 /// before it existed.
419 fn default() -> Self {
420 Self {
421 mini_gop: 4,
422 arf_q_offset: -16,
423 leaf_q_offset: 8,
424 }
425 }
426}
427
428/// Which level of the pyramid a coded frame sits at, reported on every
429/// [`Packet`] so a caller (and the BD gate's histogram) can tell them apart
430/// without parsing the frame headers back out.
431#[derive(Debug, Clone, Copy, PartialEq, Eq)]
432pub enum Level {
433 /// A key frame.
434 Key,
435 /// A hidden `ALTREF_FRAME`, coded ahead of its display position.
436 Arf,
437 /// A shown leaf.
438 Leaf,
439 /// A `show_existing_frame` header re-outputting a hidden frame: no coded
440 /// pixels at all, four bits of header.
441 ShowExisting,
442}
443
444/// The DPB slot the group anchors alternate between (see
445/// [`Av1Encoder::encode_frames`]): the hidden frame of group `g` refreshes
446/// `ANCHOR_SLOTS[(g + 1) % 2]`, which is the slot the leaves of group `g`
447/// name as `ALTREF_FRAME` and which group `g + 1` reads as its own anchor.
448/// Two slots alternate because a group's leaves must still be able to read
449/// the previous anchor while the new one is already written.
450const ANCHOR_SLOTS: [u8; 2] = [3, 4];
451
452/// The slot the leaf chain refreshes and reads as `LAST_FRAME`.
453const LEAF_SLOT: u8 = 0;
454
455/// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per
456/// [`Av1Encoder::encode`] call — or, with a [`Pyramid`] configured, a
457/// coding-order burst of them per [`Av1Encoder::encode_frames`] call plus a
458/// [`Av1Encoder::flush`] at the end of the stream.
459#[derive(Debug)]
460pub struct Av1Encoder {
461 config: EncoderConfig,
462 color_config: ColorConfig,
463 /// The previous picture's own (padded, uncropped) reconstruction — what
464 /// the next inter frame predicts from — or `None` right after a key
465 /// frame's turn comes up again, where it is about to be replaced rather
466 /// than read.
467 reference: Option<Picture>,
468 next_index: u64,
469 /// `Some` only when constructed via
470 /// [`Av1Encoder::with_rate_target`]`(_, RateTarget::BytesPerFrame(_))`;
471 /// otherwise every picture is coded at `config.base_q_idx`, unchanged
472 /// from before this field existed.
473 rate_loop: Option<RateLoop>,
474 /// This stream's decode-side per-frame state, owned here so `encode`
475 /// keeps the public signature it had before the state stopped being
476 /// thread-local. One per encoder, never per frame: several of its fields
477 /// (the inter-frame inheritance guards) carry state ACROSS frames.
478 fctx: crate::decode::FrameCtx,
479 /// What the last coded frame stored into the reference slot the next
480 /// inter frame reads (spec 7.20): the tables that frame's tile writer
481 /// must start from, since the header leaves
482 /// `disable_frame_end_update_cdf` off. `None` before the first frame.
483 carried_cdfs: Option<crate::encode::CdfSnapshot>,
484 /// The last key frame's own (padded) reconstruction: `GOLDEN_FRAME`,
485 /// which stays in DPB slot 1 until the next key frame refreshes it.
486 golden: Option<Picture>,
487 /// The frame two back: `ALTREF_FRAME`, in the slot the next frame is
488 /// about to refresh (`encode_inter_frame`'s 0/2 alternation).
489 prev2: Option<Picture>,
490 /// `Some` puts the encoder in pyramid mode: [`Av1Encoder::encode`] then
491 /// refuses (a picture no longer maps to one packet) and the state below
492 /// drives coding order.
493 pyramid: Option<Pyramid>,
494 /// The eight DPB slots, modelled exactly as the decoder does (spec 7.20):
495 /// what picture each holds, the order hint it was coded at, and the CDF
496 /// tables it stored. Only pyramid mode reads these; the flat path keeps
497 /// `reference`/`golden`/`prev2` so its bytes are unchanged.
498 dpb: [Option<DpbSlot>; 8],
499 /// Pictures held back waiting for their mini-GOP's hidden frame.
500 pending: Vec<(u64, Picture)>,
501 /// Which of [`ANCHOR_SLOTS`] the group about to be coded reads as its
502 /// anchor.
503 anchor: usize,
504 /// Coding-order position of the next packet — a packet's `dts`.
505 next_dts: u64,
506}
507
508/// One decoded-picture-buffer slot: what a `refresh_frame_flags` bit stores
509/// and what a `ref_frame_idx` entry reads back.
510#[derive(Debug, Clone)]
511struct DpbSlot {
512 picture: Picture,
513 order_hint: u32,
514 cdfs: crate::encode::CdfSnapshot,
515}
516
517/// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are
518/// `Send` but `!Sync`): it can move to another thread, it just cannot be
519/// shared by reference across threads.
520const _: fn() = || {
521 fn assert_send<T: Send>() {}
522 assert_send::<Av1Encoder>();
523};
524
525impl Av1Encoder {
526 /// # Errors
527 /// Returns an error when `config.width`/`config.height` are zero, odd,
528 /// or larger than the 16-bit frame size an AV1 sequence header carries,
529 /// or when `config.gop` is zero (there would be no picture to code the
530 /// next key frame from a cadence of).
531 pub fn new(config: EncoderConfig) -> Result<Self> {
532 if config.gop == 0 {
533 return Err(Error::unsupported("AV1 encode", "gop must be at least 1"));
534 }
535 // Validate the geometry the same way the picture-level entry points
536 // do, before the first `encode()` call rather than only surfacing it
537 // then.
538 Picture::grey(config.width, config.height).check_even()?;
539 // A tile is a whole number of superblocks, so a frame cannot carry
540 // more tile columns (rows) than it has 64x64 superblocks across
541 // (down) -- the header's own `max_log2_tile_cols` bound (spec
542 // 5.9.15), refused here rather than at the first `encode()` call.
543 let sb_cols = config.width.div_ceil(64) as u32;
544 let sb_rows = config.height.div_ceil(64) as u32;
545 if (1u32 << config.tile_cols_log2) > sb_cols || (1u32 << config.tile_rows_log2) > sb_rows {
546 return Err(Error::unsupported(
547 "AV1 encode",
548 format!(
549 "{}x{} tiles need more than the {sb_cols}x{sb_rows} superblocks this frame has",
550 1 << config.tile_cols_log2,
551 1 << config.tile_rows_log2
552 ),
553 ));
554 }
555 Ok(Self {
556 carried_cdfs: None,
557 golden: None,
558 prev2: None,
559 color_config: config.colour.color_config(),
560 config,
561 reference: None,
562 next_index: 0,
563 rate_loop: None,
564 fctx: crate::decode::FrameCtx::new(),
565 pyramid: None,
566 dpb: [const { None }; 8],
567 pending: Vec::new(),
568 anchor: 0,
569 next_dts: 0,
570 })
571 }
572
573 /// [`Av1Encoder::new`] in pyramid mode: pictures are coded out of display
574 /// order, so a call to [`Av1Encoder::encode_frames`] returns zero, one or
575 /// several packets and [`Av1Encoder::flush`] drains whatever is still
576 /// held at the end of the stream. [`Av1Encoder::encode`]'s one-in-one-out
577 /// contract cannot hold here and it returns an error instead; a caller
578 /// that wants the old shape simply does not call this constructor.
579 ///
580 /// # Errors
581 /// As [`Av1Encoder::new`], plus a `mini_gop` below 2 (no leaf would be
582 /// left between the anchor and the hidden frame) or above `config.gop`
583 /// (the group would straddle a key frame).
584 pub fn with_pyramid(config: EncoderConfig, pyramid: Pyramid) -> Result<Self> {
585 if pyramid.mini_gop < 2 {
586 return Err(Error::unsupported(
587 "AV1 encode",
588 "a pyramid mini-GOP is at least 2 pictures",
589 ));
590 }
591 let mut encoder = Self::new(config)?;
592 encoder.pyramid = Some(pyramid);
593 Ok(encoder)
594 }
595
596 /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it,
597 /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of
598 /// `config.base_q_idx` being used as-is.
599 ///
600 /// # Errors
601 /// Same as [`Av1Encoder::new`].
602 pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> {
603 let rate_loop = rate.into_loop(&mut config, None);
604 let mut encoder = Self::new(config)?;
605 encoder.rate_loop = rate_loop;
606 Ok(encoder)
607 }
608
609 /// [`Av1Encoder::with_pyramid`] and [`Av1Encoder::with_rate_target`] at
610 /// once: the rate loop then keeps a separate quantizer per pyramid level,
611 /// predicting each frame's size from the previous frame of its OWN level
612 /// (a leaf and a hidden `ALTREF` differ by several times in size, so one
613 /// shared predictor would swing the quantizer every frame).
614 ///
615 /// # Errors
616 /// As both.
617 pub fn with_pyramid_and_rate_target(
618 mut config: EncoderConfig,
619 pyramid: Pyramid,
620 rate: RateTarget,
621 ) -> Result<Self> {
622 let rate_loop = rate.into_loop(&mut config, Some(pyramid.mini_gop));
623 let mut encoder = Self::with_pyramid(config, pyramid)?;
624 encoder.rate_loop = rate_loop;
625 Ok(encoder)
626 }
627
628 /// The coded (padded-to-64) frame size every picture in this stream is
629 /// coded at — what a decoder allocates and what `ffprobe` reports.
630 #[must_use]
631 pub fn coded_size(&self) -> (usize, usize) {
632 (
633 self.config.width.next_multiple_of(SUPERBLOCK),
634 self.config.height.next_multiple_of(SUPERBLOCK),
635 )
636 }
637
638 /// The display (render) size every frame header signals — [`EncoderConfig`]'s
639 /// own `width`/`height`, always, whatever the coded size pads it to.
640 #[must_use]
641 pub fn display_size(&self) -> (usize, usize) {
642 (self.config.width, self.config.height)
643 }
644
645 /// Encodes one picture, key or inter by this stream's `gop` cadence, and
646 /// returns its packet — always exactly one, never held back for a later
647 /// call.
648 ///
649 /// # Errors
650 /// Returns an error when `picture`'s size does not match
651 /// [`EncoderConfig::width`]/[`EncoderConfig::height`], when the encoder
652 /// was built by [`Av1Encoder::with_pyramid`] (which reorders pictures, so
653 /// one call cannot return one packet), or under the same conditions
654 /// [`crate::encode::encode_key_frame`]/[`crate::encode::encode_sequence`]
655 /// do.
656 pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {
657 if self.pyramid.is_some() {
658 return Err(Error::unsupported(
659 "AV1 encode",
660 "a pyramid stream reorders pictures -- use encode_frames()/flush()",
661 ));
662 }
663 let mut packets = self.encode_frames(picture)?;
664 Ok(packets.pop().expect("the flat path emits exactly one packet"))
665 }
666
667 /// Encodes one picture and returns every packet it completed, in coding
668 /// order. Without a [`Pyramid`] that is always exactly one packet and
669 /// this is [`Av1Encoder::encode`] with a `Vec` around it; with one it is
670 /// empty for most pictures and a whole mini-GOP's worth (the hidden
671 /// frame, its leaves and the `show_existing_frame` that re-outputs it)
672 /// for the picture that closes a group.
673 ///
674 /// # Errors
675 /// As [`Av1Encoder::encode`], minus the pyramid refusal.
676 pub fn encode_frames(&mut self, picture: &Picture) -> Result<Vec<Packet>> {
677 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
678 if (picture.width, picture.height) != (self.config.width, self.config.height) {
679 return Err(Error::unsupported(
680 "AV1 encode",
681 format!(
682 "picture is {}x{}, encoder is {}x{}",
683 picture.width, picture.height, self.config.width, self.config.height
684 ),
685 ));
686 }
687 let Some(pyramid) = self.pyramid else {
688 return Ok(vec![self.encode_flat(picture)?]);
689 };
690 let order = self.next_index;
691 self.next_index += 1;
692 if order.is_multiple_of(self.config.gop as u64) {
693 // A key frame closes whatever group is open (there is nothing for
694 // its leaves to point forward at across the boundary) and then
695 // restarts the pyramid from the key itself.
696 let mut packets = self.drain_pending()?;
697 packets.push(self.encode_key(order, picture)?);
698 return Ok(packets);
699 }
700 self.pending.push((order, picture.clone()));
701 // The group closes on its own size, or early when the next picture
702 // would be a key frame.
703 let next_is_key = (order + 1).is_multiple_of(self.config.gop as u64);
704 if self.pending.len() >= pyramid.mini_gop || next_is_key {
705 return self.drain_pending();
706 }
707 Ok(Vec::new())
708 }
709
710 /// Codes and returns every picture still held back — the tail of a stream
711 /// whose last mini-GOP never filled up. Empty (and cheap) for a stream
712 /// with no [`Pyramid`], which never holds a picture at all.
713 ///
714 /// # Errors
715 /// As [`Av1Encoder::encode_frames`].
716 pub fn flush(&mut self) -> Result<Vec<Packet>> {
717 crate::encode::arm_tiles(self.config.tile_cols_log2, self.config.tile_rows_log2);
718 self.drain_pending()
719 }
720
721 /// The pre-pyramid path, byte for byte: one picture in, one packet out.
722 fn encode_flat(&mut self, picture: &Picture) -> Result<Packet> {
723 let render = (self.config.width, self.config.height);
724 let padded = picture.padded_to(SUPERBLOCK);
725 let is_key = self.next_index.is_multiple_of(self.config.gop as u64);
726 let order = self.next_index;
727 let base_q_idx = self.rate_loop.as_ref().map_or(self.config.base_q_idx, |r| {
728 r.q_idx(if is_key { Level::Key } else { Level::Leaf })
729 });
730
731 let encoded: Encoded = if is_key {
732 encode_key_frame_inner(
733 &padded,
734 base_q_idx,
735 DEADZONE,
736 &KEY_FRAME_MODES,
737 split_blocks(),
738 render,
739 self.color_config,
740 &self.fctx,
741 )?
742 } else {
743 let reference = self.reference.as_ref().ok_or_else(|| {
744 Error::unsupported(
745 "AV1 encode",
746 "an inter frame needs a previous reconstruction",
747 )
748 })?;
749 encode_inter_frame(
750 &padded,
751 reference,
752 base_q_idx,
753 DEADZONE,
754 order as u32,
755 // The flat path's own slot plan, in order hints: the key frame
756 // of the GOP this picture sits in is what `GOLDEN_FRAME`
757 // names, and every reference but `ALTREF_FRAME` is the frame
758 // just coded.
759 crate::encode::flat_order_hints(
760 order as u32 & 0x7f,
761 (order - order % self.config.gop as u64) as u32 & 0x7f,
762 self.prev2.is_some(),
763 ),
764 render,
765 self.carried_cdfs.as_ref().map(|c| &c.0),
766 self.golden.as_ref(),
767 self.prev2.as_ref(),
768 &self.fctx,
769 None,
770 )?
771 };
772
773 self.carried_cdfs = Some(encoded.next_cdfs.clone());
774 if is_key {
775 self.golden = Some(encoded.reconstruction.clone());
776 self.prev2 = None;
777 } else {
778 self.prev2 = self.reference.take();
779 }
780 self.reference = Some(encoded.reconstruction.clone());
781 self.next_index += 1;
782 let cropped = crop_encoded(&encoded, render.0, render.1);
783 let level = if is_key { Level::Key } else { Level::Leaf };
784 if let Some(rate_loop) = self.rate_loop.as_mut() {
785 rate_loop.update(level, cropped.stream.len());
786 }
787 Ok(self.packet(cropped.stream, is_key, order, level))
788 }
789
790 /// Stamps a packet with its display and coding positions and advances the
791 /// coding-order clock.
792 fn packet(&mut self, data: Vec<u8>, key: bool, order: u64, level: Level) -> Packet {
793 let dts = self.next_dts;
794 self.next_dts += 1;
795 Packet {
796 data,
797 key,
798 order,
799 dts,
800 level,
801 }
802 }
803
804 /// Stores a coded frame into every DPB slot its `refresh_frame_flags`
805 /// names (spec 7.20).
806 fn refresh(&mut self, slots: &[u8], encoded: &Encoded, order_hint: u32) {
807 let slot = DpbSlot {
808 picture: encoded.reconstruction.clone(),
809 order_hint,
810 cdfs: encoded.next_cdfs.clone(),
811 };
812 for &s in slots {
813 self.dpb[s as usize] = Some(slot.clone());
814 }
815 }
816
817 /// Codes a key frame in pyramid mode: it refreshes all eight slots, so it
818 /// becomes the anchor, the `GOLDEN_FRAME` and the CDF source for the
819 /// whole GOP at once.
820 fn encode_key(&mut self, order: u64, picture: &Picture) -> Result<Packet> {
821 let render = (self.config.width, self.config.height);
822 let base_q_idx = self
823 .rate_loop
824 .as_ref()
825 .map_or(self.config.base_q_idx, |r| r.q_idx(Level::Key));
826 let encoded = encode_key_frame_inner(
827 &picture.padded_to(SUPERBLOCK),
828 base_q_idx,
829 DEADZONE,
830 &KEY_FRAME_MODES,
831 split_blocks(),
832 render,
833 self.color_config,
834 &self.fctx,
835 )?;
836 self.refresh(&[0, 1, 2, 3, 4, 5, 6, 7], &encoded, 0);
837 self.anchor = 0;
838 let cropped = crop_encoded(&encoded, render.0, render.1);
839 if let Some(rate_loop) = self.rate_loop.as_mut() {
840 rate_loop.update(Level::Key, cropped.stream.len());
841 }
842 Ok(self.packet(cropped.stream, true, order, Level::Key))
843 }
844
845 /// Codes one inter frame at `order` from the DPB, in coding order.
846 #[allow(clippy::too_many_arguments)]
847 fn encode_pyramid_inter(
848 &mut self,
849 order: u64,
850 picture: &Picture,
851 last_slot: u8,
852 self_slot: u8,
853 altref_slot: u8,
854 show_frame: bool,
855 level: Level,
856 ) -> Result<Packet> {
857 let render = (self.config.width, self.config.height);
858 let order_hint = (order & 0x7f) as u32;
859 let pyramid = self.pyramid.expect("pyramid mode");
860 let offset = match level {
861 Level::Arf => pyramid.arf_q_offset,
862 _ => pyramid.leaf_q_offset,
863 };
864 let base = self
865 .rate_loop
866 .as_ref()
867 .map_or(i16::from(self.config.base_q_idx), |r| {
868 i16::from(r.q_idx(level))
869 });
870 let base_q_idx = (base + offset).clamp(1, 255) as u8;
871 // spec 5.9.2's `ref_frame_sign_bias`, derived from what the slots
872 // this frame names actually hold: a reference whose order hint is
873 // AHEAD of this frame's is backward-biased, and the MV stack scans
874 // (writer and decoder alike) flip borrowed candidates across the
875 // boundary. Only `ALTREF_FRAME` can be ahead here — the leaves of a
876 // mini-GOP name the group's hidden frame there.
877 let mut sign_bias = crate::mvstack::NO_SIGN_BIAS;
878 let ahead = |slot: u8, dpb: &[Option<DpbSlot>; 8]| {
879 dpb[slot as usize]
880 .as_ref()
881 .is_some_and(|s| s.order_hint > order_hint)
882 };
883 let slots = [
884 last_slot, last_slot, last_slot, GOLDEN_SLOT, last_slot, last_slot, altref_slot,
885 ];
886 for (i, slot) in slots.into_iter().enumerate() {
887 sign_bias[i] = ahead(slot, &self.dpb);
888 }
889 // The same seven slots' order hints, for `skipModeAllowed` (spec
890 // 5.9.22) in the frame-header writer.
891 let order_hints: [u32; 7] = slots.map(|slot| {
892 self.dpb[slot as usize]
893 .as_ref()
894 .map_or(0, |s| (s.order_hint & 0x7f) as u32)
895 });
896 let reference = self.dpb[last_slot as usize]
897 .as_ref()
898 .map(|s| s.picture.clone())
899 .ok_or_else(|| {
900 Error::unsupported("AV1 encode", "an inter frame needs a previous reconstruction")
901 })?;
902 let golden = self.dpb[GOLDEN_SLOT as usize].as_ref().map(|s| s.picture.clone());
903 let altref = (altref_slot != GOLDEN_SLOT)
904 .then(|| self.dpb[altref_slot as usize].as_ref().map(|s| s.picture.clone()))
905 .flatten();
906 let start_cdfs = self.dpb[last_slot as usize].as_ref().map(|s| s.cdfs.0.clone());
907 let encoded = || -> Result<Encoded> { encode_inter_frame(
908 &picture.padded_to(SUPERBLOCK),
909 &reference,
910 base_q_idx,
911 DEADZONE,
912 order_hint,
913 order_hints,
914 render,
915 start_cdfs.as_ref(),
916 golden.as_ref(),
917 altref.as_ref(),
918 &self.fctx,
919 Some(crate::encode::PyramidFrame {
920 last_slot,
921 self_slot,
922 altref_slot,
923 show_frame,
924 sign_bias,
925 }),
926 ) }();
927 // Name the pyramid position in any failure: an error out of the tile
928 // writer or the filter search is otherwise indistinguishable between
929 // the hidden frame and the leaves that read it.
930 let encoded = encoded.map_err(|e| {
931 Error::unsupported(
932 "AV1 encode",
933 format!(
934 "{level:?} frame at order {order} (last slot {last_slot}, self {self_slot}, \
935 altref {altref_slot}, shown {show_frame}, golden {}, altref pic {}): {e}",
936 golden.is_some(),
937 altref.is_some(),
938 ),
939 )
940 })?;
941 self.refresh(&[self_slot], &encoded, order_hint);
942 let cropped = crop_encoded(&encoded, render.0, render.1);
943 if let Some(rate_loop) = self.rate_loop.as_mut() {
944 rate_loop.update(level, cropped.stream.len());
945 }
946 Ok(self.packet(cropped.stream, false, order, level))
947 }
948
949 /// Codes the open mini-GOP: its hidden frame first, then its leaves, then
950 /// the `show_existing_frame` header that puts the hidden frame back in
951 /// display order.
952 fn drain_pending(&mut self) -> Result<Vec<Packet>> {
953 if self.pending.is_empty() {
954 return Ok(Vec::new());
955 }
956 let group: Vec<(u64, Picture)> = std::mem::take(&mut self.pending);
957 let mut packets = Vec::with_capacity(group.len() + 1);
958 let anchor_slot = ANCHOR_SLOTS[self.anchor];
959 let next_anchor_slot = ANCHOR_SLOTS[1 - self.anchor];
960 let (arf_order, arf_picture) = group.last().cloned().expect("non-empty");
961 if group.len() == 1 {
962 // Nothing to predict backward, so no hidden frame: one shown leaf
963 // that also becomes the next group's anchor.
964 packets.push(self.encode_pyramid_inter(
965 arf_order,
966 &arf_picture,
967 anchor_slot,
968 next_anchor_slot,
969 GOLDEN_SLOT,
970 true,
971 Level::Leaf,
972 )?);
973 self.anchor = 1 - self.anchor;
974 return Ok(packets);
975 }
976 packets.push(self.encode_pyramid_inter(
977 arf_order,
978 &arf_picture,
979 anchor_slot,
980 next_anchor_slot,
981 GOLDEN_SLOT,
982 false,
983 Level::Arf,
984 )?);
985 for (i, (order, picture)) in group[..group.len() - 1].iter().enumerate() {
986 let last_slot = if i == 0 { anchor_slot } else { LEAF_SLOT };
987 packets.push(self.encode_pyramid_inter(
988 *order,
989 picture,
990 last_slot,
991 LEAF_SLOT,
992 next_anchor_slot,
993 true,
994 Level::Leaf,
995 )?);
996 }
997 let (seq, _) = crate::encode::key_frame_headers(
998 self.config.width,
999 self.config.height,
1000 self.config.base_q_idx,
1001 )?;
1002 let mut data = crate::obu::temporal_delimiter();
1003 data.extend_from_slice(&crate::frame::show_existing_frame_obu(
1004 &seq,
1005 next_anchor_slot,
1006 )?);
1007 packets.push(self.packet(data, false, arf_order, Level::ShowExisting));
1008 self.anchor = 1 - self.anchor;
1009 Ok(packets)
1010 }
1011}
1012
1013#[cfg(test)]
1014mod tests {
1015 use super::*;
1016 use std::process::{Command, Stdio};
1017
1018 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
1019 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
1020 /// aomenc gate decodes its stream through ffmpeg and is meaningless
1021 /// without it -- turns it into a hard failure. Without this the require
1022 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
1023 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
1024 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
1025 fn have_ffmpeg() -> bool {
1026 let present = Command::new("ffmpeg")
1027 .arg("-version")
1028 .stdout(Stdio::null())
1029 .stderr(Stdio::null())
1030 .status()
1031 .is_ok_and(|s| s.success());
1032 assert!(
1033 present
1034 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
1035 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
1036 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
1037 );
1038 present
1039 }
1040
1041 fn test_card(width: usize, height: usize, shift: usize) -> Picture {
1042 let mut picture = Picture::grey(width, height);
1043 for y in 0..height {
1044 for x in 0..width {
1045 let sx = (x + shift) % width;
1046 picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16;
1047 }
1048 }
1049 for y in 0..height / 2 {
1050 for x in 0..width / 2 {
1051 let i = y * (width / 2) + x;
1052 picture.u[i] = ((100 + shift * 4) % 256) as u16;
1053 picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16;
1054 }
1055 }
1056 picture
1057 }
1058
1059 /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
1060 /// in order.
1061 fn concat(packets: &[Packet]) -> Vec<u8> {
1062 packets.iter().flat_map(|p| p.data.clone()).collect()
1063 }
1064
1065 /// One call to [`Av1Encoder::encode`] returns exactly one packet, always
1066 /// — the facade's whole "nothing held back" contract, checked without
1067 /// ffmpeg since it is a property of the return type, not the bytes.
1068 #[test]
1069 fn one_in_one_out() {
1070 let config = EncoderConfig {
1071 width: 64,
1072 height: 64,
1073 base_q_idx: 100,
1074 gop: 2,
1075 colour: Colour::Bt709Limited,
1076 tile_cols_log2: 0,
1077 tile_rows_log2: 0,
1078 };
1079 let mut enc = Av1Encoder::new(config).unwrap();
1080 for t in 0..5u64 {
1081 let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
1082 assert!(!packet.data.is_empty(), "picture {t}: empty packet");
1083 assert_eq!(packet.order, t, "picture {t}: order");
1084 }
1085 }
1086
1087 /// A key frame every `gop` pictures, inter otherwise — checked against
1088 /// what the facade itself reports, and (below) against what `ffprobe`
1089 /// reads back out of the coded bytes.
1090 #[test]
1091 fn gop_cadence_is_honored() {
1092 let config = EncoderConfig {
1093 width: 64,
1094 height: 64,
1095 base_q_idx: 100,
1096 gop: 3,
1097 colour: Colour::Unspecified,
1098 tile_cols_log2: 0,
1099 tile_rows_log2: 0,
1100 };
1101 let mut enc = Av1Encoder::new(config).unwrap();
1102 let keys: Vec<bool> = (0..7)
1103 .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key)
1104 .collect();
1105 assert_eq!(keys, vec![true, false, false, true, false, false, true]);
1106 }
1107
1108 fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {
1109 let path = std::env::temp_dir().join(format!(
1110 "ec-av1-facade-probe-{}-{}.obu",
1111 std::process::id(),
1112 std::ptr::addr_of!(stream) as usize
1113 ));
1114 std::fs::write(&path, stream).expect("writing the probe stream");
1115 let out = Command::new("ffprobe")
1116 .args([
1117 "-v",
1118 "error",
1119 "-f",
1120 "obu",
1121 "-select_streams",
1122 "v:0",
1123 "-show_entries",
1124 "frame=key_frame,width,height",
1125 "-of",
1126 "csv=p=0",
1127 ])
1128 .arg(&path)
1129 .output()
1130 .expect("ffprobe failed to run");
1131 let _ = std::fs::remove_file(&path);
1132 assert!(
1133 out.status.success(),
1134 "ffprobe refused the stream: {}",
1135 String::from_utf8_lossy(&out.stderr)
1136 );
1137 String::from_utf8_lossy(&out.stdout)
1138 .lines()
1139 .map(|line| {
1140 let mut f = line.trim().split(',');
1141 let key: u32 = f.next().unwrap().parse().unwrap();
1142 let width: u32 = f.next().unwrap().parse().unwrap();
1143 let height: u32 = f.next().unwrap().parse().unwrap();
1144 (key == 1, width, height)
1145 })
1146 .collect()
1147 }
1148
1149 fn ffprobe_colour(stream: &[u8]) -> String {
1150 let path = std::env::temp_dir().join(format!(
1151 "ec-av1-facade-colour-probe-{}-{}.obu",
1152 std::process::id(),
1153 std::ptr::addr_of!(stream) as usize
1154 ));
1155 std::fs::write(&path, stream).expect("writing the probe stream");
1156 let out = Command::new("ffprobe")
1157 .args([
1158 "-v",
1159 "error",
1160 "-f",
1161 "obu",
1162 "-select_streams",
1163 "v:0",
1164 "-show_entries",
1165 "stream=color_primaries,color_transfer,color_space,color_range",
1166 "-of",
1167 "csv=p=0",
1168 ])
1169 .arg(&path)
1170 .output()
1171 .expect("ffprobe failed to run");
1172 let _ = std::fs::remove_file(&path);
1173 assert!(
1174 out.status.success(),
1175 "ffprobe refused the stream: {}",
1176 String::from_utf8_lossy(&out.stderr)
1177 );
1178 String::from_utf8_lossy(&out.stdout).trim().to_string()
1179 }
1180
1181 /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)
1182 /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that
1183 /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and
1184 /// coded size confirm what the facade already reported.
1185 #[test]
1186 fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
1187 if !have_ffmpeg() {
1188 eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg");
1189 return;
1190 }
1191 let (width, height) = (96usize, 96usize);
1192 let config = EncoderConfig {
1193 width,
1194 height,
1195 base_q_idx: 120,
1196 gop: 15,
1197 colour: Colour::Bt709Limited,
1198 tile_cols_log2: 0,
1199 tile_rows_log2: 0,
1200 };
1201 let mut enc = Av1Encoder::new(config).unwrap();
1202 assert_eq!(enc.display_size(), (width, height));
1203 let (coded_w, coded_h) = enc.coded_size();
1204 assert_eq!(
1205 (coded_w, coded_h),
1206 (
1207 width.next_multiple_of(SUPERBLOCK),
1208 height.next_multiple_of(SUPERBLOCK)
1209 )
1210 );
1211
1212 let packets: Vec<Packet> = (0..30)
1213 .map(|t| enc.encode(&test_card(width, height, t)).unwrap())
1214 .collect();
1215 let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect();
1216 assert_eq!(
1217 packets.iter().map(|p| p.key).collect::<Vec<_>>(),
1218 expect_key,
1219 "facade's own key/inter flags"
1220 );
1221
1222 let stream = concat(&packets);
1223 let frames = ffprobe_frames(&stream);
1224 assert_eq!(frames.len(), 30, "ffprobe frame count");
1225 for (t, (key, w, h)) in frames.iter().enumerate() {
1226 assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag");
1227 assert_eq!(
1228 (*w, *h),
1229 (width as u32, height as u32),
1230 "picture {t}: ffprobe reports the true (display) size, not the padded coded one"
1231 );
1232 }
1233 }
1234
1235 /// The configured colour properties are what `ffprobe` reports back,
1236 /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it
1237 /// is the default a player assumes and the one this test would silently
1238 /// pass without wiring for (`ffprobe` reports "unknown" for the
1239 /// hardcoded "unspecified" this crate wrote before the facade existed,
1240 /// which is a visibly different string).
1241 #[test]
1242 fn bt709_limited_colour_is_reported_by_ffprobe() {
1243 if !have_ffmpeg() {
1244 eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg");
1245 return;
1246 }
1247 let config = EncoderConfig {
1248 width: 64,
1249 height: 64,
1250 base_q_idx: 100,
1251 gop: 4,
1252 colour: Colour::Bt709Limited,
1253 tile_cols_log2: 0,
1254 tile_rows_log2: 0,
1255 };
1256 let mut enc = Av1Encoder::new(config).unwrap();
1257 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
1258 let colour = ffprobe_colour(&packet.data);
1259 assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields");
1260 }
1261
1262 /// The same, for BT.601: a different set of CICP integers must produce a
1263 /// different string, or the wiring could be a no-op that happens to read
1264 /// as BT.709 for every input.
1265 #[test]
1266 fn bt601_limited_colour_is_reported_by_ffprobe() {
1267 if !have_ffmpeg() {
1268 eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg");
1269 return;
1270 }
1271 let config = EncoderConfig {
1272 width: 64,
1273 height: 64,
1274 base_q_idx: 100,
1275 gop: 4,
1276 colour: Colour::Bt601Limited,
1277 tile_cols_log2: 0,
1278 tile_rows_log2: 0,
1279 };
1280 let mut enc = Av1Encoder::new(config).unwrap();
1281 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
1282 let colour = ffprobe_colour(&packet.data);
1283 assert_eq!(
1284 colour, "tv,smpte170m,smpte170m,smpte170m",
1285 "ffprobe colour fields"
1286 );
1287 }
1288
1289 /// A frame whose size does not match the encoder's configured geometry
1290 /// is refused by name.
1291 #[test]
1292 fn geometry_mismatch_is_refused() {
1293 let config = EncoderConfig {
1294 width: 64,
1295 height: 64,
1296 base_q_idx: 100,
1297 gop: 4,
1298 colour: Colour::Bt709Limited,
1299 tile_cols_log2: 0,
1300 tile_rows_log2: 0,
1301 };
1302 let mut enc = Av1Encoder::new(config).unwrap();
1303 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
1304 assert!(err.to_string().contains("64x64"), "{err}");
1305 }
1306
1307 /// `gop == 0` is refused at construction, not the first `encode()` call.
1308 #[test]
1309 fn zero_gop_is_refused() {
1310 let config = EncoderConfig {
1311 width: 64,
1312 height: 64,
1313 base_q_idx: 100,
1314 gop: 0,
1315 colour: Colour::Bt709Limited,
1316 tile_cols_log2: 0,
1317 tile_rows_log2: 0,
1318 };
1319 let err = Av1Encoder::new(config).unwrap_err();
1320 assert!(err.to_string().contains("gop"), "{err}");
1321 }
1322
1323 /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget`
1324 /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down
1325 /// to this facade's own input size, and re-coded through the facade so the
1326 /// rate-target surface is exercised at the entry point a caller actually
1327 /// drives.
1328 fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> {
1329 if !have_ffmpeg() {
1330 return None;
1331 }
1332 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
1333 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
1334 if !clip.exists() {
1335 return None;
1336 }
1337 let out = Command::new("ffmpeg")
1338 .args(["-v", "error", "-i", clip.to_str().unwrap()])
1339 .args(["-frames:v", &frames.to_string()])
1340 .args(["-vf", &format!("scale={width}:{height}")])
1341 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
1342 .output()
1343 .expect("ffmpeg failed to run");
1344 assert!(
1345 out.status.success(),
1346 "{}",
1347 String::from_utf8_lossy(&out.stderr)
1348 );
1349 let (luma, chroma) = (width * height, width * height / 4);
1350 let frame_len = luma + 2 * chroma;
1351 assert_eq!(
1352 out.stdout.len(),
1353 frame_len * frames,
1354 "expected {frames} 4:2:0 frames"
1355 );
1356 Some(
1357 (0..frames)
1358 .map(|i| {
1359 let bytes = &out.stdout[i * frame_len..][..frame_len];
1360 Picture {
1361 width,
1362 height,
1363 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
1364 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
1365 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
1366 }
1367 })
1368 .collect(),
1369 )
1370 }
1371
1372 /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total
1373 /// coded size within ±20% of `frames * target` once the first few
1374 /// frames' settling has been discarded (the key frame's own reference
1375 /// state and the controller's first couple of steps).
1376 #[test]
1377 fn bytes_per_frame_target_settles_within_20_percent() {
1378 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
1379 eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture");
1380 return;
1381 };
1382 let target_bytes = 4_000u32;
1383 let config = EncoderConfig {
1384 width: 640,
1385 height: 384,
1386 base_q_idx: 100,
1387 gop: 24,
1388 colour: Colour::Bt709Limited,
1389 tile_cols_log2: 0,
1390 tile_rows_log2: 0,
1391 };
1392 let mut enc =
1393 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
1394 let sizes: Vec<usize> = pictures
1395 .iter()
1396 .map(|p| enc.encode(p).unwrap().data.len())
1397 .collect();
1398 // Discard the key frame (always far larger than an inter target) and
1399 // the next 4 inter frames the loop needs to step toward it.
1400 let settled = &sizes[5..];
1401 let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64;
1402 let low = f64::from(target_bytes) * 0.8;
1403 let high = f64::from(target_bytes) * 1.2;
1404 assert!(
1405 mean >= low && mean <= high,
1406 "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}"
1407 );
1408 }
1409
1410 /// [`RateTarget::Bitrate`] lands the achieved bitrate within ±10% of the
1411 /// target over 48 frames of a real clip, flat and under a pyramid alike.
1412 /// This is the accuracy claim of the target-bitrate mode: no two-pass, no
1413 /// lookahead, just each frame's size predicted from the previous frame of
1414 /// its own level and one clamped proportional step.
1415 #[test]
1416 fn bitrate_target_lands_within_10_percent_over_48_frames() {
1417 let (width, height, frames) = (640usize, 384usize, 48usize);
1418 let Some(pictures) = h264_clip_frames(width, height, frames) else {
1419 eprintln!("SKIP bitrate_target_lands_within_10_percent_over_48_frames: no ffmpeg/fixture");
1420 return;
1421 };
1422 let fps = 24.0;
1423 for bits_per_second in [768_000u32, 1_536_000] {
1424 let config = EncoderConfig {
1425 width,
1426 height,
1427 base_q_idx: 100,
1428 gop: frames,
1429 colour: Colour::Bt709Limited,
1430 tile_cols_log2: 0,
1431 tile_rows_log2: 0,
1432 };
1433 let rate = RateTarget::Bitrate {
1434 bits_per_second,
1435 frames_per_second: fps,
1436 };
1437 for pyramid in [None, Some(Pyramid::default())] {
1438 let mut enc = match pyramid {
1439 None => Av1Encoder::with_rate_target(config, rate).unwrap(),
1440 Some(p) => Av1Encoder::with_pyramid_and_rate_target(config, p, rate).unwrap(),
1441 };
1442 let mut coded = 0usize;
1443 for picture in &pictures {
1444 for packet in enc.encode_frames(picture).unwrap() {
1445 coded += packet.data.len();
1446 }
1447 }
1448 for packet in enc.flush().unwrap() {
1449 coded += packet.data.len();
1450 }
1451 let seconds = frames as f64 / fps;
1452 let achieved = coded as f64 * 8.0 / seconds;
1453 let error = achieved / f64::from(bits_per_second) - 1.0;
1454 eprintln!(
1455 "bitrate {bits_per_second} bps, pyramid {}: {coded} bytes over {seconds:.2}s \
1456 = {achieved:.0} bps ({:+.1}%)",
1457 pyramid.is_some(),
1458 100.0 * error,
1459 );
1460 assert!(
1461 error.abs() <= 0.10,
1462 "achieved {achieved:.0} bps is {:+.1}% off the {bits_per_second} bps target \
1463 (pyramid {})",
1464 100.0 * error,
1465 pyramid.is_some(),
1466 );
1467 }
1468 }
1469 }
1470
1471 /// The `BytesPerFrame` controller's own windup bound: no frame's coded
1472 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
1473 /// clip's full range of content (so a scene cut can't be the one frame
1474 /// that breaks the bound).
1475 #[test]
1476 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
1477 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
1478 eprintln!(
1479 "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture"
1480 );
1481 return;
1482 };
1483 let config = EncoderConfig {
1484 width: 640,
1485 height: 384,
1486 base_q_idx: 100,
1487 gop: 24,
1488 colour: Colour::Bt709Limited,
1489 tile_cols_log2: 0,
1490 tile_rows_log2: 0,
1491 };
1492 let mut enc =
1493 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
1494 let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
1495 for picture in &pictures {
1496 enc.encode(picture).unwrap();
1497 let q = enc.rate_loop.as_ref().unwrap().q_idx(Level::Leaf);
1498 let step = (i32::from(q) - i32::from(prev_q)).abs();
1499 assert!(
1500 f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
1501 "q stepped from {prev_q} to {q}, past the {} clamp",
1502 RateLoop::STEP_CLAMP
1503 );
1504 prev_q = q;
1505 }
1506 }
1507
1508 fn psnr(a: &[u16], b: &[u16]) -> f64 {
1509 let squared: f64 = a
1510 .iter()
1511 .zip(b)
1512 .map(|(&x, &y)| {
1513 let d = f64::from(x) - f64::from(y);
1514 d * d
1515 })
1516 .sum();
1517 if squared == 0.0 {
1518 return f64::INFINITY;
1519 }
1520 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
1521 }
1522
1523 /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one
1524 /// entry per coded frame, in order — this facade's own equivalent of
1525 /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
1526 /// PSNR check needs the decoded pixels, not just the coded byte count.
1527 fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
1528 let path = std::env::temp_dir().join(format!(
1529 "ec-av1-facade-rate-decode-{}-{}.obu",
1530 std::process::id(),
1531 std::ptr::addr_of!(stream) as usize
1532 ));
1533 std::fs::write(&path, stream).expect("writing the decode probe stream");
1534 let out = Command::new("ffmpeg")
1535 .args(["-v", "error", "-f", "obu", "-i"])
1536 .arg(&path)
1537 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
1538 .output()
1539 .expect("ffmpeg failed to run");
1540 let _ = std::fs::remove_file(&path);
1541 assert!(
1542 out.status.success(),
1543 "{}",
1544 String::from_utf8_lossy(&out.stderr)
1545 );
1546 let (luma, chroma) = (width * height, width * height / 4);
1547 let frame_len = luma + 2 * chroma;
1548 out.stdout
1549 .chunks_exact(frame_len)
1550 .map(|f| f[..luma].to_vec())
1551 .collect()
1552 }
1553
1554 /// A pyramid stream reorders pictures: the hidden `ALTREF` of each
1555 /// mini-GOP is coded before the leaves that precede it in display order,
1556 /// and a `show_existing_frame` header puts it back. This pins the shape
1557 /// (one packet per source picture plus one `show_existing_frame` per
1558 /// group, `dts` monotone, `order` NOT monotone) and then decodes the
1559 /// whole stream through OUR decoder and through ffmpeg/dav1d and requires
1560 /// the two display-order outputs to agree sample for sample — the
1561 /// [[gate-blind-to-hidden-frames]] check: a hidden frame that is never
1562 /// output, or output twice, or output in the wrong position, changes the
1563 /// display-order list and fails here.
1564 #[test]
1565 fn a_pyramid_stream_decodes_in_display_order_through_both_decoders() {
1566 let (width, height) = (128usize, 128usize);
1567 let config = EncoderConfig {
1568 width,
1569 height,
1570 base_q_idx: 120,
1571 gop: 32,
1572 colour: Colour::Bt709Limited,
1573 tile_cols_log2: 0,
1574 tile_rows_log2: 0,
1575 };
1576 let pyramid = Pyramid {
1577 mini_gop: 4,
1578 ..Pyramid::default()
1579 };
1580 let mut enc = Av1Encoder::with_pyramid(config, pyramid).unwrap();
1581 let sources: Vec<Picture> = (0..9).map(|t| test_card(width, height, t * 3)).collect();
1582 let _ = crate::encode::take_ref_frame_hits();
1583 let mut packets = Vec::new();
1584 for picture in &sources {
1585 packets.extend(enc.encode_frames(picture).unwrap());
1586 }
1587 packets.extend(enc.flush().unwrap());
1588
1589 // Shape: every source picture is coded exactly once, and each closed
1590 // group adds one `show_existing_frame` packet.
1591 let coded: Vec<u64> = packets
1592 .iter()
1593 .filter(|p| p.level != Level::ShowExisting)
1594 .map(|p| p.order)
1595 .collect();
1596 let mut sorted = coded.clone();
1597 sorted.sort_unstable();
1598 assert_eq!(sorted, (0..9).collect::<Vec<u64>>(), "one packet per picture");
1599 assert_ne!(coded, sorted, "the pyramid never reordered anything");
1600 let shown = packets.iter().filter(|p| p.level == Level::ShowExisting).count();
1601 assert_eq!(shown, 2, "one show_existing_frame per closed mini-GOP");
1602 for (i, p) in packets.iter().enumerate() {
1603 assert_eq!(p.dts, i as u64, "packet {i}: dts is the coding position");
1604 }
1605 let hist = |l: Level| packets.iter().filter(|p| p.level == l).count();
1606 eprintln!(
1607 "pyramid levels: key {} arf {} leaf {} show_existing {}",
1608 hist(Level::Key),
1609 hist(Level::Arf),
1610 hist(Level::Leaf),
1611 hist(Level::ShowExisting),
1612 );
1613 assert_eq!(hist(Level::Arf), 2, "two hidden frames");
1614 let refs = crate::encode::take_ref_frame_hits();
1615 eprintln!(
1616 "blocks per reference: LAST {} GOLDEN {} ALTREF {}",
1617 refs[crate::mvstack::LAST_FRAME as usize],
1618 refs[crate::mvstack::GOLDEN_FRAME as usize],
1619 refs[crate::mvstack::ALTREF_FRAME as usize],
1620 );
1621 // [[gate-blind-to-feature]]: the whole point of the hidden frame is
1622 // that the leaves predict BACKWARD off it, which is also the only
1623 // thing that exercises `ref_frame_sign_bias` in the MV stack. A green
1624 // round trip in which `ALTREF_FRAME` never won a block would prove
1625 // only that a hidden frame can be written and re-output.
1626 assert!(
1627 refs[crate::mvstack::ALTREF_FRAME as usize] > 0,
1628 "no block predicted off the hidden ALTREF"
1629 );
1630
1631 let stream = concat(&packets);
1632 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1633 assert_eq!(ours.len(), sources.len(), "our decoder's display-order count");
1634 if !have_ffmpeg() {
1635 eprintln!("SKIP the ffmpeg half of the pyramid round trip: no ffmpeg");
1636 return;
1637 }
1638 let theirs = ffmpeg_decode_luma(&stream, width, height);
1639 assert_eq!(theirs.len(), sources.len(), "ffmpeg's display-order count");
1640 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1641 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1642 assert_eq!(got.len(), b.len(), "frame {i}: luma size");
1643 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
1644 panic!(
1645 "display frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
1646 at % width,
1647 at / width,
1648 got[at],
1649 b[at],
1650 );
1651 }
1652 }
1653 }
1654
1655 /// Every tile layout this encoder can write decodes SAMPLE-EXACT
1656 /// through both decoders -- ours and ffmpeg's -- and the frames really
1657 /// carry the tiles the header claims (the OBU parser locates one payload
1658 /// per tile, so a stream that quietly stayed single-tile fails here
1659 /// rather than passing on a green round trip).
1660 ///
1661 /// The bytes are what the gate is on: an encoder that clipped its
1662 /// neighbour availability wrong writes a stream whose two decoders agree
1663 /// with each other and disagree with nothing -- so the ffmpeg half is
1664 /// the one that catches a tile boundary the writer respected and the
1665 /// spec does not, and the parser half catches the reverse.
1666 #[test]
1667 fn every_tile_layout_decodes_sample_exact_through_both_decoders() {
1668 let (width, height) = (640usize, 384usize);
1669 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
1670 let mut sizes = Vec::new();
1671 for (cols_log2, rows_log2) in [(0u32, 0u32), (1, 0), (0, 1), (1, 1), (2, 1)] {
1672 let config = EncoderConfig {
1673 width,
1674 height,
1675 base_q_idx: 120,
1676 gop: 4,
1677 colour: Colour::Bt709Limited,
1678 tile_cols_log2: cols_log2,
1679 tile_rows_log2: rows_log2,
1680 };
1681 let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
1682 let mut enc = Av1Encoder::new(config).unwrap();
1683 let mut stream = Vec::new();
1684 for (i, picture) in sources.iter().enumerate() {
1685 let packet = enc
1686 .encode(picture)
1687 .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}"));
1688 stream.extend_from_slice(&packet.data);
1689 }
1690 sizes.push((layout.clone(), stream.len()));
1691
1692 // The frames carry the tiles their headers claim.
1693 let mut parser = ec_av1_syntax::Av1Parser::new();
1694 let mut frames = 0usize;
1695 let mut offset = 0usize;
1696 while offset < stream.len() {
1697 let obus = parser.parse_temporal_unit(&stream[offset..]).unwrap();
1698 let unit: usize = obus.iter().map(|o| o.total_size).sum();
1699 for obu in &obus {
1700 if let ec_av1_syntax::ObuKind::Frame(parsed, tiles) = &obu.kind {
1701 assert_eq!(
1702 (parsed.tile_info.cols, parsed.tile_info.rows),
1703 (1 << cols_log2, 1 << rows_log2),
1704 "{layout}: the header's own tile grid"
1705 );
1706 assert_eq!(
1707 tiles.len(),
1708 1 << (cols_log2 + rows_log2),
1709 "{layout}: tile payloads located in the tile group"
1710 );
1711 frames += 1;
1712 }
1713 }
1714 offset += unit;
1715 }
1716 assert_eq!(frames, sources.len(), "{layout}: coded frames");
1717
1718 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
1719 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
1720 if !have_ffmpeg() {
1721 eprintln!("SKIP the ffmpeg half of {layout}: no ffmpeg");
1722 continue;
1723 }
1724 let theirs = ffmpeg_decode_luma(&stream, width, height);
1725 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
1726 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
1727 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
1728 assert_eq!(got.len(), b.len(), "{layout} frame {i}: luma size");
1729 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
1730 panic!(
1731 "{layout} frame {i}: luma differs first at ({}, {}): ours {} vs ffmpeg {}",
1732 at % width,
1733 at / width,
1734 got[at],
1735 b[at],
1736 );
1737 }
1738 }
1739 }
1740 let base = sizes[0].1 as f64;
1741 for (layout, bytes) in &sizes {
1742 eprintln!(
1743 "{layout}: {bytes} bytes ({:+.2}% vs one tile)",
1744 (*bytes as f64 / base - 1.0) * 100.0
1745 );
1746 }
1747 }
1748
1749 /// What tiles and tile threads are worth at the size the editor exports
1750 /// at: 1920x1080, eight real pictures, two passes per cell (ABAB), wall
1751 /// per cell. Ignored by default (minutes).
1752 #[test]
1753 #[ignore = "1080p wall table: minutes, run it with --ignored"]
1754 fn tile_wall_table_at_1080p() {
1755 let _gate_lock = crate::stream::tests::lock_gate_counters();
1756 let (width, height) = (1920usize, 1080usize);
1757 let Some(sources) = h264_clip_frames(width, height, 8) else {
1758 eprintln!("SKIP tile_wall_table_at_1080p: no fixture");
1759 return;
1760 };
1761 let layouts = [(0u32, 0u32), (1, 0), (1, 1), (2, 1)];
1762 let threadings = [1usize, 2, 4, 8];
1763 let mut table: Vec<(String, usize, f64, usize)> = Vec::new();
1764 for pass in 0..2 {
1765 for &(cols_log2, rows_log2) in &layouts {
1766 for &threads in &threadings {
1767 crate::par::set_tile_threads(threads);
1768 let config = EncoderConfig {
1769 width,
1770 height,
1771 base_q_idx: 120,
1772 gop: 8,
1773 colour: Colour::Bt709Limited,
1774 tile_cols_log2: cols_log2,
1775 tile_rows_log2: rows_log2,
1776 };
1777 let mut enc = Av1Encoder::new(config).unwrap();
1778 let start = std::time::Instant::now();
1779 let mut bytes = 0usize;
1780 for picture in &sources {
1781 bytes += enc.encode(picture).unwrap().data.len();
1782 }
1783 let wall = start.elapsed().as_secs_f64();
1784 let name = format!("{}x{}", 1 << cols_log2, 1 << rows_log2);
1785 match table.iter_mut().find(|r| r.0 == name && r.1 == threads) {
1786 Some(row) => row.2 = row.2.min(wall),
1787 None => table.push((name, threads, wall, bytes)),
1788 }
1789 let _ = pass;
1790 }
1791 }
1792 }
1793 crate::par::set_tile_threads(1);
1794 eprintln!("| tiles | threads | wall (s, best of 2) | bytes |");
1795 for (name, threads, wall, bytes) in &table {
1796 eprintln!("| {name} | {threads} | {wall:.2} | {bytes} |");
1797 }
1798 }
1799
1800 /// The tiles of a frame are entropy-independent, so the bytes must not
1801 /// depend on how many workers wrote them: the same stream at one tile
1802 /// thread and at four, per layout.
1803 #[test]
1804 fn tile_bytes_do_not_depend_on_the_thread_count() {
1805 let _gate_lock = crate::stream::tests::lock_gate_counters();
1806 let (width, height) = (320usize, 192usize);
1807 let sources: Vec<Picture> = (0..3).map(|t| test_card(width, height, t * 3)).collect();
1808 let coded = |threads: usize, cols_log2: u32, rows_log2: u32| {
1809 crate::par::set_tile_threads(threads);
1810 let config = EncoderConfig {
1811 width,
1812 height,
1813 base_q_idx: 120,
1814 gop: 3,
1815 colour: Colour::Bt709Limited,
1816 tile_cols_log2: cols_log2,
1817 tile_rows_log2: rows_log2,
1818 };
1819 let mut enc = Av1Encoder::new(config).unwrap();
1820 let mut stream = Vec::new();
1821 for picture in &sources {
1822 stream.extend_from_slice(&enc.encode(picture).unwrap().data);
1823 }
1824 stream
1825 };
1826 for (cols_log2, rows_log2) in [(1u32, 0u32), (0, 1), (1, 1), (2, 1)] {
1827 let one = coded(1, cols_log2, rows_log2);
1828 let four = coded(4, cols_log2, rows_log2);
1829 assert_eq!(
1830 one,
1831 four,
1832 "{}x{} tiles: {} bytes at one thread, {} at four",
1833 1 << cols_log2,
1834 1 << rows_log2,
1835 one.len(),
1836 four.len()
1837 );
1838 }
1839 crate::par::set_tile_threads(1);
1840 }
1841
1842 /// What the per-tile search (lane-av1tsearch) is worth in wall and in
1843 /// frames per second at the editor's own export sizes: every tile layout
1844 /// crossed with every tile-thread count, plus librav1e at the matching
1845 /// `tile_cols`/`tile_rows`/`threads` as the reference point. Two passes
1846 /// over the whole table (A,B,A,B... rather than AA,BB) with the best of
1847 /// the two kept, so a thermal drift cannot order the rows.
1848 ///
1849 /// Measurement, not a pass/fail gate: it asserts only that every cell
1850 /// produced a stream.
1851 #[test]
1852 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
1853 fn tile_search_wall_1080p() {
1854 tile_search_wall(1920, 1080, 12, &[(0, 0), (1, 0), (1, 1), (2, 1)], &[1, 2, 4, 8]);
1855 }
1856
1857 /// The same table at the 4K frame size the editor exports (3840x1608),
1858 /// at the two layouts with enough tiles to fill this box.
1859 #[test]
1860 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
1861 fn tile_search_wall_4k() {
1862 tile_search_wall(3840, 1608, 6, &[(2, 1), (3, 2)], &[1, 8, 12]);
1863 }
1864
1865 /// lane-av1fpar: the frame-level FILTER stage is banded across the same
1866 /// workers the tile search uses (`par::override_filter_threads`), so the
1867 /// deblock/CDEF replays, the per-64 SSE and the plane copies all run in
1868 /// pieces. Every piece is a disjoint band of the same integers, so the
1869 /// stream must not move -- at a size that crops and is several superblock
1870 /// rows tall, which is what makes the bands non-trivial.
1871 #[test]
1872 fn filter_stage_bytes_do_not_depend_on_the_thread_count() {
1873 let _gate_lock = crate::stream::tests::lock_gate_counters();
1874 let (width, height) = (384usize, 288usize);
1875 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
1876 let coded = |threads: usize| {
1877 crate::par::set_tile_threads(threads);
1878 let config = EncoderConfig {
1879 width,
1880 height,
1881 base_q_idx: 120,
1882 gop: 2,
1883 colour: Colour::Bt709Limited,
1884 tile_cols_log2: 0,
1885 tile_rows_log2: 0,
1886 };
1887 let mut enc = Av1Encoder::new(config).unwrap();
1888 let mut stream = Vec::new();
1889 for picture in &sources {
1890 stream.extend_from_slice(&enc.encode(picture).unwrap().data);
1891 }
1892 stream
1893 };
1894 // One tile, so only the filter stage can differ between these.
1895 let one = coded(1);
1896 for threads in [2usize, 4, 8] {
1897 assert_eq!(one, coded(threads), "the filter stage moved at {threads} threads");
1898 }
1899 crate::par::set_tile_threads(1);
1900 }
1901
1902 /// lane-av1fpar: the filter search scores its ~30 candidates by replaying
1903 /// the loop filters on one captured reconstruction instead of decoding
1904 /// the coded tile again per candidate. The replay must be that decode,
1905 /// byte for byte -- including at a size that CROPS (1080 and 1608 both
1906 /// pad to a superblock row, i.e. every export size the editor uses),
1907 /// which is the arm this lane opened.
1908 #[test]
1909 fn filter_replay_codes_the_same_stream_as_a_full_decode() {
1910 let _gate_lock = crate::stream::tests::lock_gate_counters();
1911 let run = |width: usize, height: usize, off: bool| {
1912 let sources: Vec<Picture> = (0..4).map(|t| test_card(width, height, t * 3)).collect();
1913 crate::decode::set_filter_replay_disabled(off);
1914 let config = EncoderConfig {
1915 width,
1916 height,
1917 base_q_idx: 120,
1918 gop: 2,
1919 colour: Colour::Bt709Limited,
1920 tile_cols_log2: 0,
1921 tile_rows_log2: 0,
1922 };
1923 let mut enc = Av1Encoder::new(config).unwrap();
1924 let mut stream = Vec::new();
1925 for picture in &sources {
1926 stream.extend_from_slice(&enc.encode(picture).unwrap().data);
1927 }
1928 crate::decode::set_filter_replay_disabled(false);
1929 stream
1930 };
1931 // 320x160 crops (the coding surface is 320x192, one superblock row
1932 // taller); 320x192 is a whole number of superblocks, the shape the
1933 // replay already covered.
1934 for (width, height) in [(320usize, 160usize), (320, 192)] {
1935 let replayed = run(width, height, false);
1936 let decoded = run(width, height, true);
1937 assert_eq!(
1938 replayed,
1939 decoded,
1940 "{width}x{height}: the filter replay is not the decode it stands in for \
1941 ({} bytes replayed, {} decoded)",
1942 replayed.len(),
1943 decoded.len(),
1944 );
1945 }
1946 }
1947
1948 /// lane-av1fpar: where a frame's wall actually goes, stage by stage --
1949 /// the per-tile search, the tile write, the frame-level filter search
1950 /// (with its deblock/CDEF replay and per-64 SSE inside it), the capture
1951 /// decode the loop-restoration search rides on, and that search itself.
1952 /// Measurement, not a pass/fail gate.
1953 #[test]
1954 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
1955 fn filter_stage_wall_1080p() {
1956 filter_stage_wall(1920, 1080, 8, (2, 1), &[8]);
1957 }
1958
1959 #[test]
1960 #[ignore = "wall measurement: minutes, run it with --ignored --nocapture"]
1961 fn filter_stage_wall_4k() {
1962 filter_stage_wall(3840, 1608, 4, (2, 1), &[8, 12]);
1963 }
1964
1965 fn filter_stage_wall(
1966 width: usize,
1967 height: usize,
1968 frames: usize,
1969 (cols_log2, rows_log2): (u32, u32),
1970 threads: &[usize],
1971 ) {
1972 let _gate_lock = crate::stream::tests::lock_gate_counters();
1973 let Some(sources) = h264_clip_frames(width, height, frames) else {
1974 eprintln!("SKIP the filter-stage breakdown: no fixture or no ffmpeg");
1975 return;
1976 };
1977 crate::par::set_stage_times(true);
1978 for &t in threads {
1979 crate::par::set_tile_threads(t);
1980 let config = EncoderConfig {
1981 width,
1982 height,
1983 base_q_idx: 120,
1984 gop: frames,
1985 colour: Colour::Bt709Limited,
1986 tile_cols_log2: cols_log2,
1987 tile_rows_log2: rows_log2,
1988 };
1989 let mut enc = Av1Encoder::new(config).unwrap();
1990 let _ = crate::par::take_stage_ns();
1991 let start = std::time::Instant::now();
1992 for picture in &sources {
1993 assert!(!enc.encode(picture).unwrap().data.is_empty());
1994 }
1995 let wall = start.elapsed().as_secs_f64();
1996 let ns = crate::par::take_stage_ns();
1997 let ms = |i: usize| ns[i] as f64 / 1e6;
1998 eprintln!(
1999 "\n{width}x{height}, {frames} frames, {}x{} tiles, {t} tile threads: \
2000 {wall:.2}s wall, {:.2} fps",
2001 1 << cols_log2,
2002 1 << rows_log2,
2003 frames as f64 / wall,
2004 );
2005 eprintln!("| stage | ms | ms/frame | % of wall |");
2006 for (i, name) in crate::par::STAGES.iter().enumerate() {
2007 eprintln!(
2008 "| {name} | {:.0} | {:.1} | {:.1}% |",
2009 ms(i),
2010 ms(i) / frames as f64,
2011 100.0 * ms(i) / (wall * 1e3),
2012 );
2013 }
2014 // Top-level stages only (the deblock/CDEF/SSE rows are inside
2015 // the filter-search total); the rest is per-frame setup, the
2016 // source conversion and the splice.
2017 let top: f64 = [
2018 crate::par::S_TILE_SEARCH,
2019 crate::par::S_TILE_WRITE,
2020 crate::par::S_FILTER,
2021 crate::par::S_CAPTURE,
2022 crate::par::S_LR,
2023 ]
2024 .iter()
2025 .map(|&i| ms(i))
2026 .sum();
2027 eprintln!(
2028 "accounted {:.1}% of wall; outside the tile search {:.1}%",
2029 100.0 * top / (wall * 1e3),
2030 100.0 * (1.0 - ms(crate::par::S_TILE_SEARCH) / (wall * 1e3)),
2031 );
2032 }
2033 crate::par::set_stage_times(false);
2034 crate::par::set_tile_threads(1);
2035 }
2036
2037 fn tile_search_wall(
2038 width: usize,
2039 height: usize,
2040 frames: usize,
2041 layouts: &[(u32, u32)],
2042 threads: &[usize],
2043 ) {
2044 let _gate_lock = crate::stream::tests::lock_gate_counters();
2045 let Some(sources) = h264_clip_frames(width, height, frames) else {
2046 eprintln!("SKIP the tile-search wall table: no fixture or no ffmpeg");
2047 return;
2048 };
2049 let run = |cols_log2: u32, rows_log2: u32, t: usize| -> (std::time::Duration, usize) {
2050 crate::par::set_tile_threads(t);
2051 let config = EncoderConfig {
2052 width,
2053 height,
2054 base_q_idx: 120,
2055 gop: frames,
2056 colour: Colour::Bt709Limited,
2057 tile_cols_log2: cols_log2,
2058 tile_rows_log2: rows_log2,
2059 };
2060 let mut enc = Av1Encoder::new(config).unwrap();
2061 let start = std::time::Instant::now();
2062 let mut bytes = 0usize;
2063 for picture in &sources {
2064 bytes += enc.encode(picture).unwrap().data.len();
2065 }
2066 (start.elapsed(), bytes)
2067 };
2068 let cells: Vec<((u32, u32), usize)> = layouts
2069 .iter()
2070 .flat_map(|&l| threads.iter().map(move |&t| (l, t)))
2071 .collect();
2072 let mut best: Vec<Option<(std::time::Duration, usize)>> = vec![None; cells.len()];
2073 for _pass in 0..2 {
2074 for (i, &((c, r), t)) in cells.iter().enumerate() {
2075 let got = run(c, r, t);
2076 assert!(got.1 > 0, "{}x{} tiles at {t} threads: empty stream", 1 << c, 1 << r);
2077 if best[i].is_none_or(|(w, _)| got.0 < w) {
2078 best[i] = Some(got);
2079 }
2080 }
2081 }
2082 crate::par::set_tile_threads(1);
2083 eprintln!("\n{width}x{height}, {frames} frames, base_q_idx 120 -- best of two passes");
2084 eprintln!("| layout | tiles | threads | wall | fps | speedup vs 1 tile 1 thread | bytes |");
2085 let base = best[0].expect("the first cell ran").0.as_secs_f64();
2086 for (i, &((c, r), t)) in cells.iter().enumerate() {
2087 let (wall, bytes) = best[i].expect("every cell ran");
2088 let secs = wall.as_secs_f64();
2089 eprintln!(
2090 "| {}x{} | {} | {t} | {secs:.2}s | {:.2} | {:.2}x | {bytes} |",
2091 1 << c,
2092 1 << r,
2093 1 << (c + r),
2094 frames as f64 / secs,
2095 base / secs,
2096 );
2097 }
2098 // Parallel efficiency per layout: what the extra threads actually
2099 // took off that layout's own single-threaded wall, and so what share
2100 // of the added cores sat idle.
2101 for &(c, r) in layouts {
2102 let one = cells
2103 .iter()
2104 .position(|&(l, t)| l == (c, r) && t == threads[0])
2105 .map(|i| best[i].expect("cell").0.as_secs_f64());
2106 let Some(one) = one else { continue };
2107 for &t in &threads[1..] {
2108 let i = cells.iter().position(|&(l, tt)| l == (c, r) && tt == t).expect("cell");
2109 let secs = best[i].expect("cell").0.as_secs_f64();
2110 let workers = (t.min(1 << (c + r))) as f64 / threads[0] as f64;
2111 let speedup = one / secs;
2112 eprintln!(
2113 "{}x{} tiles, {} -> {t} threads: {speedup:.2}x of a possible {workers:.2}x, \
2114 idle share {:.0}%",
2115 1 << c,
2116 1 << r,
2117 threads[0],
2118 100.0 * (1.0 - speedup / workers).max(0.0),
2119 );
2120 }
2121 }
2122 rav1e_wall_reference(width, height, frames, layouts, threads);
2123 }
2124
2125 /// librav1e at the same sizes, layouts and thread counts, through ffmpeg
2126 /// -- the reference the wall table is read against.
2127 fn rav1e_wall_reference(
2128 width: usize,
2129 height: usize,
2130 frames: usize,
2131 layouts: &[(u32, u32)],
2132 threads: &[usize],
2133 ) {
2134 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
2135 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
2136 let listed = Command::new("ffmpeg").args(["-hide_banner", "-encoders"]).output();
2137 let has_rav1e = listed
2138 .map(|o| String::from_utf8_lossy(&o.stdout).contains("librav1e"))
2139 .unwrap_or(false);
2140 if !has_rav1e || !clip.exists() {
2141 eprintln!("SKIP the rav1e reference: no librav1e or no fixture");
2142 return;
2143 }
2144 eprintln!("| rav1e layout | threads | wall | fps | bytes |");
2145 for &(c, r) in layouts {
2146 for &t in threads {
2147 let out = std::env::temp_dir().join(format!("ec-av1-rav1e-{}.ivf", std::process::id()));
2148 let params = format!(
2149 "speed=6:quantizer=100:tile_cols={}:tile_rows={}:threads={t}",
2150 1 << c,
2151 1 << r
2152 );
2153 let start = std::time::Instant::now();
2154 let status = Command::new("ffmpeg")
2155 .args(["-v", "error", "-y", "-i", clip.to_str().unwrap()])
2156 .args(["-frames:v", &frames.to_string()])
2157 .args(["-vf", &format!("scale={width}:{height}")])
2158 .args(["-c:v", "librav1e", "-rav1e-params", &params])
2159 .arg(out.to_str().unwrap())
2160 .output()
2161 .expect("ffmpeg failed to run");
2162 let secs = start.elapsed().as_secs_f64();
2163 if !status.status.success() {
2164 eprintln!("| {}x{} | {t} | FAILED: {} |", 1 << c, 1 << r, String::from_utf8_lossy(&status.stderr).lines().last().unwrap_or(""));
2165 continue;
2166 }
2167 let bytes = std::fs::metadata(&out).map(|m| m.len()).unwrap_or(0);
2168 let _ = std::fs::remove_file(&out);
2169 eprintln!(
2170 "| {}x{} | {t} | {secs:.2}s | {:.2} | {bytes} |",
2171 1 << c,
2172 1 << r,
2173 frames as f64 / secs
2174 );
2175 }
2176 }
2177 }
2178
2179 /// The same round trip at a real 1920x1080 crop of the gate's own clip
2180 /// -- the size the editor's export actually runs at, where a tile grid
2181 /// is worth having. Ignored by default only for its wall (a 1080p
2182 /// encode of three pictures), not for any weakness in the check.
2183 #[test]
2184 #[ignore = "1080p encode: minutes, run it with --ignored"]
2185 fn a_1080p_multi_tile_stream_decodes_sample_exact_through_both_decoders() {
2186 let (width, height) = (1920usize, 1080usize);
2187 let Some(sources) = h264_clip_frames(width, height, 3) else {
2188 eprintln!("SKIP the 1080p tile round trip: no fixture");
2189 return;
2190 };
2191 for (cols_log2, rows_log2) in [(1u32, 0u32), (1, 1), (2, 1)] {
2192 let config = EncoderConfig {
2193 width,
2194 height,
2195 base_q_idx: 120,
2196 gop: 3,
2197 colour: Colour::Bt709Limited,
2198 tile_cols_log2: cols_log2,
2199 tile_rows_log2: rows_log2,
2200 };
2201 let layout = format!("{}x{} tiles", 1 << cols_log2, 1 << rows_log2);
2202 let mut enc = Av1Encoder::new(config).unwrap();
2203 let mut stream = Vec::new();
2204 for (i, picture) in sources.iter().enumerate() {
2205 let packet = enc
2206 .encode(picture)
2207 .unwrap_or_else(|e| panic!("{layout} frame {i}: {e}"));
2208 stream.extend_from_slice(&packet.data);
2209 }
2210 let ours = crate::stream::decode_stream(&stream).expect("our decoder");
2211 assert_eq!(ours.len(), sources.len(), "{layout}: our decoder's frames");
2212 if !have_ffmpeg() {
2213 eprintln!("SKIP the ffmpeg half of 1080p {layout}: no ffmpeg");
2214 continue;
2215 }
2216 let theirs = ffmpeg_decode_luma(&stream, width, height);
2217 assert_eq!(theirs.len(), sources.len(), "{layout}: ffmpeg's frames");
2218 for (i, (a, b)) in ours.iter().zip(&theirs).enumerate() {
2219 let got: Vec<u8> = a.y.iter().map(|&v| v as u8).collect();
2220 if let Some(at) = got.iter().zip(b).position(|(x, y)| x != y) {
2221 panic!(
2222 "1080p {layout} frame {i}: luma differs first at ({}, {})",
2223 at % width,
2224 at / width
2225 );
2226 }
2227 }
2228 eprintln!("1080p {layout}: {} bytes, sample-exact", stream.len());
2229 }
2230 }
2231
2232 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
2233 /// produces a smaller stream or a worse mean PSNR than a lower one, on
2234 /// the same real clip.
2235 #[test]
2236 fn quality_target_is_monotone_in_bytes_and_psnr() {
2237 if !have_ffmpeg() {
2238 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg");
2239 return;
2240 }
2241 let (width, height) = (640, 384);
2242 let Some(pictures) = h264_clip_frames(width, height, 8) else {
2243 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture");
2244 return;
2245 };
2246 let mut prev_bytes = 0usize;
2247 let mut prev_psnr = 0.0f64;
2248 for quality in [20u8, 50, 80] {
2249 let config = EncoderConfig {
2250 width,
2251 height,
2252 base_q_idx: 100,
2253 gop: 8,
2254 colour: Colour::Bt709Limited,
2255 tile_cols_log2: 0,
2256 tile_rows_log2: 0,
2257 };
2258 let mut enc =
2259 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
2260 let mut stream = Vec::new();
2261 let mut total_bytes = 0usize;
2262 for picture in &pictures {
2263 let packet = enc.encode(picture).unwrap();
2264 total_bytes += packet.data.len();
2265 stream.extend_from_slice(&packet.data);
2266 }
2267 let decoded = ffmpeg_decode_luma(&stream, width, height);
2268 assert_eq!(
2269 decoded.len(),
2270 pictures.len(),
2271 "quality {quality}: dav1d frame count"
2272 );
2273 let mean_psnr: f64 = decoded
2274 .iter()
2275 .zip(&pictures)
2276 .map(|(d, p)| {
2277 let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect();
2278 psnr(&d16, &p.y)
2279 })
2280 .sum::<f64>()
2281 / decoded.len() as f64;
2282 assert!(
2283 total_bytes >= prev_bytes,
2284 "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}"
2285 );
2286 assert!(
2287 mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours
2288 "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB"
2289 );
2290 prev_bytes = total_bytes;
2291 prev_psnr = mean_psnr;
2292 }
2293 }
2294}