Merge branch 'lane-av1-facade': I11 streaming encoder facade with colour signalling
Browse files at this commit3 changed files +569 -22
- crates/ec-av1/src/encode.rs +53 -22
- crates/ec-av1/src/encoder.rs +515 -0
- crates/ec-av1/src/lib.rs +1 -0
crates/ec-av1/src/encode.rsmodified+53 -22
| @@ -45,7 +45,7 @@ const BLOCK: usize = 32; | |||
| 45 | const SUB: usize = 16; | 45 | const SUB: usize = 16; |
| 46 | 46 | ||
| 47 | /// The side of a superblock, which is what the partition tree starts from. | 47 | /// 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; |
| 49 | 49 | ||
| 50 | /// How heavily the mode search weighs rate against squared error, in units of | 50 | /// How heavily the mode search weighs rate against squared error, in units of |
| 51 | /// the quantizer's reconstruction step squared per bit. | 51 | /// the quantizer's reconstruction step squared per bit. |
| @@ -77,7 +77,7 @@ const SPLIT_BLOCKS: bool = true; | |||
| 77 | 77 | ||
| 78 | /// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides | 78 | /// What [`encode_key_frame_with_modes`] codes with, which the sweep overrides |
| 79 | /// by calling [`encode_key_frame_inner`] both ways. | 79 | /// by calling [`encode_key_frame_inner`] both ways. |
| 80 | -fn split_blocks() -> bool { | 80 | +pub(crate) fn split_blocks() -> bool { |
| 81 | SPLIT_BLOCKS | 81 | SPLIT_BLOCKS |
| 82 | } | 82 | } |
| 83 | 83 | ||
| @@ -109,7 +109,7 @@ impl Picture { | |||
| 109 | } | 109 | } |
| 110 | } | 110 | } |
| 111 | 111 | ||
| 112 | - fn check(&self) -> Result<()> { | 112 | + pub(crate) fn check(&self) -> Result<()> { |
| 113 | if self.width == 0 | 113 | if self.width == 0 |
| 114 | || !self.width.is_multiple_of(BLOCK) | 114 | || !self.width.is_multiple_of(BLOCK) |
| 115 | || !self.height.is_multiple_of(BLOCK) | 115 | || !self.height.is_multiple_of(BLOCK) |
| @@ -134,7 +134,7 @@ impl Picture { | |||
| 134 | /// before it is padded to the block grid: even, nonzero dimensions (4:2:0 | 134 | /// before it is padded to the block grid: even, nonzero dimensions (4:2:0 |
| 135 | /// needs a whole chroma sample per two luma ones) and one sample per | 135 | /// needs a whole chroma sample per two luma ones) and one sample per |
| 136 | /// position on each plane. | 136 | /// position on each plane. |
| 137 | - fn check_even(&self) -> Result<()> { | 137 | + pub(crate) fn check_even(&self) -> Result<()> { |
| 138 | if self.width == 0 | 138 | if self.width == 0 |
| 139 | || self.height == 0 | 139 | || self.height == 0 |
| 140 | || !self.width.is_multiple_of(2) | 140 | || !self.width.is_multiple_of(2) |
| @@ -162,7 +162,7 @@ impl Picture { | |||
| 162 | /// that). Identity (a plain clone, not a copy through the replication | 162 | /// that). Identity (a plain clone, not a copy through the replication |
| 163 | /// loop) when the picture is already that size — the multiple-of-32 (or | 163 | /// loop) when the picture is already that size — the multiple-of-32 (or |
| 164 | /// -64) fast path is unchanged. | 164 | /// -64) fast path is unchanged. |
| 165 | - fn padded_to(&self, align: usize) -> Picture { | 165 | + pub(crate) fn padded_to(&self, align: usize) -> Picture { |
| 166 | let padded_width = self.width.next_multiple_of(align); | 166 | let padded_width = self.width.next_multiple_of(align); |
| 167 | let padded_height = self.height.next_multiple_of(align); | 167 | let padded_height = self.height.next_multiple_of(align); |
| 168 | if padded_width == self.width && padded_height == self.height { | 168 | 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) - | |||
| 231 | /// region a decoder produces, which is the public contract for what a caller | 231 | /// region a decoder produces, which is the public contract for what a caller |
| 232 | /// sees back — the padded planes the encoder coded against never leave this | 232 | /// sees back — the padded planes the encoder coded against never leave this |
| 233 | /// module. Identity when the reconstruction is already that size. | 233 | /// 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 { |
| 235 | let reconstruction = &encoded.reconstruction; | 235 | let reconstruction = &encoded.reconstruction; |
| 236 | let cropped = if reconstruction.width == width && reconstruction.height == height { | 236 | let cropped = if reconstruction.width == width && reconstruction.height == height { |
| 237 | reconstruction.clone() | 237 | reconstruction.clone() |
| @@ -293,6 +293,43 @@ pub fn key_frame_headers( | |||
| 293 | width: usize, | 293 | width: usize, |
| 294 | height: usize, | 294 | height: usize, |
| 295 | base_q_idx: u8, | 295 | 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, | ||
| 296 | ) -> Result<(SequenceHeader, FrameHeader)> { | 333 | ) -> Result<(SequenceHeader, FrameHeader)> { |
| 297 | let bits = |n: usize| -> Result<u32> { | 334 | let bits = |n: usize| -> Result<u32> { |
| 298 | let n = u32::try_from(n).map_err(|_| too_large())?; | 335 | let n = u32::try_from(n).map_err(|_| too_large())?; |
| @@ -323,19 +360,7 @@ pub fn key_frame_headers( | |||
| 323 | enable_restoration: false, | 360 | enable_restoration: false, |
| 324 | seq_force_screen_content_tools: 0, | 361 | seq_force_screen_content_tools: 0, |
| 325 | seq_force_integer_mv: 0, | 362 | seq_force_integer_mv: 0, |
| 326 | - color_config: ColorConfig { | 363 | + color_config, |
| 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 | - }, | ||
| 339 | still_picture: false, | 364 | still_picture: false, |
| 340 | reduced_still_picture_header: false, | 365 | reduced_still_picture_header: false, |
| 341 | timing_info: None, | 366 | timing_info: None, |
| @@ -988,6 +1013,7 @@ pub fn encode_key_frame_with_modes( | |||
| 988 | modes, | 1013 | modes, |
| 989 | split_blocks(), | 1014 | split_blocks(), |
| 990 | (picture.width, picture.height), | 1015 | (picture.width, picture.height), |
| 1016 | + unspecified_color_config(), | ||
| 991 | )?; | 1017 | )?; |
| 992 | Ok(crop_encoded(&encoded, picture.width, picture.height)) | 1018 | Ok(crop_encoded(&encoded, picture.width, picture.height)) |
| 993 | } | 1019 | } |
| @@ -996,13 +1022,14 @@ pub fn encode_key_frame_with_modes( | |||
| 996 | /// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is | 1022 | /// what the sweep that sets [`SPLIT_BLOCKS`] measures both ways. `picture` is |
| 997 | /// already padded to a whole number of 32x32 blocks; `render` is the real | 1023 | /// already padded to a whole number of 32x32 blocks; `render` is the real |
| 998 | /// (pre-pad) size the frame header tells a decoder to crop back to. | 1024 | /// (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( |
| 1000 | picture: &Picture, | 1026 | picture: &Picture, |
| 1001 | base_q_idx: u8, | 1027 | base_q_idx: u8, |
| 1002 | deadzone: f64, | 1028 | deadzone: f64, |
| 1003 | modes: &[u8], | 1029 | modes: &[u8], |
| 1004 | split_blocks: bool, | 1030 | split_blocks: bool, |
| 1005 | render: (usize, usize), | 1031 | render: (usize, usize), |
| 1032 | + color_config: ColorConfig, | ||
| 1006 | ) -> Result<Encoded> { | 1033 | ) -> Result<Encoded> { |
| 1007 | picture.check()?; | 1034 | picture.check()?; |
| 1008 | if modes.is_empty() { | 1035 | if modes.is_empty() { |
| @@ -1017,7 +1044,8 @@ fn encode_key_frame_inner( | |||
| 1017 | format!("intra mode {bad} is not one the encoder predicts"), | 1044 | format!("intra mode {bad} is not one the encoder predicts"), |
| 1018 | )); | 1045 | )); |
| 1019 | } | 1046 | } |
| 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)?; | ||
| 1021 | header.render_width = render.0 as u32; | 1049 | header.render_width = render.0 as u32; |
| 1022 | header.render_height = render.1 as u32; | 1050 | header.render_height = render.1 as u32; |
| 1023 | 1051 | ||
| @@ -1638,7 +1666,7 @@ fn search_inter_block( | |||
| 1638 | /// Encodes one picture as an inter frame predicting from `reference`'s | 1666 | /// Encodes one picture as an inter frame predicting from `reference`'s |
| 1639 | /// reconstruction, which the caller decoded (or, for the frame right after | 1667 | /// reconstruction, which the caller decoded (or, for the frame right after |
| 1640 | /// the key frame, is the key frame's own reconstruction). | 1668 | /// the key frame, is the key frame's own reconstruction). |
| 1641 | -fn encode_inter_frame( | 1669 | +pub(crate) fn encode_inter_frame( |
| 1642 | picture: &Picture, | 1670 | picture: &Picture, |
| 1643 | reference: &Picture, | 1671 | reference: &Picture, |
| 1644 | base_q_idx: u8, | 1672 | base_q_idx: u8, |
| @@ -1827,6 +1855,7 @@ pub fn encode_sequence( | |||
| 1827 | &KEY_FRAME_MODES, | 1855 | &KEY_FRAME_MODES, |
| 1828 | split_blocks(), | 1856 | split_blocks(), |
| 1829 | render, | 1857 | render, |
| 1858 | + unspecified_color_config(), | ||
| 1830 | )?; | 1859 | )?; |
| 1831 | let mut stream = key.stream.clone(); | 1860 | let mut stream = key.stream.clone(); |
| 1832 | let mut reference = key.reconstruction.clone(); | 1861 | let mut reference = key.reconstruction.clone(); |
| @@ -2343,6 +2372,7 @@ mod tests { | |||
| 2343 | &KEY_FRAME_MODES, | 2372 | &KEY_FRAME_MODES, |
| 2344 | split, | 2373 | split, |
| 2345 | (picture.width, picture.height), | 2374 | (picture.width, picture.height), |
| 2375 | + unspecified_color_config(), | ||
| 2346 | ) | 2376 | ) |
| 2347 | .unwrap(); | 2377 | .unwrap(); |
| 2348 | ( | 2378 | ( |
| @@ -2362,6 +2392,7 @@ mod tests { | |||
| 2362 | &KEY_FRAME_MODES, | 2392 | &KEY_FRAME_MODES, |
| 2363 | true, | 2393 | true, |
| 2364 | (picture.width, picture.height), | 2394 | (picture.width, picture.height), |
| 2395 | + unspecified_color_config(), | ||
| 2365 | ) | 2396 | ) |
| 2366 | .unwrap() | 2397 | .unwrap() |
| 2367 | .modes | 2398 | .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; | |||
| 16 | pub mod cdf; | 16 | pub mod cdf; |
| 17 | mod cdf_state; | 17 | mod cdf_state; |
| 18 | pub mod encode; | 18 | pub mod encode; |
| 19 | +pub mod encoder; | ||
| 19 | pub mod frame; | 20 | pub mod frame; |
| 20 | pub mod intra; | 21 | pub mod intra; |
| 21 | pub mod mc; | 22 | pub mod mc; |