forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2a2adbaTahinli2 months ago2117 commits

encoder.rs898 lines, 35.1 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 /// This stream's decode-side per-frame state, owned here so `encode`
225 /// keeps the public signature it had before the state stopped being
226 /// thread-local. One per encoder, never per frame: several of its fields
227 /// (the inter-frame inheritance guards) carry state ACROSS frames.
228 fctx: crate::decode::FrameCtx,
229}
230
231/// The encoder stays `Send` now that it owns a `FrameCtx` (whose cells are
232/// `Send` but `!Sync`): it can move to another thread, it just cannot be
233/// shared by reference across threads.
234const _: fn() = || {
235 fn assert_send<T: Send>() {}
236 assert_send::<Av1Encoder>();
237};
238
239impl Av1Encoder {
240 /// # Errors
241 /// Returns an error when `config.width`/`config.height` are zero, odd,
242 /// or larger than the 16-bit frame size an AV1 sequence header carries,
243 /// or when `config.gop` is zero (there would be no picture to code the
244 /// next key frame from a cadence of).
245 pub fn new(config: EncoderConfig) -> Result<Self> {
246 if config.gop == 0 {
247 return Err(Error::unsupported("AV1 encode", "gop must be at least 1"));
248 }
249 // Validate the geometry the same way the picture-level entry points
250 // do, before the first `encode()` call rather than only surfacing it
251 // then.
252 Picture::grey(config.width, config.height).check_even()?;
253 Ok(Self {
254 color_config: config.colour.color_config(),
255 config,
256 reference: None,
257 next_index: 0,
258 rate_loop: None,
259 fctx: crate::decode::FrameCtx::new(),
260 })
261 }
262
263 /// [`Av1Encoder::new`], but `rate` picks `base_q_idx` (or steers it,
264 /// frame by frame, for [`RateTarget::BytesPerFrame`]) instead of
265 /// `config.base_q_idx` being used as-is.
266 ///
267 /// # Errors
268 /// Same as [`Av1Encoder::new`].
269 pub fn with_rate_target(mut config: EncoderConfig, rate: RateTarget) -> Result<Self> {
270 let rate_loop = match rate {
271 RateTarget::QIndex(q) => {
272 config.base_q_idx = q;
273 None
274 }
275 RateTarget::Quality(quality) => {
276 config.base_q_idx = quality_to_q_idx(quality);
277 None
278 }
279 RateTarget::BytesPerFrame(target_bytes) => {
280 Some(RateLoop::new(target_bytes, f64::from(config.base_q_idx)))
281 }
282 };
283 let mut encoder = Self::new(config)?;
284 encoder.rate_loop = rate_loop;
285 Ok(encoder)
286 }
287
288 /// The coded (padded-to-64) frame size every picture in this stream is
289 /// coded at — what a decoder allocates and what `ffprobe` reports.
290 #[must_use]
291 pub fn coded_size(&self) -> (usize, usize) {
292 (
293 self.config.width.next_multiple_of(SUPERBLOCK),
294 self.config.height.next_multiple_of(SUPERBLOCK),
295 )
296 }
297
298 /// The display (render) size every frame header signals — [`EncoderConfig`]'s
299 /// own `width`/`height`, always, whatever the coded size pads it to.
300 #[must_use]
301 pub fn display_size(&self) -> (usize, usize) {
302 (self.config.width, self.config.height)
303 }
304
305 /// Encodes one picture, key or inter by this stream's `gop` cadence, and
306 /// returns its packet — always exactly one, never held back for a later
307 /// call.
308 ///
309 /// # Errors
310 /// Returns an error when `picture`'s size does not match
311 /// [`EncoderConfig::width`]/[`EncoderConfig::height`], or under the same
312 /// conditions [`crate::encode::encode_key_frame`]/
313 /// [`crate::encode::encode_sequence`] do.
314 pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {
315 if (picture.width, picture.height) != (self.config.width, self.config.height) {
316 return Err(Error::unsupported(
317 "AV1 encode",
318 format!(
319 "picture is {}x{}, encoder is {}x{}",
320 picture.width, picture.height, self.config.width, self.config.height
321 ),
322 ));
323 }
324 let render = (self.config.width, self.config.height);
325 let padded = picture.padded_to(SUPERBLOCK);
326 let is_key = self.next_index % self.config.gop as u64 == 0;
327 let order = self.next_index;
328 let base_q_idx = self
329 .rate_loop
330 .as_ref()
331 .map_or(self.config.base_q_idx, RateLoop::q_idx);
332
333 let encoded: Encoded = if is_key {
334 encode_key_frame_inner(
335 &padded,
336 base_q_idx,
337 DEADZONE,
338 &KEY_FRAME_MODES,
339 split_blocks(),
340 render,
341 self.color_config,
342 &self.fctx,
343 )?
344 } else {
345 let reference = self.reference.as_ref().ok_or_else(|| {
346 Error::unsupported(
347 "AV1 encode",
348 "an inter frame needs a previous reconstruction",
349 )
350 })?;
351 encode_inter_frame(
352 &padded,
353 reference,
354 base_q_idx,
355 DEADZONE,
356 order as u32,
357 render,
358 &self.fctx,
359 )?
360 };
361
362 self.reference = Some(encoded.reconstruction.clone());
363 self.next_index += 1;
364 let cropped = crop_encoded(&encoded, render.0, render.1);
365 if let Some(rate_loop) = self.rate_loop.as_mut() {
366 rate_loop.update(cropped.stream.len());
367 }
368 Ok(Packet {
369 data: cropped.stream,
370 key: is_key,
371 order,
372 })
373 }
374}
375
376#[cfg(test)]
377mod tests {
378 use super::*;
379 use std::process::{Command, Stdio};
380
381 /// Whether ffmpeg is on PATH. Absence normally SKIPs, but
382 /// `EC_AV1_REQUIRE_FFMPEG=1` -- or `EC_AV1_REQUIRE_AOMENC=1`, since every
383 /// aomenc gate decodes its stream through ffmpeg and is meaningless
384 /// without it -- turns it into a hard failure. Without this the require
385 /// flag was silently short-circuited: `!have_ffmpeg()` is evaluated first
386 /// in `if !have_ffmpeg() || !have_aomenc()`, so a machine with no ffmpeg
387 /// printed SKIP and reported green (class gate-skips-on-its-own-failure).
388 fn have_ffmpeg() -> bool {
389 let present = Command::new("ffmpeg")
390 .arg("-version")
391 .stdout(Stdio::null())
392 .stderr(Stdio::null())
393 .status()
394 .is_ok_and(|s| s.success());
395 assert!(
396 present
397 || (std::env::var_os("EC_AV1_REQUIRE_FFMPEG").is_none()
398 && std::env::var_os("EC_AV1_REQUIRE_AOMENC").is_none()),
399 "EC_AV1_REQUIRE_FFMPEG/EC_AV1_REQUIRE_AOMENC is set but no working ffmpeg on PATH"
400 );
401 present
402 }
403
404 fn test_card(width: usize, height: usize, shift: usize) -> Picture {
405 let mut picture = Picture::grey(width, height);
406 for y in 0..height {
407 for x in 0..width {
408 let sx = (x + shift) % width;
409 picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u16;
410 }
411 }
412 for y in 0..height / 2 {
413 for x in 0..width / 2 {
414 let i = y * (width / 2) + x;
415 picture.u[i] = ((100 + shift * 4) % 256) as u16;
416 picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u16;
417 }
418 }
419 picture
420 }
421
422 /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
423 /// in order.
424 fn concat(packets: &[Packet]) -> Vec<u8> {
425 packets.iter().flat_map(|p| p.data.clone()).collect()
426 }
427
428 /// One call to [`Av1Encoder::encode`] returns exactly one packet, always
429 /// — the facade's whole "nothing held back" contract, checked without
430 /// ffmpeg since it is a property of the return type, not the bytes.
431 #[test]
432 fn one_in_one_out() {
433 let config = EncoderConfig {
434 width: 64,
435 height: 64,
436 base_q_idx: 100,
437 gop: 2,
438 colour: Colour::Bt709Limited,
439 };
440 let mut enc = Av1Encoder::new(config).unwrap();
441 for t in 0..5u64 {
442 let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
443 assert!(!packet.data.is_empty(), "picture {t}: empty packet");
444 assert_eq!(packet.order, t, "picture {t}: order");
445 }
446 }
447
448 /// A key frame every `gop` pictures, inter otherwise — checked against
449 /// what the facade itself reports, and (below) against what `ffprobe`
450 /// reads back out of the coded bytes.
451 #[test]
452 fn gop_cadence_is_honored() {
453 let config = EncoderConfig {
454 width: 64,
455 height: 64,
456 base_q_idx: 100,
457 gop: 3,
458 colour: Colour::Unspecified,
459 };
460 let mut enc = Av1Encoder::new(config).unwrap();
461 let keys: Vec<bool> = (0..7)
462 .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key)
463 .collect();
464 assert_eq!(keys, vec![true, false, false, true, false, false, true]);
465 }
466
467 fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {
468 let path = std::env::temp_dir().join(format!(
469 "ec-av1-facade-probe-{}-{}.obu",
470 std::process::id(),
471 std::ptr::addr_of!(stream) as usize
472 ));
473 std::fs::write(&path, stream).expect("writing the probe stream");
474 let out = Command::new("ffprobe")
475 .args([
476 "-v",
477 "error",
478 "-f",
479 "obu",
480 "-select_streams",
481 "v:0",
482 "-show_entries",
483 "frame=key_frame,width,height",
484 "-of",
485 "csv=p=0",
486 ])
487 .arg(&path)
488 .output()
489 .expect("ffprobe failed to run");
490 let _ = std::fs::remove_file(&path);
491 assert!(
492 out.status.success(),
493 "ffprobe refused the stream: {}",
494 String::from_utf8_lossy(&out.stderr)
495 );
496 String::from_utf8_lossy(&out.stdout)
497 .lines()
498 .map(|line| {
499 let mut f = line.trim().split(',');
500 let key: u32 = f.next().unwrap().parse().unwrap();
501 let width: u32 = f.next().unwrap().parse().unwrap();
502 let height: u32 = f.next().unwrap().parse().unwrap();
503 (key == 1, width, height)
504 })
505 .collect()
506 }
507
508 fn ffprobe_colour(stream: &[u8]) -> String {
509 let path = std::env::temp_dir().join(format!(
510 "ec-av1-facade-colour-probe-{}-{}.obu",
511 std::process::id(),
512 std::ptr::addr_of!(stream) as usize
513 ));
514 std::fs::write(&path, stream).expect("writing the probe stream");
515 let out = Command::new("ffprobe")
516 .args([
517 "-v",
518 "error",
519 "-f",
520 "obu",
521 "-select_streams",
522 "v:0",
523 "-show_entries",
524 "stream=color_primaries,color_transfer,color_space,color_range",
525 "-of",
526 "csv=p=0",
527 ])
528 .arg(&path)
529 .output()
530 .expect("ffprobe failed to run");
531 let _ = std::fs::remove_file(&path);
532 assert!(
533 out.status.success(),
534 "ffprobe refused the stream: {}",
535 String::from_utf8_lossy(&out.stderr)
536 );
537 String::from_utf8_lossy(&out.stdout).trim().to_string()
538 }
539
540 /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)
541 /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that
542 /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and
543 /// coded size confirm what the facade already reported.
544 #[test]
545 fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
546 if !have_ffmpeg() {
547 eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg");
548 return;
549 }
550 let (width, height) = (96usize, 96usize);
551 let config = EncoderConfig {
552 width,
553 height,
554 base_q_idx: 120,
555 gop: 15,
556 colour: Colour::Bt709Limited,
557 };
558 let mut enc = Av1Encoder::new(config).unwrap();
559 assert_eq!(enc.display_size(), (width, height));
560 let (coded_w, coded_h) = enc.coded_size();
561 assert_eq!(
562 (coded_w, coded_h),
563 (
564 width.next_multiple_of(SUPERBLOCK),
565 height.next_multiple_of(SUPERBLOCK)
566 )
567 );
568
569 let packets: Vec<Packet> = (0..30)
570 .map(|t| enc.encode(&test_card(width, height, t)).unwrap())
571 .collect();
572 let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect();
573 assert_eq!(
574 packets.iter().map(|p| p.key).collect::<Vec<_>>(),
575 expect_key,
576 "facade's own key/inter flags"
577 );
578
579 let stream = concat(&packets);
580 let frames = ffprobe_frames(&stream);
581 assert_eq!(frames.len(), 30, "ffprobe frame count");
582 for (t, (key, w, h)) in frames.iter().enumerate() {
583 assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag");
584 assert_eq!(
585 (*w, *h),
586 (width as u32, height as u32),
587 "picture {t}: ffprobe reports the true (display) size, not the padded coded one"
588 );
589 }
590 }
591
592 /// The configured colour properties are what `ffprobe` reports back,
593 /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it
594 /// is the default a player assumes and the one this test would silently
595 /// pass without wiring for (`ffprobe` reports "unknown" for the
596 /// hardcoded "unspecified" this crate wrote before the facade existed,
597 /// which is a visibly different string).
598 #[test]
599 fn bt709_limited_colour_is_reported_by_ffprobe() {
600 if !have_ffmpeg() {
601 eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg");
602 return;
603 }
604 let config = EncoderConfig {
605 width: 64,
606 height: 64,
607 base_q_idx: 100,
608 gop: 4,
609 colour: Colour::Bt709Limited,
610 };
611 let mut enc = Av1Encoder::new(config).unwrap();
612 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
613 let colour = ffprobe_colour(&packet.data);
614 assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields");
615 }
616
617 /// The same, for BT.601: a different set of CICP integers must produce a
618 /// different string, or the wiring could be a no-op that happens to read
619 /// as BT.709 for every input.
620 #[test]
621 fn bt601_limited_colour_is_reported_by_ffprobe() {
622 if !have_ffmpeg() {
623 eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg");
624 return;
625 }
626 let config = EncoderConfig {
627 width: 64,
628 height: 64,
629 base_q_idx: 100,
630 gop: 4,
631 colour: Colour::Bt601Limited,
632 };
633 let mut enc = Av1Encoder::new(config).unwrap();
634 let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
635 let colour = ffprobe_colour(&packet.data);
636 assert_eq!(
637 colour, "tv,smpte170m,smpte170m,smpte170m",
638 "ffprobe colour fields"
639 );
640 }
641
642 /// A frame whose size does not match the encoder's configured geometry
643 /// is refused by name.
644 #[test]
645 fn geometry_mismatch_is_refused() {
646 let config = EncoderConfig {
647 width: 64,
648 height: 64,
649 base_q_idx: 100,
650 gop: 4,
651 colour: Colour::Bt709Limited,
652 };
653 let mut enc = Av1Encoder::new(config).unwrap();
654 let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
655 assert!(err.to_string().contains("64x64"), "{err}");
656 }
657
658 /// `gop == 0` is refused at construction, not the first `encode()` call.
659 #[test]
660 fn zero_gop_is_refused() {
661 let config = EncoderConfig {
662 width: 64,
663 height: 64,
664 base_q_idx: 100,
665 gop: 0,
666 colour: Colour::Bt709Limited,
667 };
668 let err = Av1Encoder::new(config).unwrap_err();
669 assert!(err.to_string().contains("gop"), "{err}");
670 }
671
672 /// The 12-frame real clip `real_clip_encodes_within_its_quality_and_size_budget`
673 /// already gates on at `q=100` (`crates/ec-av1/src/encode.rs`), decoded down
674 /// to this facade's own input size, and re-coded through the facade so the
675 /// rate-target surface is exercised at the entry point a caller actually
676 /// drives.
677 fn h264_clip_frames(width: usize, height: usize, frames: usize) -> Option<Vec<Picture>> {
678 if !have_ffmpeg() {
679 return None;
680 }
681 let clip = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
682 .join("../../fixtures/video/h264-1080p-23.976-8bit.mp4");
683 if !clip.exists() {
684 return None;
685 }
686 let out = Command::new("ffmpeg")
687 .args(["-v", "error", "-i", clip.to_str().unwrap()])
688 .args(["-frames:v", &frames.to_string()])
689 .args(["-vf", &format!("scale={width}:{height}")])
690 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
691 .output()
692 .expect("ffmpeg failed to run");
693 assert!(
694 out.status.success(),
695 "{}",
696 String::from_utf8_lossy(&out.stderr)
697 );
698 let (luma, chroma) = (width * height, width * height / 4);
699 let frame_len = luma + 2 * chroma;
700 assert_eq!(
701 out.stdout.len(),
702 frame_len * frames,
703 "expected {frames} 4:2:0 frames"
704 );
705 Some(
706 (0..frames)
707 .map(|i| {
708 let bytes = &out.stdout[i * frame_len..][..frame_len];
709 Picture {
710 width,
711 height,
712 y: bytes[..luma].iter().map(|&v| u16::from(v)).collect(),
713 u: bytes[luma..luma + chroma].iter().map(|&v| u16::from(v)).collect(),
714 v: bytes[luma + chroma..].iter().map(|&v| u16::from(v)).collect(),
715 }
716 })
717 .collect(),
718 )
719 }
720
721 /// [`RateTarget::BytesPerFrame`] on a real, 24-frame clip lands its total
722 /// coded size within ±20% of `frames * target` once the first few
723 /// frames' settling has been discarded (the key frame's own reference
724 /// state and the controller's first couple of steps).
725 #[test]
726 fn bytes_per_frame_target_settles_within_20_percent() {
727 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
728 eprintln!("SKIP bytes_per_frame_target_settles_within_20_percent: no ffmpeg/fixture");
729 return;
730 };
731 let target_bytes = 4_000u32;
732 let config = EncoderConfig {
733 width: 640,
734 height: 384,
735 base_q_idx: 100,
736 gop: 24,
737 colour: Colour::Bt709Limited,
738 };
739 let mut enc =
740 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(target_bytes)).unwrap();
741 let sizes: Vec<usize> = pictures
742 .iter()
743 .map(|p| enc.encode(p).unwrap().data.len())
744 .collect();
745 // Discard the key frame (always far larger than an inter target) and
746 // the next 4 inter frames the loop needs to step toward it.
747 let settled = &sizes[5..];
748 let mean = settled.iter().sum::<usize>() as f64 / settled.len() as f64;
749 let low = f64::from(target_bytes) * 0.8;
750 let high = f64::from(target_bytes) * 1.2;
751 assert!(
752 mean >= low && mean <= high,
753 "settled mean {mean:.0} bytes/frame outside ±20% of {target_bytes} ({low:.0}..{high:.0}); sizes={sizes:?}"
754 );
755 }
756
757 /// The `BytesPerFrame` controller's own windup bound: no frame's coded
758 /// `base_q_idx` step exceeds [`RateLoop::STEP_CLAMP`], across a real
759 /// clip's full range of content (so a scene cut can't be the one frame
760 /// that breaks the bound).
761 #[test]
762 fn bytes_per_frame_controller_never_oscillates_past_its_clamp() {
763 let Some(pictures) = h264_clip_frames(640, 384, 24) else {
764 eprintln!(
765 "SKIP bytes_per_frame_controller_never_oscillates_past_its_clamp: no ffmpeg/fixture"
766 );
767 return;
768 };
769 let config = EncoderConfig {
770 width: 640,
771 height: 384,
772 base_q_idx: 100,
773 gop: 24,
774 colour: Colour::Bt709Limited,
775 };
776 let mut enc =
777 Av1Encoder::with_rate_target(config, RateTarget::BytesPerFrame(4_000)).unwrap();
778 let mut prev_q = enc.rate_loop.as_ref().unwrap().q_idx();
779 for picture in &pictures {
780 enc.encode(picture).unwrap();
781 let q = enc.rate_loop.as_ref().unwrap().q_idx();
782 let step = (i32::from(q) - i32::from(prev_q)).abs();
783 assert!(
784 f64::from(step) <= RateLoop::STEP_CLAMP + 1.0, // +1 for u8 rounding
785 "q stepped from {prev_q} to {q}, past the {} clamp",
786 RateLoop::STEP_CLAMP
787 );
788 prev_q = q;
789 }
790 }
791
792 fn psnr(a: &[u16], b: &[u16]) -> f64 {
793 let squared: f64 = a
794 .iter()
795 .zip(b)
796 .map(|(&x, &y)| {
797 let d = f64::from(x) - f64::from(y);
798 d * d
799 })
800 .sum();
801 if squared == 0.0 {
802 return f64::INFINITY;
803 }
804 10.0 * (255.0 * 255.0 * a.len() as f64 / squared).log10()
805 }
806
807 /// Decodes an OBU stream back to raw luma planes via `ffmpeg`/dav1d, one
808 /// entry per coded frame, in order — this facade's own equivalent of
809 /// `encode::tests::ffmpeg_decode_sequence`, needed here too since a
810 /// PSNR check needs the decoded pixels, not just the coded byte count.
811 fn ffmpeg_decode_luma(stream: &[u8], width: usize, height: usize) -> Vec<Vec<u8>> {
812 let path = std::env::temp_dir().join(format!(
813 "ec-av1-facade-rate-decode-{}-{}.obu",
814 std::process::id(),
815 std::ptr::addr_of!(stream) as usize
816 ));
817 std::fs::write(&path, stream).expect("writing the decode probe stream");
818 let out = Command::new("ffmpeg")
819 .args(["-v", "error", "-f", "obu", "-i"])
820 .arg(&path)
821 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-"])
822 .output()
823 .expect("ffmpeg failed to run");
824 let _ = std::fs::remove_file(&path);
825 assert!(
826 out.status.success(),
827 "{}",
828 String::from_utf8_lossy(&out.stderr)
829 );
830 let (luma, chroma) = (width * height, width * height / 4);
831 let frame_len = luma + 2 * chroma;
832 out.stdout
833 .chunks_exact(frame_len)
834 .map(|f| f[..luma].to_vec())
835 .collect()
836 }
837
838 /// [`RateTarget::Quality`] is monotone: a higher quality dial never
839 /// produces a smaller stream or a worse mean PSNR than a lower one, on
840 /// the same real clip.
841 #[test]
842 fn quality_target_is_monotone_in_bytes_and_psnr() {
843 if !have_ffmpeg() {
844 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no ffmpeg");
845 return;
846 }
847 let (width, height) = (640, 384);
848 let Some(pictures) = h264_clip_frames(width, height, 8) else {
849 eprintln!("SKIP quality_target_is_monotone_in_bytes_and_psnr: no fixture");
850 return;
851 };
852 let mut prev_bytes = 0usize;
853 let mut prev_psnr = 0.0f64;
854 for quality in [20u8, 50, 80] {
855 let config = EncoderConfig {
856 width,
857 height,
858 base_q_idx: 100,
859 gop: 8,
860 colour: Colour::Bt709Limited,
861 };
862 let mut enc =
863 Av1Encoder::with_rate_target(config, RateTarget::Quality(quality)).unwrap();
864 let mut stream = Vec::new();
865 let mut total_bytes = 0usize;
866 for picture in &pictures {
867 let packet = enc.encode(picture).unwrap();
868 total_bytes += packet.data.len();
869 stream.extend_from_slice(&packet.data);
870 }
871 let decoded = ffmpeg_decode_luma(&stream, width, height);
872 assert_eq!(
873 decoded.len(),
874 pictures.len(),
875 "quality {quality}: dav1d frame count"
876 );
877 let mean_psnr: f64 = decoded
878 .iter()
879 .zip(&pictures)
880 .map(|(d, p)| {
881 let d16: Vec<u16> = d.iter().map(|&v| u16::from(v)).collect();
882 psnr(&d16, &p.y)
883 })
884 .sum::<f64>()
885 / decoded.len() as f64;
886 assert!(
887 total_bytes >= prev_bytes,
888 "quality {quality}: {total_bytes} bytes not >= previous {prev_bytes}"
889 );
890 assert!(
891 mean_psnr >= prev_psnr - 0.01, // rounding slack, same-ish q_idx neighbours
892 "quality {quality}: {mean_psnr:.2} dB not >= previous {prev_psnr:.2} dB"
893 );
894 prev_bytes = total_bytes;
895 prev_psnr = mean_psnr;
896 }
897 }
898}