forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBf44b458Tahinli3 months ago649 commits

encoder.rs515 lines, 19.2 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/// 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)]
85pub 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)]
104pub 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)]
122pub 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
133impl 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)]
235mod 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 (width as u32, height as u32),
431 "picture {t}: ffprobe reports the true (display) size, not the padded coded one"
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}