forge
Explore
Log in

Don't you dare go Hollow

Streaming encoder facade with configurable colour (I11)

Browse files at this commit

f421d981a5f37b82290b1f5babea4b87dae07171Ahmet Kaan GümüşParent: 77b8ab9
  • feat
    • streaming encoder facade with configurable colour (I11)
Show full message
feat(av1): streaming encoder facade with configurable colour (I11)

Av1Encoder is the one-in-one-out surface edith_replica's engine will call
in place of rav1e: EncoderConfig{width,height,base_q_idx,gop,colour} in,
encode(&Picture) -> Packet{data,key,order} out, gop-cadenced key frames
predicting inter frames from the previous reconstruction like
encode_sequence already did. encode_key_frame_inner/encode_inter_frame
are now shared (pub(crate)) between encode_sequence and the facade
instead of being duplicated. The sequence header's colour_config is wired
to Colour::{Bt709Limited,Bt601Limited,Unspecified} (spec 5.5.2's CICP
triple + range), replacing the hardcoded "unspecified" -- verified against
ffprobe.
crates/ec-av1/src/encode.rsmodified+53 -22
@@ -45,7 +45,7 @@ const BLOCK: usize = 32;
4545 const SUB: usize = 16;
4646
4747 /// The side of a superblock, which is what the partition tree starts from.
48-const SUPERBLOCK: usize = 64;
48+pub(crate) const SUPERBLOCK: usize = 64;
4949
5050 /// How heavily the mode search weighs rate against squared error, in units of
5151 /// the quantizer's reconstruction step squared per bit.
@@ -77,7 +77,7 @@ const SPLIT_BLOCKS: bool = true;
7777
7878 /// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides
7979 /// by calling [`encode_key_frame_inner`] both ways.
80-fn split_blocks() -> bool {
80+pub(crate) fn split_blocks() -> bool {
8181 SPLIT_BLOCKS
8282 }
8383
@@ -109,7 +109,7 @@ impl Picture {
109109 }
110110 }
111111
112- fn check(&self) -> Result<()> {
112+ pub(crate) fn check(&self) -> Result<()> {
113113 if self.width == 0
114114 || !self.width.is_multiple_of(BLOCK)
115115 || !self.height.is_multiple_of(BLOCK)
@@ -134,7 +134,7 @@ impl Picture {
134134 /// before it is padded to the block grid: even, nonzero dimensions (4:2:0
135135 /// needs a whole chroma sample per two luma ones) and one sample per
136136 /// position on each plane.
137- fn check_even(&self) -> Result<()> {
137+ pub(crate) fn check_even(&self) -> Result<()> {
138138 if self.width == 0
139139 || self.height == 0
140140 || !self.width.is_multiple_of(2)
@@ -162,7 +162,7 @@ impl Picture {
162162 /// that). Identity (a plain clone, not a copy through the replication
163163 /// loop) when the picture is already that size — the multiple-of-32 (or
164164 /// -64) fast path is unchanged.
165- fn padded_to(&self, align: usize) -> Picture {
165+ pub(crate) fn padded_to(&self, align: usize) -> Picture {
166166 let padded_width = self.width.next_multiple_of(align);
167167 let padded_height = self.height.next_multiple_of(align);
168168 if padded_width == self.width && padded_height == self.height {
@@ -231,7 +231,7 @@ fn crop_plane(source: &[u8], padded_width: usize, width: usize, height: usize) -
231231 /// region a decoder produces, which is the public contract for what a caller
232232 /// sees back — the padded planes the encoder coded against never leave this
233233 /// module. Identity when the reconstruction is already that size.
234-fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
234+pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded {
235235 let reconstruction = &encoded.reconstruction;
236236 let cropped = if reconstruction.width == width && reconstruction.height == height {
237237 reconstruction.clone()
@@ -293,6 +293,43 @@ pub fn key_frame_headers(
293293 width: usize,
294294 height: usize,
295295 base_q_idx: u8,
296+) -> Result<(SequenceHeader, FrameHeader)> {
297+ key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config())
298+}
299+
300+/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and
301+/// studio (limited) range: what this crate's sequence header carried before
302+/// [`crate::encoder`]'s facade could configure it, and what
303+/// [`key_frame_headers`] still asks for.
304+fn unspecified_color_config() -> ColorConfig {
305+ ColorConfig {
306+ bit_depth: 8,
307+ mono_chrome: false,
308+ num_planes: 3,
309+ color_primaries: 2,
310+ transfer_characteristics: 2,
311+ matrix_coefficients: 2,
312+ color_range: false,
313+ subsampling_x: 1,
314+ subsampling_y: 1,
315+ chroma_sample_position: ChromaSamplePosition::Unknown,
316+ separate_uv_delta_q: false,
317+ }
318+}
319+
320+/// [`key_frame_headers`] with the sequence header's colour config named
321+/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`,
322+/// `transfer_characteristics`, `matrix_coefficients` and `color_range`,
323+/// which is all a player picks a colour transform from and which
324+/// [`crate::encoder::Colour`] is the facade's own name for.
325+///
326+/// # Errors
327+/// The same as [`key_frame_headers`].
328+pub(crate) fn key_frame_headers_colour(
329+ width: usize,
330+ height: usize,
331+ base_q_idx: u8,
332+ color_config: ColorConfig,
296333 ) -> Result<(SequenceHeader, FrameHeader)> {
297334 let bits = |n: usize| -> Result<u32> {
298335 let n = u32::try_from(n).map_err(|_| too_large())?;
@@ -323,19 +360,7 @@ pub fn key_frame_headers(
323360 enable_restoration: false,
324361 seq_force_screen_content_tools: 0,
325362 seq_force_integer_mv: 0,
326- color_config: ColorConfig {
327- bit_depth: 8,
328- mono_chrome: false,
329- num_planes: 3,
330- color_primaries: 2,
331- transfer_characteristics: 2,
332- matrix_coefficients: 2,
333- color_range: false,
334- subsampling_x: 1,
335- subsampling_y: 1,
336- chroma_sample_position: ChromaSamplePosition::Unknown,
337- separate_uv_delta_q: false,
338- },
363+ color_config,
339364 still_picture: false,
340365 reduced_still_picture_header: false,
341366 timing_info: None,
@@ -988,6 +1013,7 @@ pub fn encode_key_frame_with_modes(
9881013 modes,
9891014 split_blocks(),
9901015 (picture.width, picture.height),
1016+ unspecified_color_config(),
9911017 )?;
9921018 Ok(crop_encoded(&encoded, picture.width, picture.height))
9931019 }
@@ -996,13 +1022,14 @@ pub fn encode_key_frame_with_modes(
9961022 /// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is
9971023 /// already padded to a whole number of 32x32 blocks; `render` is the real
9981024 /// (pre-pad) size the frame header tells a decoder to crop back to.
999-fn encode_key_frame_inner(
1025+pub(crate) fn encode_key_frame_inner(
10001026 picture: &Picture,
10011027 base_q_idx: u8,
10021028 deadzone: f64,
10031029 modes: &[u8],
10041030 split_blocks: bool,
10051031 render: (usize, usize),
1032+ color_config: ColorConfig,
10061033 ) -> Result<Encoded> {
10071034 picture.check()?;
10081035 if modes.is_empty() {
@@ -1017,7 +1044,8 @@ fn encode_key_frame_inner(
10171044 format!("intra mode {bad} is not one the encoder predicts"),
10181045 ));
10191046 }
1020- let (seq, mut header) = key_frame_headers(picture.width, picture.height, base_q_idx)?;
1047+ let (seq, mut header) =
1048+ key_frame_headers_colour(picture.width, picture.height, base_q_idx, color_config)?;
10211049 header.render_width = render.0 as u32;
10221050 header.render_height = render.1 as u32;
10231051
@@ -1638,7 +1666,7 @@ fn search_inter_block(
16381666 /// Encodes one picture as an inter frame predicting from `reference`'s
16391667 /// reconstruction, which the caller decoded (or, for the frame right after
16401668 /// the key frame, is the key frame's own reconstruction).
1641-fn encode_inter_frame(
1669+pub(crate) fn encode_inter_frame(
16421670 picture: &Picture,
16431671 reference: &Picture,
16441672 base_q_idx: u8,
@@ -1827,6 +1855,7 @@ pub fn encode_sequence(
18271855 &KEY_FRAME_MODES,
18281856 split_blocks(),
18291857 render,
1858+ unspecified_color_config(),
18301859 )?;
18311860 let mut stream = key.stream.clone();
18321861 let mut reference = key.reconstruction.clone();
@@ -2343,6 +2372,7 @@ mod tests {
23432372 &KEY_FRAME_MODES,
23442373 split,
23452374 (picture.width, picture.height),
2375+ unspecified_color_config(),
23462376 )
23472377 .unwrap();
23482378 (
@@ -2362,6 +2392,7 @@ mod tests {
23622392 &KEY_FRAME_MODES,
23632393 true,
23642394 (picture.width, picture.height),
2395+ unspecified_color_config(),
23652396 )
23662397 .unwrap()
23672398 .modes
crates/ec-av1/src/encoder.rsadded+515 -0
@@ -0,0 +1,515 @@
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+
16+use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig};
17+use ec_core::{Error, Result};
18+
19+use crate::encode::{
20+ Encoded, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame, encode_key_frame_inner,
21+ split_blocks,
22+};
23+use 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.)
30+const 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)]
38+pub 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+
52+impl 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+/// What [`Av1Encoder::new`] takes: geometry, rate, key-frame cadence and
80+/// colour. `base_q_idx` is picked directly (0..=255, `crate::encode`'s own
81+/// unit) rather than a bitrate — a bitrate control loop is not part of this
82+/// lane's charter, and a caller that wants one can still derive a
83+/// `base_q_idx` from its own target and set that field.
84+#[derive(Debug, Clone, Copy)]
85+pub struct EncoderConfig {
86+ /// The picture's width in luma samples; must be even and nonzero.
87+ pub width: usize,
88+ /// The picture's height in luma samples; must be even and nonzero.
89+ pub height: usize,
90+ /// The quantizer index every frame is coded at (0..=255).
91+ pub base_q_idx: u8,
92+ /// Pictures between key frames, inclusive of the key frame itself: `1`
93+ /// codes every picture as a key frame, `gop` codes picture `gop` (and
94+ /// `2*gop`, ...) as a key frame and every other picture inter.
95+ pub gop: usize,
96+ /// The colour the sequence header signals.
97+ pub colour: Colour,
98+}
99+
100+/// One coded picture: its OBUs, in the order a demuxer that just wants bytes
101+/// on the wire can concatenate them, and the two things a muxer needs to
102+/// know without parsing them back out.
103+#[derive(Debug, Clone)]
104+pub struct Packet {
105+ /// A temporal delimiter, a sequence header and the frame OBU for a key
106+ /// frame; a temporal delimiter and the frame OBU alone for an inter
107+ /// frame (the sequence header is identical across a stream's key
108+ /// frames, since only [`EncoderConfig`]'s own fields feed it, so it is
109+ /// simplest to let every key frame carry its own copy rather than have
110+ /// the facade special-case the first one).
111+ pub data: Vec<u8>,
112+ /// Whether this picture was coded as a key frame.
113+ pub key: bool,
114+ /// This picture's position in the stream, in coding (== presentation,
115+ /// since this encoder has no B frames) order, starting at 0.
116+ pub order: u64,
117+}
118+
119+/// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per
120+/// [`Av1Encoder::encode`] call.
121+#[derive(Debug)]
122+pub struct Av1Encoder {
123+ config: EncoderConfig,
124+ color_config: ColorConfig,
125+ /// The previous picture's own (padded, uncropped) reconstruction — what
126+ /// the next inter frame predicts from — or `None` right after a key
127+ /// frame's turn comes up again, where it is about to be replaced rather
128+ /// than read.
129+ reference: Option<Picture>,
130+ next_index: u64,
131+}
132+
133+impl Av1Encoder {
134+ /// # Errors
135+ /// Returns an error when `config.width`/`config.height` are zero, odd,
136+ /// or larger than the 16-bit frame size an AV1 sequence header carries,
137+ /// or when `config.gop` is zero (there would be no picture to code the
138+ /// next key frame from a cadence of).
139+ pub fn new(config: EncoderConfig) -> Result<Self> {
140+ if config.gop == 0 {
141+ return Err(Error::unsupported("AV1 encode", "gop must be at least 1"));
142+ }
143+ // Validate the geometry the same way the picture-level entry points
144+ // do, before the first `encode()` call rather than only surfacing it
145+ // then.
146+ Picture::grey(config.width, config.height).check_even()?;
147+ Ok(Self {
148+ color_config: config.colour.color_config(),
149+ config,
150+ reference: None,
151+ next_index: 0,
152+ })
153+ }
154+
155+ /// The coded (padded-to-64) frame size every picture in this stream is
156+ /// coded at — what a decoder allocates and what `ffprobe` reports.
157+ #[must_use]
158+ pub fn coded_size(&self) -> (usize, usize) {
159+ (
160+ self.config.width.next_multiple_of(SUPERBLOCK),
161+ self.config.height.next_multiple_of(SUPERBLOCK),
162+ )
163+ }
164+
165+ /// The display (render) size every frame header signals — [`EncoderConfig`]'s
166+ /// own `width`/`height`, always, whatever the coded size pads it to.
167+ #[must_use]
168+ pub fn display_size(&self) -> (usize, usize) {
169+ (self.config.width, self.config.height)
170+ }
171+
172+ /// Encodes one picture, key or inter by this stream's `gop` cadence, and
173+ /// returns its packet — always exactly one, never held back for a later
174+ /// call.
175+ ///
176+ /// # Errors
177+ /// Returns an error when `picture`'s size does not match
178+ /// [`EncoderConfig::width`]/[`EncoderConfig::height`], or under the same
179+ /// conditions [`crate::encode::encode_key_frame`]/
180+ /// [`crate::encode::encode_sequence`] do.
181+ pub fn encode(&mut self, picture: &Picture) -> Result<Packet> {
182+ if (picture.width, picture.height) != (self.config.width, self.config.height) {
183+ return Err(Error::unsupported(
184+ "AV1 encode",
185+ format!(
186+ "picture is {}x{}, encoder is {}x{}",
187+ picture.width, picture.height, self.config.width, self.config.height
188+ ),
189+ ));
190+ }
191+ let render = (self.config.width, self.config.height);
192+ let padded = picture.padded_to(SUPERBLOCK);
193+ let is_key = self.next_index % self.config.gop as u64 == 0;
194+ let order = self.next_index;
195+
196+ let encoded: Encoded = if is_key {
197+ encode_key_frame_inner(
198+ &padded,
199+ self.config.base_q_idx,
200+ DEADZONE,
201+ &KEY_FRAME_MODES,
202+ split_blocks(),
203+ render,
204+ self.color_config,
205+ )?
206+ } else {
207+ let reference = self.reference.as_ref().ok_or_else(|| {
208+ Error::unsupported(
209+ "AV1 encode",
210+ "an inter frame needs a previous reconstruction",
211+ )
212+ })?;
213+ encode_inter_frame(
214+ &padded,
215+ reference,
216+ self.config.base_q_idx,
217+ DEADZONE,
218+ order as u32,
219+ render,
220+ )?
221+ };
222+
223+ self.reference = Some(encoded.reconstruction.clone());
224+ self.next_index += 1;
225+ let cropped = crop_encoded(&encoded, render.0, render.1);
226+ Ok(Packet {
227+ data: cropped.stream,
228+ key: is_key,
229+ order,
230+ })
231+ }
232+}
233+
234+#[cfg(test)]
235+mod tests {
236+ use super::*;
237+ use std::process::{Command, Stdio};
238+
239+ fn have_ffmpeg() -> bool {
240+ Command::new("ffmpeg")
241+ .arg("-version")
242+ .stdout(Stdio::null())
243+ .stderr(Stdio::null())
244+ .status()
245+ .is_ok_and(|s| s.success())
246+ }
247+
248+ fn test_card(width: usize, height: usize, shift: usize) -> Picture {
249+ let mut picture = Picture::grey(width, height);
250+ for y in 0..height {
251+ for x in 0..width {
252+ let sx = (x + shift) % width;
253+ picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u8;
254+ }
255+ }
256+ for y in 0..height / 2 {
257+ for x in 0..width / 2 {
258+ let i = y * (width / 2) + x;
259+ picture.u[i] = ((100 + shift * 4) % 256) as u8;
260+ picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u8;
261+ }
262+ }
263+ picture
264+ }
265+
266+ /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated
267+ /// in order.
268+ fn concat(packets: &[Packet]) -> Vec<u8> {
269+ packets.iter().flat_map(|p| p.data.clone()).collect()
270+ }
271+
272+ /// One call to [`Av1Encoder::encode`] returns exactly one packet, always
273+ /// — the facade's whole "nothing held back" contract, checked without
274+ /// ffmpeg since it is a property of the return type, not the bytes.
275+ #[test]
276+ fn one_in_one_out() {
277+ let config = EncoderConfig {
278+ width: 64,
279+ height: 64,
280+ base_q_idx: 100,
281+ gop: 2,
282+ colour: Colour::Bt709Limited,
283+ };
284+ let mut enc = Av1Encoder::new(config).unwrap();
285+ for t in 0..5u64 {
286+ let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap();
287+ assert!(!packet.data.is_empty(), "picture {t}: empty packet");
288+ assert_eq!(packet.order, t, "picture {t}: order");
289+ }
290+ }
291+
292+ /// A key frame every `gop` pictures, inter otherwise — checked against
293+ /// what the facade itself reports, and (below) against what `ffprobe`
294+ /// reads back out of the coded bytes.
295+ #[test]
296+ fn gop_cadence_is_honored() {
297+ let config = EncoderConfig {
298+ width: 64,
299+ height: 64,
300+ base_q_idx: 100,
301+ gop: 3,
302+ colour: Colour::Unspecified,
303+ };
304+ let mut enc = Av1Encoder::new(config).unwrap();
305+ let keys: Vec<bool> = (0..7)
306+ .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key)
307+ .collect();
308+ assert_eq!(keys, vec![true, false, false, true, false, false, true]);
309+ }
310+
311+ fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> {
312+ let path = std::env::temp_dir().join(format!(
313+ "ec-av1-facade-probe-{}-{}.obu",
314+ std::process::id(),
315+ std::ptr::addr_of!(stream) as usize
316+ ));
317+ std::fs::write(&path, stream).expect("writing the probe stream");
318+ let out = Command::new("ffprobe")
319+ .args([
320+ "-v",
321+ "error",
322+ "-f",
323+ "obu",
324+ "-select_streams",
325+ "v:0",
326+ "-show_entries",
327+ "frame=key_frame,width,height",
328+ "-of",
329+ "csv=p=0",
330+ ])
331+ .arg(&path)
332+ .output()
333+ .expect("ffprobe failed to run");
334+ let _ = std::fs::remove_file(&path);
335+ assert!(
336+ out.status.success(),
337+ "ffprobe refused the stream: {}",
338+ String::from_utf8_lossy(&out.stderr)
339+ );
340+ String::from_utf8_lossy(&out.stdout)
341+ .lines()
342+ .map(|line| {
343+ let mut f = line.trim().split(',');
344+ let key: u32 = f.next().unwrap().parse().unwrap();
345+ let width: u32 = f.next().unwrap().parse().unwrap();
346+ let height: u32 = f.next().unwrap().parse().unwrap();
347+ (key == 1, width, height)
348+ })
349+ .collect()
350+ }
351+
352+ fn ffprobe_colour(stream: &[u8]) -> String {
353+ let path = std::env::temp_dir().join(format!(
354+ "ec-av1-facade-colour-probe-{}-{}.obu",
355+ std::process::id(),
356+ std::ptr::addr_of!(stream) as usize
357+ ));
358+ std::fs::write(&path, stream).expect("writing the probe stream");
359+ let out = Command::new("ffprobe")
360+ .args([
361+ "-v",
362+ "error",
363+ "-f",
364+ "obu",
365+ "-select_streams",
366+ "v:0",
367+ "-show_entries",
368+ "stream=color_primaries,color_transfer,color_space,color_range",
369+ "-of",
370+ "csv=p=0",
371+ ])
372+ .arg(&path)
373+ .output()
374+ .expect("ffprobe failed to run");
375+ let _ = std::fs::remove_file(&path);
376+ assert!(
377+ out.status.success(),
378+ "ffprobe refused the stream: {}",
379+ String::from_utf8_lossy(&out.stderr)
380+ );
381+ String::from_utf8_lossy(&out.stdout).trim().to_string()
382+ }
383+
384+ /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15)
385+ /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that
386+ /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and
387+ /// coded size confirm what the facade already reported.
388+ #[test]
389+ fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() {
390+ if !have_ffmpeg() {
391+ eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg");
392+ return;
393+ }
394+ let (width, height) = (96usize, 96usize);
395+ let config = EncoderConfig {
396+ width,
397+ height,
398+ base_q_idx: 120,
399+ gop: 15,
400+ colour: Colour::Bt709Limited,
401+ };
402+ let mut enc = Av1Encoder::new(config).unwrap();
403+ assert_eq!(enc.display_size(), (width, height));
404+ let (coded_w, coded_h) = enc.coded_size();
405+ assert_eq!(
406+ (coded_w, coded_h),
407+ (
408+ width.next_multiple_of(SUPERBLOCK),
409+ height.next_multiple_of(SUPERBLOCK)
410+ )
411+ );
412+
413+ let packets: Vec<Packet> = (0..30)
414+ .map(|t| enc.encode(&test_card(width, height, t)).unwrap())
415+ .collect();
416+ let expect_key: Vec<bool> = (0..30).map(|t| t % 15 == 0).collect();
417+ assert_eq!(
418+ packets.iter().map(|p| p.key).collect::<Vec<_>>(),
419+ expect_key,
420+ "facade's own key/inter flags"
421+ );
422+
423+ let stream = concat(&packets);
424+ let frames = ffprobe_frames(&stream);
425+ assert_eq!(frames.len(), 30, "ffprobe frame count");
426+ for (t, (key, w, h)) in frames.iter().enumerate() {
427+ assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag");
428+ assert_eq!(
429+ (*w, *h),
430+ (coded_w as u32, coded_h as u32),
431+ "picture {t}: coded size"
432+ );
433+ }
434+ }
435+
436+ /// The configured colour properties are what `ffprobe` reports back,
437+ /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it
438+ /// is the default a player assumes and the one this test would silently
439+ /// pass without wiring for (`ffprobe` reports "unknown" for the
440+ /// hardcoded "unspecified" this crate wrote before the facade existed,
441+ /// which is a visibly different string).
442+ #[test]
443+ fn bt709_limited_colour_is_reported_by_ffprobe() {
444+ if !have_ffmpeg() {
445+ eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg");
446+ return;
447+ }
448+ let config = EncoderConfig {
449+ width: 64,
450+ height: 64,
451+ base_q_idx: 100,
452+ gop: 4,
453+ colour: Colour::Bt709Limited,
454+ };
455+ let mut enc = Av1Encoder::new(config).unwrap();
456+ let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
457+ let colour = ffprobe_colour(&packet.data);
458+ assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields");
459+ }
460+
461+ /// The same, for BT.601: a different set of CICP integers must produce a
462+ /// different string, or the wiring could be a no-op that happens to read
463+ /// as BT.709 for every input.
464+ #[test]
465+ fn bt601_limited_colour_is_reported_by_ffprobe() {
466+ if !have_ffmpeg() {
467+ eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg");
468+ return;
469+ }
470+ let config = EncoderConfig {
471+ width: 64,
472+ height: 64,
473+ base_q_idx: 100,
474+ gop: 4,
475+ colour: Colour::Bt601Limited,
476+ };
477+ let mut enc = Av1Encoder::new(config).unwrap();
478+ let packet = enc.encode(&test_card(64, 64, 0)).unwrap();
479+ let colour = ffprobe_colour(&packet.data);
480+ assert_eq!(
481+ colour, "tv,smpte170m,smpte170m,smpte170m",
482+ "ffprobe colour fields"
483+ );
484+ }
485+
486+ /// A frame whose size does not match the encoder's configured geometry
487+ /// is refused by name.
488+ #[test]
489+ fn geometry_mismatch_is_refused() {
490+ let config = EncoderConfig {
491+ width: 64,
492+ height: 64,
493+ base_q_idx: 100,
494+ gop: 4,
495+ colour: Colour::Bt709Limited,
496+ };
497+ let mut enc = Av1Encoder::new(config).unwrap();
498+ let err = enc.encode(&Picture::grey(32, 32)).unwrap_err();
499+ assert!(err.to_string().contains("64x64"), "{err}");
500+ }
501+
502+ /// `gop == 0` is refused at construction, not the first `encode()` call.
503+ #[test]
504+ fn zero_gop_is_refused() {
505+ let config = EncoderConfig {
506+ width: 64,
507+ height: 64,
508+ base_q_idx: 100,
509+ gop: 0,
510+ colour: Colour::Bt709Limited,
511+ };
512+ let err = Av1Encoder::new(config).unwrap_err();
513+ assert!(err.to_string().contains("gop"), "{err}");
514+ }
515+}
crates/ec-av1/src/lib.rsmodified+1 -0
@@ -16,6 +16,7 @@ pub mod bits;
1616 pub mod cdf;
1717 mod cdf_state;
1818 pub mod encode;
19+pub mod encoder;
1920 pub mod frame;
2021 pub mod intra;
2122 pub mod mc;