From f421d981a5f37b82290b1f5babea4b87dae07171 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 26 Aug 2026 23:14:11 +0300 Subject: [PATCH] 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.rs | 75 +++-- crates/ec-av1/src/encoder.rs | 515 +++++++++++++++++++++++++++++++++++ crates/ec-av1/src/lib.rs | 1 + 3 files changed, 569 insertions(+), 22 deletions(-) create mode 100644 crates/ec-av1/src/encoder.rs diff --git a/crates/ec-av1/src/encode.rs b/crates/ec-av1/src/encode.rs index 1f79237a..f6c8999f 100644 --- a/crates/ec-av1/src/encode.rs +++ b/crates/ec-av1/src/encode.rs @@ -45,7 +45,7 @@ const BLOCK: usize = 32; const SUB: usize = 16; /// The side of a superblock, which is what the partition tree starts from. -const SUPERBLOCK: usize = 64; +pub(crate) const SUPERBLOCK: usize = 64; /// How heavily the mode search weighs rate against squared error, in units of /// the quantizer's reconstruction step squared per bit. @@ -77,7 +77,7 @@ const SPLIT_BLOCKS: bool = true; /// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides /// by calling [`encode_key_frame_inner`] both ways. -fn split_blocks() -> bool { +pub(crate) fn split_blocks() -> bool { SPLIT_BLOCKS } @@ -109,7 +109,7 @@ impl Picture { } } - fn check(&self) -> Result<()> { + pub(crate) fn check(&self) -> Result<()> { if self.width == 0 || !self.width.is_multiple_of(BLOCK) || !self.height.is_multiple_of(BLOCK) @@ -134,7 +134,7 @@ impl Picture { /// before it is padded to the block grid: even, nonzero dimensions (4:2:0 /// needs a whole chroma sample per two luma ones) and one sample per /// position on each plane. - fn check_even(&self) -> Result<()> { + pub(crate) fn check_even(&self) -> Result<()> { if self.width == 0 || self.height == 0 || !self.width.is_multiple_of(2) @@ -162,7 +162,7 @@ impl Picture { /// that). Identity (a plain clone, not a copy through the replication /// loop) when the picture is already that size — the multiple-of-32 (or /// -64) fast path is unchanged. - fn padded_to(&self, align: usize) -> Picture { + pub(crate) fn padded_to(&self, align: usize) -> Picture { let padded_width = self.width.next_multiple_of(align); let padded_height = self.height.next_multiple_of(align); 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) - /// region a decoder produces, which is the public contract for what a caller /// sees back — the padded planes the encoder coded against never leave this /// module. Identity when the reconstruction is already that size. -fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded { +pub(crate) fn crop_encoded(encoded: &Encoded, width: usize, height: usize) -> Encoded { let reconstruction = &encoded.reconstruction; let cropped = if reconstruction.width == width && reconstruction.height == height { reconstruction.clone() @@ -293,6 +293,43 @@ pub fn key_frame_headers( width: usize, height: usize, base_q_idx: u8, +) -> Result<(SequenceHeader, FrameHeader)> { + key_frame_headers_colour(width, height, base_q_idx, unspecified_color_config()) +} + +/// [`ColorConfig`] with every CICP field "unspecified" (H.273 value 2) and +/// studio (limited) range: what this crate's sequence header carried before +/// [`crate::encoder`]'s facade could configure it, and what +/// [`key_frame_headers`] still asks for. +fn unspecified_color_config() -> ColorConfig { + ColorConfig { + bit_depth: 8, + mono_chrome: false, + num_planes: 3, + color_primaries: 2, + transfer_characteristics: 2, + matrix_coefficients: 2, + color_range: false, + subsampling_x: 1, + subsampling_y: 1, + chroma_sample_position: ChromaSamplePosition::Unknown, + separate_uv_delta_q: false, + } +} + +/// [`key_frame_headers`] with the sequence header's colour config named +/// instead of hardcoded to "unspecified" -- spec 5.5.2's `color_primaries`, +/// `transfer_characteristics`, `matrix_coefficients` and `color_range`, +/// which is all a player picks a colour transform from and which +/// [`crate::encoder::Colour`] is the facade's own name for. +/// +/// # Errors +/// The same as [`key_frame_headers`]. +pub(crate) fn key_frame_headers_colour( + width: usize, + height: usize, + base_q_idx: u8, + color_config: ColorConfig, ) -> Result<(SequenceHeader, FrameHeader)> { let bits = |n: usize| -> Result { let n = u32::try_from(n).map_err(|_| too_large())?; @@ -323,19 +360,7 @@ pub fn key_frame_headers( enable_restoration: false, seq_force_screen_content_tools: 0, seq_force_integer_mv: 0, - color_config: ColorConfig { - bit_depth: 8, - mono_chrome: false, - num_planes: 3, - color_primaries: 2, - transfer_characteristics: 2, - matrix_coefficients: 2, - color_range: false, - subsampling_x: 1, - subsampling_y: 1, - chroma_sample_position: ChromaSamplePosition::Unknown, - separate_uv_delta_q: false, - }, + color_config, still_picture: false, reduced_still_picture_header: false, timing_info: None, @@ -988,6 +1013,7 @@ pub fn encode_key_frame_with_modes( modes, split_blocks(), (picture.width, picture.height), + unspecified_color_config(), )?; Ok(crop_encoded(&encoded, picture.width, picture.height)) } @@ -996,13 +1022,14 @@ pub fn encode_key_frame_with_modes( /// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is /// already padded to a whole number of 32x32 blocks; `render` is the real /// (pre-pad) size the frame header tells a decoder to crop back to. -fn encode_key_frame_inner( +pub(crate) fn encode_key_frame_inner( picture: &Picture, base_q_idx: u8, deadzone: f64, modes: &[u8], split_blocks: bool, render: (usize, usize), + color_config: ColorConfig, ) -> Result { picture.check()?; if modes.is_empty() { @@ -1017,7 +1044,8 @@ fn encode_key_frame_inner( format!("intra mode {bad} is not one the encoder predicts"), )); } - let (seq, mut header) = key_frame_headers(picture.width, picture.height, base_q_idx)?; + let (seq, mut header) = + key_frame_headers_colour(picture.width, picture.height, base_q_idx, color_config)?; header.render_width = render.0 as u32; header.render_height = render.1 as u32; @@ -1638,7 +1666,7 @@ fn search_inter_block( /// Encodes one picture as an inter frame predicting from `reference`'s /// reconstruction, which the caller decoded (or, for the frame right after /// the key frame, is the key frame's own reconstruction). -fn encode_inter_frame( +pub(crate) fn encode_inter_frame( picture: &Picture, reference: &Picture, base_q_idx: u8, @@ -1827,6 +1855,7 @@ pub fn encode_sequence( &KEY_FRAME_MODES, split_blocks(), render, + unspecified_color_config(), )?; let mut stream = key.stream.clone(); let mut reference = key.reconstruction.clone(); @@ -2343,6 +2372,7 @@ mod tests { &KEY_FRAME_MODES, split, (picture.width, picture.height), + unspecified_color_config(), ) .unwrap(); ( @@ -2362,6 +2392,7 @@ mod tests { &KEY_FRAME_MODES, true, (picture.width, picture.height), + unspecified_color_config(), ) .unwrap() .modes diff --git a/crates/ec-av1/src/encoder.rs b/crates/ec-av1/src/encoder.rs new file mode 100644 index 00000000..49d48096 --- /dev/null +++ b/crates/ec-av1/src/encoder.rs @@ -0,0 +1,515 @@ +//! The streaming encoder facade — I11 of `lanes/av1-inter-plan.md`, the +//! surface `edith_replica`'s engine calls in place of rav1e. +//! +//! One picture in, one [`Packet`] out, same contract as the repo's other +//! software encoder shims (`shims/rusty_h264`'s `Encoder::try_encode`, +//! "nothing is ever held back"): [`Av1Encoder::encode`] never buffers a +//! picture past its own call, so there is no flush to drain. Internally it +//! is [`crate::encode::encode_key_frame_inner`] and +//! [`crate::encode::encode_inter_frame`] driven by a small state machine — +//! a key frame every `gop` pictures, an inter frame predicting from the +//! previous picture's own reconstruction otherwise — which is the same core +//! [`crate::encode::encode_sequence`] uses for its one-key-frame-then-all-inter +//! case; both now share it rather than each padding/cropping/refreshing the +//! reference on their own. + +use ec_av1_syntax::sequence::{ChromaSamplePosition, ColorConfig}; +use ec_core::{Error, Result}; + +use crate::encode::{ + Encoded, Picture, SUPERBLOCK, crop_encoded, encode_inter_frame, encode_key_frame_inner, + split_blocks, +}; +use crate::intra::KEY_FRAME_MODES; + +/// A quantizer step round to nearest: half a step either way costs the same +/// rate, so this is the deadzone every facade-driven frame is coded with. +/// (`crate::encode`'s public entry points take a caller-chosen deadzone +/// instead; the facade has no field for it because nothing downstream of it +/// picks one.) +const DEADZONE: f64 = 0.5; + +/// The colour a played-back frame is transformed by, named at what a +/// container/player picks a colour space from (spec 5.5.2's CICP triple plus +/// range) rather than at the raw integers. `edith_replica`'s rav1e seat sets +/// limited-range BT.709 or BT.601 (`export.rs:3494-3507`); this crate's +/// pre-facade sequence header always wrote [`Colour::Unspecified`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Colour { + /// `color_primaries`/`transfer_characteristics`/`matrix_coefficients` = + /// 1 (BT.709, H.273), studio range: consumer HD video's own space, and + /// the default a player assumes when nothing is signalled at all. + #[default] + Bt709Limited, + /// The same three fields = 6 (BT.601, H.273), studio range: SD video's + /// space. + Bt601Limited, + /// Every field = 2 ("unspecified", H.273): what this crate wrote before + /// any of this was configurable. + Unspecified, +} + +impl Colour { + fn color_config(self) -> ColorConfig { + let (color_primaries, transfer_characteristics, matrix_coefficients) = match self { + Colour::Bt709Limited => (1, 1, 1), + Colour::Bt601Limited => (6, 6, 6), + Colour::Unspecified => (2, 2, 2), + }; + ColorConfig { + bit_depth: 8, + mono_chrome: false, + num_planes: 3, + color_primaries, + transfer_characteristics, + matrix_coefficients, + // Every variant here is studio (limited) swing; a full-range + // variant would need its own name, not a fourth field on this + // enum, since a played-back frame's range is a property of the + // pictures fed in, not just a label. + color_range: false, + subsampling_x: 1, + subsampling_y: 1, + chroma_sample_position: ChromaSamplePosition::Unknown, + separate_uv_delta_q: false, + } + } +} + +/// What [`Av1Encoder::new`] takes: geometry, rate, key-frame cadence and +/// colour. `base_q_idx` is picked directly (0..=255, `crate::encode`'s own +/// unit) rather than a bitrate — a bitrate control loop is not part of this +/// lane's charter, and a caller that wants one can still derive a +/// `base_q_idx` from its own target and set that field. +#[derive(Debug, Clone, Copy)] +pub struct EncoderConfig { + /// The picture's width in luma samples; must be even and nonzero. + pub width: usize, + /// The picture's height in luma samples; must be even and nonzero. + pub height: usize, + /// The quantizer index every frame is coded at (0..=255). + pub base_q_idx: u8, + /// Pictures between key frames, inclusive of the key frame itself: `1` + /// codes every picture as a key frame, `gop` codes picture `gop` (and + /// `2*gop`, ...) as a key frame and every other picture inter. + pub gop: usize, + /// The colour the sequence header signals. + pub colour: Colour, +} + +/// One coded picture: its OBUs, in the order a demuxer that just wants bytes +/// on the wire can concatenate them, and the two things a muxer needs to +/// know without parsing them back out. +#[derive(Debug, Clone)] +pub struct Packet { + /// A temporal delimiter, a sequence header and the frame OBU for a key + /// frame; a temporal delimiter and the frame OBU alone for an inter + /// frame (the sequence header is identical across a stream's key + /// frames, since only [`EncoderConfig`]'s own fields feed it, so it is + /// simplest to let every key frame carry its own copy rather than have + /// the facade special-case the first one). + pub data: Vec, + /// Whether this picture was coded as a key frame. + pub key: bool, + /// This picture's position in the stream, in coding (== presentation, + /// since this encoder has no B frames) order, starting at 0. + pub order: u64, +} + +/// The AV1 software encoder: [`EncoderConfig`] in, one [`Packet`] out per +/// [`Av1Encoder::encode`] call. +#[derive(Debug)] +pub struct Av1Encoder { + config: EncoderConfig, + color_config: ColorConfig, + /// The previous picture's own (padded, uncropped) reconstruction — what + /// the next inter frame predicts from — or `None` right after a key + /// frame's turn comes up again, where it is about to be replaced rather + /// than read. + reference: Option, + next_index: u64, +} + +impl Av1Encoder { + /// # Errors + /// Returns an error when `config.width`/`config.height` are zero, odd, + /// or larger than the 16-bit frame size an AV1 sequence header carries, + /// or when `config.gop` is zero (there would be no picture to code the + /// next key frame from a cadence of). + pub fn new(config: EncoderConfig) -> Result { + if config.gop == 0 { + return Err(Error::unsupported("AV1 encode", "gop must be at least 1")); + } + // Validate the geometry the same way the picture-level entry points + // do, before the first `encode()` call rather than only surfacing it + // then. + Picture::grey(config.width, config.height).check_even()?; + Ok(Self { + color_config: config.colour.color_config(), + config, + reference: None, + next_index: 0, + }) + } + + /// The coded (padded-to-64) frame size every picture in this stream is + /// coded at — what a decoder allocates and what `ffprobe` reports. + #[must_use] + pub fn coded_size(&self) -> (usize, usize) { + ( + self.config.width.next_multiple_of(SUPERBLOCK), + self.config.height.next_multiple_of(SUPERBLOCK), + ) + } + + /// The display (render) size every frame header signals — [`EncoderConfig`]'s + /// own `width`/`height`, always, whatever the coded size pads it to. + #[must_use] + pub fn display_size(&self) -> (usize, usize) { + (self.config.width, self.config.height) + } + + /// Encodes one picture, key or inter by this stream's `gop` cadence, and + /// returns its packet — always exactly one, never held back for a later + /// call. + /// + /// # Errors + /// Returns an error when `picture`'s size does not match + /// [`EncoderConfig::width`]/[`EncoderConfig::height`], or under the same + /// conditions [`crate::encode::encode_key_frame`]/ + /// [`crate::encode::encode_sequence`] do. + pub fn encode(&mut self, picture: &Picture) -> Result { + if (picture.width, picture.height) != (self.config.width, self.config.height) { + return Err(Error::unsupported( + "AV1 encode", + format!( + "picture is {}x{}, encoder is {}x{}", + picture.width, picture.height, self.config.width, self.config.height + ), + )); + } + let render = (self.config.width, self.config.height); + let padded = picture.padded_to(SUPERBLOCK); + let is_key = self.next_index % self.config.gop as u64 == 0; + let order = self.next_index; + + let encoded: Encoded = if is_key { + encode_key_frame_inner( + &padded, + self.config.base_q_idx, + DEADZONE, + &KEY_FRAME_MODES, + split_blocks(), + render, + self.color_config, + )? + } else { + let reference = self.reference.as_ref().ok_or_else(|| { + Error::unsupported( + "AV1 encode", + "an inter frame needs a previous reconstruction", + ) + })?; + encode_inter_frame( + &padded, + reference, + self.config.base_q_idx, + DEADZONE, + order as u32, + render, + )? + }; + + self.reference = Some(encoded.reconstruction.clone()); + self.next_index += 1; + let cropped = crop_encoded(&encoded, render.0, render.1); + Ok(Packet { + data: cropped.stream, + key: is_key, + order, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::process::{Command, Stdio}; + + fn have_ffmpeg() -> bool { + Command::new("ffmpeg") + .arg("-version") + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status() + .is_ok_and(|s| s.success()) + } + + fn test_card(width: usize, height: usize, shift: usize) -> Picture { + let mut picture = Picture::grey(width, height); + for y in 0..height { + for x in 0..width { + let sx = (x + shift) % width; + picture.y[y * width + x] = ((sx * 3 + y * 5) % 256) as u8; + } + } + for y in 0..height / 2 { + for x in 0..width / 2 { + let i = y * (width / 2) + x; + picture.u[i] = ((100 + shift * 4) % 256) as u8; + picture.v[i] = ((200 + 256 - shift * 2 % 256) % 256) as u8; + } + } + picture + } + + /// Every OBU stream this test writes to `ffmpeg`/`ffprobe`, concatenated + /// in order. + fn concat(packets: &[Packet]) -> Vec { + packets.iter().flat_map(|p| p.data.clone()).collect() + } + + /// One call to [`Av1Encoder::encode`] returns exactly one packet, always + /// — the facade's whole "nothing held back" contract, checked without + /// ffmpeg since it is a property of the return type, not the bytes. + #[test] + fn one_in_one_out() { + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 2, + colour: Colour::Bt709Limited, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + for t in 0..5u64 { + let packet = enc.encode(&test_card(64, 64, t as usize)).unwrap(); + assert!(!packet.data.is_empty(), "picture {t}: empty packet"); + assert_eq!(packet.order, t, "picture {t}: order"); + } + } + + /// A key frame every `gop` pictures, inter otherwise — checked against + /// what the facade itself reports, and (below) against what `ffprobe` + /// reads back out of the coded bytes. + #[test] + fn gop_cadence_is_honored() { + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 3, + colour: Colour::Unspecified, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let keys: Vec = (0..7) + .map(|t| enc.encode(&test_card(64, 64, t)).unwrap().key) + .collect(); + assert_eq!(keys, vec![true, false, false, true, false, false, true]); + } + + fn ffprobe_frames(stream: &[u8]) -> Vec<(bool, u32, u32)> { + let path = std::env::temp_dir().join(format!( + "ec-av1-facade-probe-{}-{}.obu", + std::process::id(), + std::ptr::addr_of!(stream) as usize + )); + std::fs::write(&path, stream).expect("writing the probe stream"); + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-f", + "obu", + "-select_streams", + "v:0", + "-show_entries", + "frame=key_frame,width,height", + "-of", + "csv=p=0", + ]) + .arg(&path) + .output() + .expect("ffprobe failed to run"); + let _ = std::fs::remove_file(&path); + assert!( + out.status.success(), + "ffprobe refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout) + .lines() + .map(|line| { + let mut f = line.trim().split(','); + let key: u32 = f.next().unwrap().parse().unwrap(); + let width: u32 = f.next().unwrap().parse().unwrap(); + let height: u32 = f.next().unwrap().parse().unwrap(); + (key == 1, width, height) + }) + .collect() + } + + fn ffprobe_colour(stream: &[u8]) -> String { + let path = std::env::temp_dir().join(format!( + "ec-av1-facade-colour-probe-{}-{}.obu", + std::process::id(), + std::ptr::addr_of!(stream) as usize + )); + std::fs::write(&path, stream).expect("writing the probe stream"); + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-f", + "obu", + "-select_streams", + "v:0", + "-show_entries", + "stream=color_primaries,color_transfer,color_space,color_range", + "-of", + "csv=p=0", + ]) + .arg(&path) + .output() + .expect("ffprobe failed to run"); + let _ = std::fs::remove_file(&path); + assert!( + out.status.success(), + "ffprobe refused the stream: {}", + String::from_utf8_lossy(&out.stderr) + ); + String::from_utf8_lossy(&out.stdout).trim().to_string() + } + + /// A 30-picture stream at gop 15 codes 2 key frames (pictures 0 and 15) + /// and 28 inter ones, at an odd-ish (not superblock-multiple) size that + /// exercises the pad/crop path -- `ffprobe`'s own `key_frame` flags and + /// coded size confirm what the facade already reported. + #[test] + fn thirty_pictures_at_gop_fifteen_decode_to_two_key_frames() { + if !have_ffmpeg() { + eprintln!("SKIP thirty_pictures_at_gop_fifteen_decode_to_two_key_frames: no ffmpeg"); + return; + } + let (width, height) = (96usize, 96usize); + let config = EncoderConfig { + width, + height, + base_q_idx: 120, + gop: 15, + colour: Colour::Bt709Limited, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + assert_eq!(enc.display_size(), (width, height)); + let (coded_w, coded_h) = enc.coded_size(); + assert_eq!( + (coded_w, coded_h), + ( + width.next_multiple_of(SUPERBLOCK), + height.next_multiple_of(SUPERBLOCK) + ) + ); + + let packets: Vec = (0..30) + .map(|t| enc.encode(&test_card(width, height, t)).unwrap()) + .collect(); + let expect_key: Vec = (0..30).map(|t| t % 15 == 0).collect(); + assert_eq!( + packets.iter().map(|p| p.key).collect::>(), + expect_key, + "facade's own key/inter flags" + ); + + let stream = concat(&packets); + let frames = ffprobe_frames(&stream); + assert_eq!(frames.len(), 30, "ffprobe frame count"); + for (t, (key, w, h)) in frames.iter().enumerate() { + assert_eq!(*key, expect_key[t], "picture {t}: ffprobe key_frame flag"); + assert_eq!( + (*w, *h), + (coded_w as u32, coded_h as u32), + "picture {t}: coded size" + ); + } + } + + /// The configured colour properties are what `ffprobe` reports back, + /// spec 5.5.2's CICP triple plus range -- BT.709 limited here, since it + /// is the default a player assumes and the one this test would silently + /// pass without wiring for (`ffprobe` reports "unknown" for the + /// hardcoded "unspecified" this crate wrote before the facade existed, + /// which is a visibly different string). + #[test] + fn bt709_limited_colour_is_reported_by_ffprobe() { + if !have_ffmpeg() { + eprintln!("SKIP bt709_limited_colour_is_reported_by_ffprobe: no ffmpeg"); + return; + } + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 4, + colour: Colour::Bt709Limited, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); + let colour = ffprobe_colour(&packet.data); + assert_eq!(colour, "tv,bt709,bt709,bt709", "ffprobe colour fields"); + } + + /// The same, for BT.601: a different set of CICP integers must produce a + /// different string, or the wiring could be a no-op that happens to read + /// as BT.709 for every input. + #[test] + fn bt601_limited_colour_is_reported_by_ffprobe() { + if !have_ffmpeg() { + eprintln!("SKIP bt601_limited_colour_is_reported_by_ffprobe: no ffmpeg"); + return; + } + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 4, + colour: Colour::Bt601Limited, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let packet = enc.encode(&test_card(64, 64, 0)).unwrap(); + let colour = ffprobe_colour(&packet.data); + assert_eq!( + colour, "tv,smpte170m,smpte170m,smpte170m", + "ffprobe colour fields" + ); + } + + /// A frame whose size does not match the encoder's configured geometry + /// is refused by name. + #[test] + fn geometry_mismatch_is_refused() { + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 4, + colour: Colour::Bt709Limited, + }; + let mut enc = Av1Encoder::new(config).unwrap(); + let err = enc.encode(&Picture::grey(32, 32)).unwrap_err(); + assert!(err.to_string().contains("64x64"), "{err}"); + } + + /// `gop == 0` is refused at construction, not the first `encode()` call. + #[test] + fn zero_gop_is_refused() { + let config = EncoderConfig { + width: 64, + height: 64, + base_q_idx: 100, + gop: 0, + colour: Colour::Bt709Limited, + }; + let err = Av1Encoder::new(config).unwrap_err(); + assert!(err.to_string().contains("gop"), "{err}"); + } +} diff --git a/crates/ec-av1/src/lib.rs b/crates/ec-av1/src/lib.rs index 149ff37c..d7a74798 100644 --- a/crates/ec-av1/src/lib.rs +++ b/crates/ec-av1/src/lib.rs @@ -16,6 +16,7 @@ pub mod bits; pub mod cdf; mod cdf_state; pub mod encode; +pub mod encoder; pub mod frame; pub mod intra; pub mod mc;