forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB552edc4Tahinli2 months ago2048 commits

encoder.rs882 lines, 34.4 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. Internally it
8//! is [`crate::encode::encode_key_frame_inner`] and
9//! [`crate::encode::encode_inter_frame`] driven by a small state machine —
10//! a key frame every `gop` pictures, an inter frame predicting from the
11//! previous picture's own reconstruction otherwise — which is the same core
12//! [`crate::encode::encode_sequence`] uses for its one-key-frame-then-all-inter
13//! case; both now share it rather than each padding/cropping/refreshing the
14//! reference on their own.
15
16use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig};
17use ec_core::{Error, Result};
18
19use crate::encode::{
20 Encoded, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame, encode_key_frame_inner,
21 split_blocks,
22};
23use crate::intra::KEY_FRAME_MODES;
24
25/// A quantizer step round to nearest: half a step either way costs the same
26/// rate, so this is the deadzone every facade-driven frame is coded with.
27/// (`crate::encode`'s public entry points take a caller-chosen deadzone
28/// instead; the facade has no field for it because nothing downstream of it
29/// picks one.)
30const DEADZONE: f64 = 0.5;
31
32/// The colour a played-back frame is transformed by, named at what a
33/// container/player picks a colour space from (spec 5.5.2's CICP triple plus
34/// range) rather than at the raw integers. `edith_replica`'s rav1e seat sets
35/// limited-range BT.709 or BT.601 (`export.rs:3494-3507`); this crate's
36/// pre-facade sequence header always wrote [`Colour::Unspecified`].
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
38pub enum Colour {
39 /// `color_primaries`/`transfer_characteristics`/`matrix_coefficients` =
40 /// 1 (BT.709, H.273), studio range: consumer HD video's own space, and
41 /// the default a player assumes when nothing is signalled at all.
42 #[default]
43 Bt709Limited,
44 /// The same three fields = 6 (BT.601, H.273), studio range: SD video's
45 /// space.
46 Bt601Limited,
47 /// Every field = 2 ("unspecified", H.273): what this crate wrote before
48 /// any of this was configurable.
49 Unspecified,
50}
51
52impl Colour {
53 fn color_config(self) -> ColorConfig {
54 let (color_primaries, transfer_characteristics, matrix_coefficients) = match self {
55 Colour::Bt709Limited => (1, 1, 1),
56 Colour::Bt601Limited => (6, 6, 6),
57 Colour::Unspecified => (2, 2, 2),
58 };
59 ColorConfig {
60 bit_depth: 8,
61 mono_chrome: false,
62 num_planes: 3,
63 color_primaries,
64 transfer_characteristics,
65 matrix_coefficients,
66 // Every variant here is studio (limited) swing; a full-range
67 // variant would need its own name, not a fourth field on this
68 // enum, since a played-back frame's range is a property of the
69 // pictures fed in, not just a label.
70 color_range: false,
71 subsampling_x: 1,
72 subsampling_y: 1,
73 chroma_sample_position: ChromaSamplePosition::Unknown,
74 separate_uv_delta_q: false,
75 }
76 }
77}
78
79/// A quality/size targeting surface for callers who would rather not pick a
80/// `base_q_idx` themselves, oracled at CRF's own shape (a single "quality"
81/// dial that holds a stable perceptual level across content, `ffmpeg -crf`)
82/// since a from-scratch scheme is not this lane's charter to invent.
83/// [`Av1Encoder::with_rate_target`] is additive: [`EncoderConfig::base_q_idx`]
84/// keeps working exactly as before for every existing caller, this is a
85/// second, opt-in constructor.
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub enum RateTarget {
88 /// Exactly `base_q_idx`, unchanged — the `EncoderConfig` field's own
89 /// value, for a caller that already has one.
90 QIndex(u8),
91 /// A CRF-like single dial, 0 (smallest/worst) to 100 (largest/best),
92 /// mapped to a fixed `base_q_idx` by the calibration in
93 /// `encode::tests::calibration_sweep_base_q_idx` (linear in `q_idx`
94 /// across the sweep's own 40..=240 span, since the measured bytes/PSNR
95 /// curve is close enough to log-linear there that a straight line is
96 /// the "simplest correct" fit this lane's charter asks for). No
97 /// per-frame feedback: one value, picked once at construction.
98 Quality(u8),
99 /// A closed loop that steers `base_q_idx` frame by frame to land each
100 /// coded frame near this many bytes, via [`RateLoop`] — see there for
101 /// the controller and its windup bound.
102 BytesPerFrame(u32),
103}
104
105/// `quality`'s mapping to `base_q_idx`, linear across the calibration sweep's
106/// span (`q_idx` 40 at `quality` 100 down to `q_idx` 240 at `quality` 0);
107/// `quality` above 100 clamps to the best point measured, matching a CRF
108/// dial's own saturating ends rather than extrapolating past calibrated
109/// data.
110fn quality_to_q_idx(quality: u8) -> u8 {
111 let quality = f64::from(quality.min(100));
112 (240.0 - quality * 2.0).round() as u8
113}
114
115/// The closed-loop controller behind [`RateTarget::BytesPerFrame`]: a
116/// proportional step on `base_q_idx`, sized from the calibration sweep's own
117/// log-linear slope (bytes roughly halve every ~45 `q_idx` steps there, i.e.
118/// `d(ln bytes)/d(q_idx) ≈ -0.0154`), clamped per frame. Pure proportional —
119/// no accumulated error term — is the windup bound itself
120/// ([[vorbis-rate-loop-windup]]'s class): the only state carried between
121/// frames is `q`, already clamped to `0..=255`, so a quiet lead-in cannot
122/// build a debt a later transient has to repay; each frame's step is bounded
123/// by `STEP_CLAMP` regardless of history.
124#[derive(Debug, Clone, Copy)]
125struct RateLoop {
126 target_bytes: u32,
127 q: f64,
128}
129
130impl RateLoop {
131 /// The steepest a single frame is allowed to move `base_q_idx`, in
132 /// either direction — chosen so one wildly over/under-sized frame
133 /// (a scene cut, a black lead-in) nudges the next frame's quantizer
134 /// rather than slamming it to an extreme.
135 const STEP_CLAMP: f64 = 12.0;
136 /// The calibration sweep's own slope (see the struct doc), inverted to
137 /// convert a bytes ratio into a `q_idx` step.
138 const GAIN: f64 = 1.0 / 0.0154;
139
140 fn new(target_bytes: u32, start_q: f64) -> Self {
141 Self {
142 target_bytes,
143 q: start_q,
144 }
145 }
146
147 fn q_idx(&self) -> u8 {
148 self.q.round().clamp(0.0, 255.0) as u8
149 }
150
151 /// Steers `q` toward `target_bytes` from this frame's actual coded size.
152 fn update(&mut self, actual_bytes: usize) {
153 if self.target_bytes == 0 || actual_bytes == 0 {
154 return;
155 }
156 let ratio = actual_bytes as f64 / f64::from(self.target_bytes);
157 let step = (ratio.ln() * Self::GAIN).clamp(-Self::STEP_CLAMP, Self::STEP_CLAMP);
158 self.q = (self.q + step).clamp(0.0, 255.0);
159 }
160}
161
162/// What [`Av1Encoder::new`] takes: geometry, rate, key-frame cadence and
163/// colour. `base_q_idx` is picked directly (0..=255, `crate::encode`'s own
164/// unit) rather than a bitrate — a bitrate control loop is not part of this
165/// lane's charter, and a caller that wants one can still derive a
166/// `base_q_idx` from its own target and set that field. A caller who wants
167/// [`RateTarget`]'s quality/size dials instead of picking `base_q_idx`
168/// itself uses [`Av1Encoder::with_rate_target`], which still starts from an
169/// `EncoderConfig` (its `base_q_idx` is the loop's seed/fallback for
170/// [`RateTarget::BytesPerFrame`], and is overwritten outright for the other
171/// two variants).
172#[derive(Debug, Clone, Copy)]
173pub struct EncoderConfig {
174 /// The picture's width in luma samples; must be even and nonzero.
175 pub width: usize,
176 /// The picture's height in luma samples; must be even and nonzero.
177 pub height: usize,
178 /// The quantizer index every frame is coded at (0..=255).
179 pub base_q_idx: u8,
180 /// Pictures between key frames, inclusive of the key frame itself: `1`
181 /// codes every picture as a key frame, `gop` codes picture `gop` (and
182 /// `2*gop`, ...) as a key frame and every other picture inter.
183 pub gop: usize,
184 /// The colour the sequence header signals.
185 pub colour: Colour,
186}
187
188/// One coded picture: its OBUs, in the order a demuxer that just wants bytes
189/// on the wire can concatenate them, and the two things a muxer needs to
190/// know without parsing them back out.
191#[derive(Debug, Clone)]
192pub struct Packet {
193 /// A temporal delimiter, a sequence header and the frame OBU for a key
194 /// frame; a temporal delimiter and the frame OBU alone for an inter
195 /// frame (the sequence header is identical across a stream's key
196 /// frames, since only [`EncoderConfig`]'s own fields feed it, so it is
197 /// simplest to let every key frame carry its own copy rather than have
198 /// the facade special-case the first one).
199 pub data: Vec<u8>,
200 /// Whether this picture was coded as a key frame.
201 pub key: bool,
202 /// This picture's position in the stream, in coding (== presentation,
203 /// since this encoder has no B frames) order, starting at 0.
204 pub order: u64,
205}
206
207/// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per
208/// [`Av1Encoder::encode`] call.
209#[derive(Debug)]
210pub struct Av1Encoder {
211 config: EncoderConfig,
212 color_config: ColorConfig,
213 /// The previous picture's own (padded, uncropped) reconstruction — what
214 /// the next inter frame predicts from — or `None` right after a key
215 /// frame's turn comes up again, where it is about to be replaced rather
216 /// than read.
217 reference: Option<Picture>,
218 next_index: u64,
219 /// `Some` only when constructed via
220 /// [`Av1Encoder::with_rate_target`]`(_, RateTarget::BytesPerFrame(_))`;
221 /// otherwise every picture is coded at `config.base_q_idx`, unchanged
222 /// from before this field existed.
223 rate_loop: Option<RateLoop>,
224}
225
226impl Av1Encoder {
227 /// # Errors
228 /// Returns an error when `config.width`/`config.height` are zero, odd,
229 /// or larger than the 16-bit frame size an AV1 sequence header carries,
230 /// or when `config.gop` is zero (there would be no picture to code the
231 /// next key frame from a cadence of).
232 pub fn new(config: EncoderConfig) -> Result<Self> {
233 if config.gop == 0 {
234 return Err(Error::unsupported("AV1 encode", "gop must be at least 1"));
235 }
236 // Validate the geometry the same way the picture-level entry points
237 // do, before the first `encode()` call rather than only surfacing it
238 // then.
239 Picture::grey(config.width, config.height).check_even()?;
240 Ok(Self {
241 color_config: config.colour.color_config(),
242 config,
243 reference: None,
244 next_index: 0,
245 rate_loop: None,
246 })
247 }
248
249 /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it,
250 /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of
251 /// `config.base_q_idx` being used as-is.
252 ///
253 /// # Errors
254 /// Same as [`Av1Encoder::new`].
255 pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> {
256 let rate_loop = match rate {
257 RateTarget::QIndex(q) => {
258 config.base_q_idx = q;
259 None
260 }
261 RateTarget::Quality(quality) => {
262 config.base_q_idx = quality_to_q_idx(quality);
263 None
264 }
265 RateTarget::BytesPerFrame(target_bytes) => {
266 Some(RateLoop::new(target_bytes, f64::from(config.base_q_idx)))
267 }
268 };
269 let mut encoder = Self::new(config)?;
270 encoder.rate_loop = rate_loop;
271 Ok(encoder)
272 }
273
274 /// The coded (padded-to-64) frame size every picture in this stream is
275 /// coded at — what a decoder allocates and what `ffprobe` reports.
276 #[must_use]
277 pub fn coded_size(&self) -> (usize, usize) {
278 (
279 self.config.width.next_multiple_of(SUPERBLOCK),
280 self.config.height.next_multiple_of(SUPERBLOCK),
281 )
282 }
283
284 /// The display (render) size every frame header signals — [`EncoderConfig`]'s
285 /// own `width`/`height`, always, whatever the coded size pads it to.
286 #[must_use]
287 pub fn display_size(&self) -> (usize, usize) {
288 (self.config.width, self.config.height)
289 }
290
291 /// Encodes one picture, key or inter by this stream's `gop` cadence, and
292 /// returns its packet — always exactly one, never held back for a later
293 /// call.
294 ///
295 /// # Errors
296 /// Returns an error when `picture`'s size does not match
297 /// [`EncoderConfig::width`]/[`EncoderConfig::height`], or under the same
298 /// conditions [`crate::encode::encode_key_frame`]/
299 /// [`crate::encode::encode_sequence`] do.
300 pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {
301 if (picture.width, picture.height) != (self.config.width, self.config.height) {
302 return Err(Error::unsupported(
303 "AV1 encode",
304 format!(
305 "picture is {}x{}, encoder is {}x{}",
306 picture.width, picture.height, self.config.width, self.config.height
307 ),
308 ));
309 }
310 let render = (self.config.width, self.config.height);
311 let padded = picture.padded_to(SUPERBLOCK);
312 let is_key = self.next_index % self.config.gop as u64 == 0;
313 let order = self.next_index;
314 let base_q_idx = self
315 .rate_loop
316 .as_ref()
317 .map_or(self.config.base_q_idx, RateLoop::q_idx);
318
319 let encoded: Encoded = if is_key {
320 encode_key_frame_inner(
321 &padded,
322 base_q_idx,
323 DEADZONE,
324 &KEY_FRAME_MODES,
325 split_blocks(),
326 render,
327 self.color_config,
328 )?
329 } else {
330 let reference = self.reference.as_ref().ok_or_else(|| {
331 Error::unsupported(
332 "AV1 encode",
333 "an inter frame needs a previous reconstruction",
334 )
335 })?;
336 encode_inter_frame(
337 &padded,
338 reference,
339 base_q_idx,
340 DEADZONE,
341 order as u32,
342 render,
343 )?
344 };
345
346 self.reference = Some(encoded.reconstruction.clone());
347 self.next_index += 1;
348 let cropped = crop_encoded(&encoded, render.0, render.1);
349 if let Some(rate_loop) = self.rate_loop.as_mut() {
350 rate_loop.update(cropped.stream.len());
351 }
352 Ok(Packet {
353 data: cropped.stream,
354 key: is_key,
355 order,
356 })
357 }
358}
359
360#[cfg(test)]
361mod tests {
362 use super::*;
363 use std::process::{Command, Stdio};
364
365 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
366 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
367 /// aomenc gate decodes its stream through ffmpeg and is meaningless
368 /// without it -- turns it into a hard failure. Without this the require
369 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
370 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
371 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
372 fn have_ffmpeg() -> bool {
373 let present = Command::new("ffmpeg")
374 .arg("-version")
375 .stdout(Stdio::null())
376 .stderr(Stdio::null())
377 .status()
378 .is_ok_and(|s| s.success());
379 assert!(
380 present
381 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
382 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
383 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
384 );
385 present
386 }
387
388 fn test_card(width: usize, height: usize, shift: usize) -> Picture {
389 let mut picture = Picture::grey(width, height);
390 for y in 0..height {
391 for x in 0..width {
392 let sx = (x + shift) % width;
393 picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16;
394 }
395 }
396 for y in 0..height / 2 {
397 for x in 0..width / 2 {
398 let i = y * (width / 2) + x;
399 picture.u[i] = ((100 + shift * 4) % 256) as u16;
400 picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16;
401 }
402 }
403 picture
404 }
405
406 /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
407 /// in order.
408 fn concat(packets: &[Packet]) -> Vec<u8> {
409 packets.iter().flat_map(|p| p.data.clone()).collect()
410 }
411
412 /// One call to [`Av1Encoder::encode`] returns exactly one packet, always
413 /// — the facade's whole "nothing held back" contract, checked without
414 /// ffmpeg since it is a property of the return type, not the bytes.
415 #[test]
416 fn one_in_one_out() {
417 let config = EncoderConfig {
418 width: 64,
419 height: 64,
420 base_q_idx: 100,
421 gop: 2,
422 colour: Colour::Bt709Limited,
423 };
424 let mut enc = Av1Encoder::new(config).unwrap();
425 for t in 0..5u64 {
426 let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
427 assert!(!packet.data.is_empty(), "picture {t}: empty packet");
428 assert_eq!(packet.order, t, "picture {t}: order");
429 }
430 }
431
432 /// A key frame every `gop` pictures, inter otherwise — checked against
433 /// what the facade itself reports, and (below) against what `ffprobe`
434 /// reads back out of the coded bytes.
435 #[test]
436 fn gop_cadence_is_honored() {
437 let config = EncoderConfig {
438 width: 64,
439 height: 64,
440 base_q_idx: 100,
441 gop: 3,
442 colour: Colour::Unspecified,
443 };
444 let mut enc = Av1Encoder::new(config).unwrap();
445 let keys: Vec<bool> = (0..7)
446 .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key)
447 .collect();
448 assert_eq!(keys, vec![true, false, false, true, false, false, true]);
449 }
450
451 fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {
452 let path = std::env::temp_dir().join(format!(
453 "ec-av1-facade-probe-{}-{}.obu",
454 std::process::id(),
455 std::ptr::addr_of!(stream) as usize
456 ));
457 std::fs::write(&path, stream).expect("writing the probe stream");
458 let out = Command::new("ffprobe")
459 .args([
460 "-v",
461 "error",
462 "-f",
463 "obu",
464 "-select_streams",
465 "v:0",
466 "-show_entries",
467 "frame=key_frame,width,height",
468 "-of",
469 "csv=p=0",
470 ])
471 .arg(&path)
472 .output()
473 .expect("ffprobe failed to run");
474 let _ = std::fs::remove_file(&path);
475 assert!(
476 out.status.success(),
477 "ffprobe refused the stream: {}",
478 String::from_utf8_lossy(&out.stderr)
479 );
480 String::from_utf8_lossy(&out.stdout)
481 .lines()
482 .map(|line| {
483 let mut f = line.trim().split(',');
484 let key: u32 = f.next().unwrap().parse().unwrap();
485 let width: u32 = f.next().unwrap().parse().unwrap();
486 let height: u32 = f.next().unwrap().parse().unwrap();
487 (key == 1, width, height)
488 })
489 .collect()
490 }
491
492 fn ffprobe_colour(stream: &[u8]) -> String {
493 let path = std::env::temp_dir().join(format!(
494 "ec-av1-facade-colour-probe-{}-{}.obu",
495 std::process::id(),
496 std::ptr::addr_of!(stream) as usize
497 ));
498 std::fs::write(&path, stream).expect("writing the probe stream");
499 let out = Command::new("ffprobe")
500 .args([
501 "-v",
502 "error",
503 "-f",
504 "obu",
505 "-select_streams",
506 "v:0",
507 "-show_entries",
508 "stream=color_primaries,color_transfer,color_space,color_range",
509 "-of",
510 "csv=p=0",
511 ])
512 .arg(&path)
513 .output()
514 .expect("ffprobe failed to run");
515 let _ = std::fs::remove_file(&path);
516 assert!(
517 out.status.success(),
518 "ffprobe refused the stream: {}",
519 String::from_utf8_lossy(&out.stderr)
520 );
521 String::from_utf8_lossy(&out.stdout).trim().to_string()
522 }
523
524 /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)
525 /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that
526 /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and
527 /// coded size confirm what the facade already reported.
528 #[test]
529 fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
530 if !have_ffmpeg() {
531 eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg");
532 return;
533 }
534 let (width, height) = (96usize, 96usize);
535 let config = EncoderConfig {
536 width,
537 height,
538 base_q_idx: 120,
539 gop: 15,
540 colour: Colour::Bt709Limited,
541 };
542 let mut enc = Av1Encoder::new(config).unwrap();
543 assert_eq!(enc.display_size(), (width, height));
544 let (coded_w, coded_h) = enc.coded_size();
545 assert_eq!(
546 (coded_w, coded_h),
547 (
548 width.next_multiple_of(SUPERBLOCK),
549 height.next_multiple_of(SUPERBLOCK)
550 )
551 );
552
553 let packets: Vec<Packet> = (0..30)
554 .map(|t| enc.encode(&test_card(width, height, t)).unwrap())
555 .collect();
556 let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect();
557 assert_eq!(
558 packets.iter().map(|p| p.key).collect::<Vec<_>>(),
559 expect_key,
560 "facade's own key/inter flags"
561 );
562
563 let stream = concat(&packets);
564 let frames = ffprobe_frames(&stream);
565 assert_eq!(frames.len(), 30, "ffprobe frame count");
566 for (t, (key, w, h)) in frames.iter().enumerate() {
567 assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag");
568 assert_eq!(
569 (*w, *h),
570 (width as u32, height as u32),
571 "picture {t}: ffprobe reports the true (display) size, not the padded coded one"
572 );
573 }
574 }
575
576 /// The configured colour properties are what `ffprobe` reports back,
577 /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it
578 /// is the default a player assumes and the one this test would silently
579 /// pass without wiring for (`ffprobe` reports "unknown" for the
580 /// hardcoded "unspecified" this crate wrote before the facade existed,
581 /// which is a visibly different string).
582 #[test]
583 fn bt709_limited_colour_is_reported_by_ffprobe() {
584 if !have_ffmpeg() {
585 eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg");
586 return;
587 }
588 let config = EncoderConfig {
589 width: 64,
590 height: 64,
591 base_q_idx: 100,
592 gop: 4,
593 colour: Colour::Bt709Limited,
594 };
595 let mut enc = Av1Encoder::new(config).unwrap();
596 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
597 let colour = ffprobe_colour(&packet.data);
598 assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields");
599 }
600
601 /// The same, for BT.601: a different set of CICP integers must produce a
602 /// different string, or the wiring could be a no-op that happens to read
603 /// as BT.709 for every input.
604 #[test]
605 fn bt601_limited_colour_is_reported_by_ffprobe() {
606 if !have_ffmpeg() {
607 eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg");
608 return;
609 }
610 let config = EncoderConfig {
611 width: 64,
612 height: 64,
613 base_q_idx: 100,
614 gop: 4,
615 colour: Colour::Bt601Limited,
616 };
617 let mut enc = Av1Encoder::new(config).unwrap();
618 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
619 let colour = ffprobe_colour(&packet.data);
620 assert_eq!(
621 colour, "tv,smpte170m,smpte170m,smpte170m",
622 "ffprobe colour fields"
623 );
624 }
625
626 /// A frame whose size does not match the encoder's configured geometry
627 /// is refused by name.
628 #[test]
629 fn geometry_mismatch_is_refused() {
630 let config = EncoderConfig {
631 width: 64,
632 height: 64,
633 base_q_idx: 100,
634 gop: 4,
635 colour: Colour::Bt709Limited,
636 };
637 let mut enc = Av1Encoder::new(config).unwrap();
638 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
639 assert!(err.to_string().contains("64x64"), "{err}");
640 }
641
642 /// `gop == 0` is refused at construction, not the first `encode()` call.
643 #[test]
644 fn zero_gop_is_refused() {
645 let config = EncoderConfig {
646 width: 64,
647 height: 64,
648 base_q_idx: 100,
649 gop: 0,
650 colour: Colour::Bt709Limited,
651 };
652 let err = Av1Encoder::new(config).unwrap_err();
653 assert!(err.to_string().contains("gop"), "{err}");
654 }
655
656 /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget`
657 /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down
658 /// to this facade's own input size, and re-coded through the facade so the
659 /// rate-target surface is exercised at the entry point a caller actually
660 /// drives.
661 fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> {
662 if !have_ffmpeg() {
663 return None;
664 }
665 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
666 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
667 if !clip.exists() {
668 return None;
669 }
670 let out = Command::new("ffmpeg")
671 .args(["-v", "error", "-i", clip.to_str().unwrap()])
672 .args(["-frames:v", &frames.to_string()])
673 .args(["-vf", &format!("scale={width}:{height}")])
674 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
675 .output()
676 .expect("ffmpeg failed to run");
677 assert!(
678 out.status.success(),
679 "{}",
680 String::from_utf8_lossy(&out.stderr)
681 );
682 let (luma, chroma) = (width * height, width * height / 4);
683 let frame_len = luma + 2 * chroma;
684 assert_eq!(
685 out.stdout.len(),
686 frame_len * frames,
687 "expected {frames} 4:2:0 frames"
688 );
689 Some(
690 (0..frames)
691 .map(|i| {
692 let bytes = &out.stdout[i * frame_len..][..frame_len];
693 Picture {
694 width,
695 height,
696 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
697 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
698 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
699 }
700 })
701 .collect(),
702 )
703 }
704
705 /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total
706 /// coded size within ±20% of `frames * target` once the first few
707 /// frames' settling has been discarded (the key frame's own reference
708 /// state and the controller's first couple of steps).
709 #[test]
710 fn bytes_per_frame_target_settles_within_20_percent() {
711 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
712 eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture");
713 return;
714 };
715 let target_bytes = 4_000u32;
716 let config = EncoderConfig {
717 width: 640,
718 height: 384,
719 base_q_idx: 100,
720 gop: 24,
721 colour: Colour::Bt709Limited,
722 };
723 let mut enc =
724 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
725 let sizes: Vec<usize> = pictures
726 .iter()
727 .map(|p| enc.encode(p).unwrap().data.len())
728 .collect();
729 // Discard the key frame (always far larger than an inter target) and
730 // the next 4 inter frames the loop needs to step toward it.
731 let settled = &sizes[5..];
732 let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64;
733 let low = f64::from(target_bytes) * 0.8;
734 let high = f64::from(target_bytes) * 1.2;
735 assert!(
736 mean >= low && mean <= high,
737 "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}"
738 );
739 }
740
741 /// The `BytesPerFrame` controller's own windup bound: no frame's coded
742 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
743 /// clip's full range of content (so a scene cut can't be the one frame
744 /// that breaks the bound).
745 #[test]
746 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
747 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
748 eprintln!(
749 "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture"
750 );
751 return;
752 };
753 let config = EncoderConfig {
754 width: 640,
755 height: 384,
756 base_q_idx: 100,
757 gop: 24,
758 colour: Colour::Bt709Limited,
759 };
760 let mut enc =
761 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
762 let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx();
763 for picture in &pictures {
764 enc.encode(picture).unwrap();
765 let q = enc.rate_loop.as_ref().unwrap().q_idx();
766 let step = (i32::from(q) - i32::from(prev_q)).abs();
767 assert!(
768 f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
769 "q stepped from {prev_q} to {q}, past the {} clamp",
770 RateLoop::STEP_CLAMP
771 );
772 prev_q = q;
773 }
774 }
775
776 fn psnr(a: &[u16], b: &[u16]) -> f64 {
777 let squared: f64 = a
778 .iter()
779 .zip(b)
780 .map(|(&x, &y)| {
781 let d = f64::from(x) - f64::from(y);
782 d * d
783 })
784 .sum();
785 if squared == 0.0 {
786 return f64::INFINITY;
787 }
788 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
789 }
790
791 /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one
792 /// entry per coded frame, in order — this facade's own equivalent of
793 /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
794 /// PSNR check needs the decoded pixels, not just the coded byte count.
795 fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
796 let path = std::env::temp_dir().join(format!(
797 "ec-av1-facade-rate-decode-{}-{}.obu",
798 std::process::id(),
799 std::ptr::addr_of!(stream) as usize
800 ));
801 std::fs::write(&path, stream).expect("writing the decode probe stream");
802 let out = Command::new("ffmpeg")
803 .args(["-v", "error", "-f", "obu", "-i"])
804 .arg(&path)
805 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
806 .output()
807 .expect("ffmpeg failed to run");
808 let _ = std::fs::remove_file(&path);
809 assert!(
810 out.status.success(),
811 "{}",
812 String::from_utf8_lossy(&out.stderr)
813 );
814 let (luma, chroma) = (width * height, width * height / 4);
815 let frame_len = luma + 2 * chroma;
816 out.stdout
817 .chunks_exact(frame_len)
818 .map(|f| f[..luma].to_vec())
819 .collect()
820 }
821
822 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
823 /// produces a smaller stream or a worse mean PSNR than a lower one, on
824 /// the same real clip.
825 #[test]
826 fn quality_target_is_monotone_in_bytes_and_psnr() {
827 if !have_ffmpeg() {
828 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg");
829 return;
830 }
831 let (width, height) = (640, 384);
832 let Some(pictures) = h264_clip_frames(width, height, 8) else {
833 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture");
834 return;
835 };
836 let mut prev_bytes = 0usize;
837 let mut prev_psnr = 0.0f64;
838 for quality in [20u8, 50, 80] {
839 let config = EncoderConfig {
840 width,
841 height,
842 base_q_idx: 100,
843 gop: 8,
844 colour: Colour::Bt709Limited,
845 };
846 let mut enc =
847 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
848 let mut stream = Vec::new();
849 let mut total_bytes = 0usize;
850 for picture in &pictures {
851 let packet = enc.encode(picture).unwrap();
852 total_bytes += packet.data.len();
853 stream.extend_from_slice(&packet.data);
854 }
855 let decoded = ffmpeg_decode_luma(&stream, width, height);
856 assert_eq!(
857 decoded.len(),
858 pictures.len(),
859 "quality {quality}: dav1d frame count"
860 );
861 let mean_psnr: f64 = decoded
862 .iter()
863 .zip(&pictures)
864 .map(|(d, p)| {
865 let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect();
866 psnr(&d16, &p.y)
867 })
868 .sum::<f64>()
869 / decoded.len() as f64;
870 assert!(
871 total_bytes >= prev_bytes,
872 "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}"
873 );
874 assert!(
875 mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours
876 "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB"
877 );
878 prev_bytes = total_bytes;
879 prev_psnr = mean_psnr;
880 }
881 }
882}