forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBb07f07aTahinli3 months ago1061 commits

encoder.rs865 lines, 33.3 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 fn have_ffmpeg() -> bool {
366 Command::new("ffmpeg")
367 .arg("-version")
368 .stdout(Stdio::null())
369 .stderr(Stdio::null())
370 .status()
371 .is_ok_and(|s| s.success())
372 }
373
374 fn test_card(width: usize, height: usize, shift: usize) -> Picture {
375 let mut picture = Picture::grey(width, height);
376 for y in 0..height {
377 for x in 0..width {
378 let sx = (x + shift) % width;
379 picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u8;
380 }
381 }
382 for y in 0..height / 2 {
383 for x in 0..width / 2 {
384 let i = y * (width / 2) + x;
385 picture.u[i] = ((100 + shift * 4) % 256) as u8;
386 picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u8;
387 }
388 }
389 picture
390 }
391
392 /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
393 /// in order.
394 fn concat(packets: &[Packet]) -> Vec<u8> {
395 packets.iter().flat_map(|p| p.data.clone()).collect()
396 }
397
398 /// One call to [`Av1Encoder::encode`] returns exactly one packet, always
399 /// — the facade's whole "nothing held back" contract, checked without
400 /// ffmpeg since it is a property of the return type, not the bytes.
401 #[test]
402 fn one_in_one_out() {
403 let config = EncoderConfig {
404 width: 64,
405 height: 64,
406 base_q_idx: 100,
407 gop: 2,
408 colour: Colour::Bt709Limited,
409 };
410 let mut enc = Av1Encoder::new(config).unwrap();
411 for t in 0..5u64 {
412 let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
413 assert!(!packet.data.is_empty(), "picture {t}: empty packet");
414 assert_eq!(packet.order, t, "picture {t}: order");
415 }
416 }
417
418 /// A key frame every `gop` pictures, inter otherwise — checked against
419 /// what the facade itself reports, and (below) against what `ffprobe`
420 /// reads back out of the coded bytes.
421 #[test]
422 fn gop_cadence_is_honored() {
423 let config = EncoderConfig {
424 width: 64,
425 height: 64,
426 base_q_idx: 100,
427 gop: 3,
428 colour: Colour::Unspecified,
429 };
430 let mut enc = Av1Encoder::new(config).unwrap();
431 let keys: Vec<bool> = (0..7)
432 .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key)
433 .collect();
434 assert_eq!(keys, vec![true, false, false, true, false, false, true]);
435 }
436
437 fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {
438 let path = std::env::temp_dir().join(format!(
439 "ec-av1-facade-probe-{}-{}.obu",
440 std::process::id(),
441 std::ptr::addr_of!(stream) as usize
442 ));
443 std::fs::write(&path, stream).expect("writing the probe stream");
444 let out = Command::new("ffprobe")
445 .args([
446 "-v",
447 "error",
448 "-f",
449 "obu",
450 "-select_streams",
451 "v:0",
452 "-show_entries",
453 "frame=key_frame,width,height",
454 "-of",
455 "csv=p=0",
456 ])
457 .arg(&path)
458 .output()
459 .expect("ffprobe failed to run");
460 let _ = std::fs::remove_file(&path);
461 assert!(
462 out.status.success(),
463 "ffprobe refused the stream: {}",
464 String::from_utf8_lossy(&out.stderr)
465 );
466 String::from_utf8_lossy(&out.stdout)
467 .lines()
468 .map(|line| {
469 let mut f = line.trim().split(',');
470 let key: u32 = f.next().unwrap().parse().unwrap();
471 let width: u32 = f.next().unwrap().parse().unwrap();
472 let height: u32 = f.next().unwrap().parse().unwrap();
473 (key == 1, width, height)
474 })
475 .collect()
476 }
477
478 fn ffprobe_colour(stream: &[u8]) -> String {
479 let path = std::env::temp_dir().join(format!(
480 "ec-av1-facade-colour-probe-{}-{}.obu",
481 std::process::id(),
482 std::ptr::addr_of!(stream) as usize
483 ));
484 std::fs::write(&path, stream).expect("writing the probe stream");
485 let out = Command::new("ffprobe")
486 .args([
487 "-v",
488 "error",
489 "-f",
490 "obu",
491 "-select_streams",
492 "v:0",
493 "-show_entries",
494 "stream=color_primaries,color_transfer,color_space,color_range",
495 "-of",
496 "csv=p=0",
497 ])
498 .arg(&path)
499 .output()
500 .expect("ffprobe failed to run");
501 let _ = std::fs::remove_file(&path);
502 assert!(
503 out.status.success(),
504 "ffprobe refused the stream: {}",
505 String::from_utf8_lossy(&out.stderr)
506 );
507 String::from_utf8_lossy(&out.stdout).trim().to_string()
508 }
509
510 /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)
511 /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that
512 /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and
513 /// coded size confirm what the facade already reported.
514 #[test]
515 fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
516 if !have_ffmpeg() {
517 eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg");
518 return;
519 }
520 let (width, height) = (96usize, 96usize);
521 let config = EncoderConfig {
522 width,
523 height,
524 base_q_idx: 120,
525 gop: 15,
526 colour: Colour::Bt709Limited,
527 };
528 let mut enc = Av1Encoder::new(config).unwrap();
529 assert_eq!(enc.display_size(), (width, height));
530 let (coded_w, coded_h) = enc.coded_size();
531 assert_eq!(
532 (coded_w, coded_h),
533 (
534 width.next_multiple_of(SUPERBLOCK),
535 height.next_multiple_of(SUPERBLOCK)
536 )
537 );
538
539 let packets: Vec<Packet> = (0..30)
540 .map(|t| enc.encode(&test_card(width, height, t)).unwrap())
541 .collect();
542 let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect();
543 assert_eq!(
544 packets.iter().map(|p| p.key).collect::<Vec<_>>(),
545 expect_key,
546 "facade's own key/inter flags"
547 );
548
549 let stream = concat(&packets);
550 let frames = ffprobe_frames(&stream);
551 assert_eq!(frames.len(), 30, "ffprobe frame count");
552 for (t, (key, w, h)) in frames.iter().enumerate() {
553 assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag");
554 assert_eq!(
555 (*w, *h),
556 (width as u32, height as u32),
557 "picture {t}: ffprobe reports the true (display) size, not the padded coded one"
558 );
559 }
560 }
561
562 /// The configured colour properties are what `ffprobe` reports back,
563 /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it
564 /// is the default a player assumes and the one this test would silently
565 /// pass without wiring for (`ffprobe` reports "unknown" for the
566 /// hardcoded "unspecified" this crate wrote before the facade existed,
567 /// which is a visibly different string).
568 #[test]
569 fn bt709_limited_colour_is_reported_by_ffprobe() {
570 if !have_ffmpeg() {
571 eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg");
572 return;
573 }
574 let config = EncoderConfig {
575 width: 64,
576 height: 64,
577 base_q_idx: 100,
578 gop: 4,
579 colour: Colour::Bt709Limited,
580 };
581 let mut enc = Av1Encoder::new(config).unwrap();
582 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
583 let colour = ffprobe_colour(&packet.data);
584 assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields");
585 }
586
587 /// The same, for BT.601: a different set of CICP integers must produce a
588 /// different string, or the wiring could be a no-op that happens to read
589 /// as BT.709 for every input.
590 #[test]
591 fn bt601_limited_colour_is_reported_by_ffprobe() {
592 if !have_ffmpeg() {
593 eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg");
594 return;
595 }
596 let config = EncoderConfig {
597 width: 64,
598 height: 64,
599 base_q_idx: 100,
600 gop: 4,
601 colour: Colour::Bt601Limited,
602 };
603 let mut enc = Av1Encoder::new(config).unwrap();
604 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
605 let colour = ffprobe_colour(&packet.data);
606 assert_eq!(
607 colour, "tv,smpte170m,smpte170m,smpte170m",
608 "ffprobe colour fields"
609 );
610 }
611
612 /// A frame whose size does not match the encoder's configured geometry
613 /// is refused by name.
614 #[test]
615 fn geometry_mismatch_is_refused() {
616 let config = EncoderConfig {
617 width: 64,
618 height: 64,
619 base_q_idx: 100,
620 gop: 4,
621 colour: Colour::Bt709Limited,
622 };
623 let mut enc = Av1Encoder::new(config).unwrap();
624 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
625 assert!(err.to_string().contains("64x64"), "{err}");
626 }
627
628 /// `gop == 0` is refused at construction, not the first `encode()` call.
629 #[test]
630 fn zero_gop_is_refused() {
631 let config = EncoderConfig {
632 width: 64,
633 height: 64,
634 base_q_idx: 100,
635 gop: 0,
636 colour: Colour::Bt709Limited,
637 };
638 let err = Av1Encoder::new(config).unwrap_err();
639 assert!(err.to_string().contains("gop"), "{err}");
640 }
641
642 /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget`
643 /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down
644 /// to this facade's own input size, and re-coded through the facade so the
645 /// rate-target surface is exercised at the entry point a caller actually
646 /// drives.
647 fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> {
648 if !have_ffmpeg() {
649 return None;
650 }
651 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
652 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
653 if !clip.exists() {
654 return None;
655 }
656 let out = Command::new("ffmpeg")
657 .args(["-v", "error", "-i", clip.to_str().unwrap()])
658 .args(["-frames:v", &frames.to_string()])
659 .args(["-vf", &format!("scale={width}:{height}")])
660 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
661 .output()
662 .expect("ffmpeg failed to run");
663 assert!(
664 out.status.success(),
665 "{}",
666 String::from_utf8_lossy(&out.stderr)
667 );
668 let (luma, chroma) = (width * height, width * height / 4);
669 let frame_len = luma + 2 * chroma;
670 assert_eq!(
671 out.stdout.len(),
672 frame_len * frames,
673 "expected {frames} 4:2:0 frames"
674 );
675 Some(
676 (0..frames)
677 .map(|i| {
678 let bytes = &out.stdout[i * frame_len..][..frame_len];
679 Picture {
680 width,
681 height,
682 y: bytes[..luma].to_vec(),
683 u: bytes[luma..luma + chroma].to_vec(),
684 v: bytes[luma + chroma..].to_vec(),
685 }
686 })
687 .collect(),
688 )
689 }
690
691 /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total
692 /// coded size within ±20% of `frames * target` once the first few
693 /// frames' settling has been discarded (the key frame's own reference
694 /// state and the controller's first couple of steps).
695 #[test]
696 fn bytes_per_frame_target_settles_within_20_percent() {
697 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
698 eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture");
699 return;
700 };
701 let target_bytes = 4_000u32;
702 let config = EncoderConfig {
703 width: 640,
704 height: 384,
705 base_q_idx: 100,
706 gop: 24,
707 colour: Colour::Bt709Limited,
708 };
709 let mut enc =
710 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
711 let sizes: Vec<usize> = pictures
712 .iter()
713 .map(|p| enc.encode(p).unwrap().data.len())
714 .collect();
715 // Discard the key frame (always far larger than an inter target) and
716 // the next 4 inter frames the loop needs to step toward it.
717 let settled = &sizes[5..];
718 let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64;
719 let low = f64::from(target_bytes) * 0.8;
720 let high = f64::from(target_bytes) * 1.2;
721 assert!(
722 mean >= low && mean <= high,
723 "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}"
724 );
725 }
726
727 /// The `BytesPerFrame` controller's own windup bound: no frame's coded
728 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
729 /// clip's full range of content (so a scene cut can't be the one frame
730 /// that breaks the bound).
731 #[test]
732 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
733 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
734 eprintln!(
735 "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture"
736 );
737 return;
738 };
739 let config = EncoderConfig {
740 width: 640,
741 height: 384,
742 base_q_idx: 100,
743 gop: 24,
744 colour: Colour::Bt709Limited,
745 };
746 let mut enc =
747 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
748 let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx();
749 for picture in &pictures {
750 enc.encode(picture).unwrap();
751 let q = enc.rate_loop.as_ref().unwrap().q_idx();
752 let step = (i32::from(q) - i32::from(prev_q)).abs();
753 assert!(
754 f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
755 "q stepped from {prev_q} to {q}, past the {} clamp",
756 RateLoop::STEP_CLAMP
757 );
758 prev_q = q;
759 }
760 }
761
762 fn psnr(a: &[u8], b: &[u8]) -> f64 {
763 let squared: f64 = a
764 .iter()
765 .zip(b)
766 .map(|(&x, &y)| {
767 let d = f64::from(x) - f64::from(y);
768 d * d
769 })
770 .sum();
771 if squared == 0.0 {
772 return f64::INFINITY;
773 }
774 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
775 }
776
777 /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one
778 /// entry per coded frame, in order — this facade's own equivalent of
779 /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
780 /// PSNR check needs the decoded pixels, not just the coded byte count.
781 fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
782 let path = std::env::temp_dir().join(format!(
783 "ec-av1-facade-rate-decode-{}-{}.obu",
784 std::process::id(),
785 std::ptr::addr_of!(stream) as usize
786 ));
787 std::fs::write(&path, stream).expect("writing the decode probe stream");
788 let out = Command::new("ffmpeg")
789 .args(["-v", "error", "-f", "obu", "-i"])
790 .arg(&path)
791 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
792 .output()
793 .expect("ffmpeg failed to run");
794 let _ = std::fs::remove_file(&path);
795 assert!(
796 out.status.success(),
797 "{}",
798 String::from_utf8_lossy(&out.stderr)
799 );
800 let (luma, chroma) = (width * height, width * height / 4);
801 let frame_len = luma + 2 * chroma;
802 out.stdout
803 .chunks_exact(frame_len)
804 .map(|f| f[..luma].to_vec())
805 .collect()
806 }
807
808 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
809 /// produces a smaller stream or a worse mean PSNR than a lower one, on
810 /// the same real clip.
811 #[test]
812 fn quality_target_is_monotone_in_bytes_and_psnr() {
813 if !have_ffmpeg() {
814 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg");
815 return;
816 }
817 let (width, height) = (640, 384);
818 let Some(pictures) = h264_clip_frames(width, height, 8) else {
819 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture");
820 return;
821 };
822 let mut prev_bytes = 0usize;
823 let mut prev_psnr = 0.0f64;
824 for quality in [20u8, 50, 80] {
825 let config = EncoderConfig {
826 width,
827 height,
828 base_q_idx: 100,
829 gop: 8,
830 colour: Colour::Bt709Limited,
831 };
832 let mut enc =
833 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
834 let mut stream = Vec::new();
835 let mut total_bytes = 0usize;
836 for picture in &pictures {
837 let packet = enc.encode(picture).unwrap();
838 total_bytes += packet.data.len();
839 stream.extend_from_slice(&packet.data);
840 }
841 let decoded = ffmpeg_decode_luma(&stream, width, height);
842 assert_eq!(
843 decoded.len(),
844 pictures.len(),
845 "quality {quality}: dav1d frame count"
846 );
847 let mean_psnr: f64 = decoded
848 .iter()
849 .zip(&pictures)
850 .map(|(d, p)| psnr(d, &p.y))
851 .sum::<f64>()
852 / decoded.len() as f64;
853 assert!(
854 total_bytes >= prev_bytes,
855 "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}"
856 );
857 assert!(
858 mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours
859 "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB"
860 );
861 prev_bytes = total_bytes;
862 prev_psnr = mean_psnr;
863 }
864 }
865}