forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB682c080Tahinli2 months ago2434 commits

lib.rs328 lines, 10.8 KiBHistoryRawDownload
1//! The `rusty_h264` 0.9.1 surface, served by `ec-h264`.
2//!
3//! Only what edith consumes is here, at the incumbent's signatures:
4//! `Decoder::new` + `decode` over whole access units (decode.rs:1478-1500,
5//! export.rs:4200), and `EncoderConfig` + `Encoder::new` + `try_encode` +
6//! `try_flush` with `YuvFrame` and `Preset` (export.rs:3407-3422, 3640-3650,
7//! 3727-3736).
8//!
9//! Two differences from the incumbent, both deliberate and both visible only
10//! as *absences*:
11//!
12//! - No `#[global_allocator]`. The incumbent's `common` crate installed one
13//! process-wide and had to be vendored out; there is nothing to vendor here.
14//! - No lookahead buffering. `try_encode` returns the access unit of the
15//! picture it was handed, every time, so `try_flush` has nothing left to
16//! give and the caller's per-picture timing is exact whatever the rate
17//! control mode.
18//!
19//! Pictures come out in decode order, which is what the incumbent did and what
20//! edith's decode loop assumes. [`Decoder::in_display_order`] is the same
21//! decoder with the reordering the incumbent never had.
22
23#![forbid(unsafe_code)]
24
25use ec_h264::{NalOutcome, OutputOrder, PictureView};
26
27/// The incumbent's error type: one variant per refusal reason.
28#[derive(Debug)]
29pub enum Error {
30 NeedMore,
31 Invalid(String),
32 Unsupported(String),
33}
34
35impl std::fmt::Display for Error {
36 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37 match self {
38 Error::NeedMore => write!(f, "need more data"),
39 Error::Invalid(m) => write!(f, "invalid: {m}"),
40 Error::Unsupported(m) => write!(f, "unsupported: {m}"),
41 }
42 }
43}
44
45impl std::error::Error for Error {}
46
47impl From<ec_h264::Error> for Error {
48 fn from(e: ec_h264::Error) -> Error {
49 match e {
50 ec_h264::Error::NeedMore => Error::NeedMore,
51 ec_h264::Error::Unsupported { .. } => Error::Unsupported(e.to_string()),
52 other => Error::Invalid(other.to_string()),
53 }
54 }
55}
56
57/// A decoded — or about to be encoded — I420 picture, planes owned.
58#[derive(Debug, Clone, Default, PartialEq, Eq)]
59pub struct YuvFrame {
60 pub width: usize,
61 pub height: usize,
62 pub y: Vec<u8>,
63 pub u: Vec<u8>,
64 pub v: Vec<u8>,
65}
66
67/// Speed/quality ladder.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
69pub enum Preset {
70 #[default]
71 Fast,
72 Balanced,
73}
74
75impl From<Preset> for ec_h264::Preset {
76 fn from(p: Preset) -> ec_h264::Preset {
77 match p {
78 Preset::Fast => ec_h264::Preset::Fast,
79 Preset::Balanced => ec_h264::Preset::Balanced,
80 }
81 }
82}
83
84/// The H.264 software decoder.
85pub struct Decoder {
86 inner: ec_h264::Decoder,
87}
88
89impl Default for Decoder {
90 fn default() -> Decoder {
91 Decoder::new()
92 }
93}
94
95impl Decoder {
96 /// A decoder that emits pictures in decode order.
97 pub fn new() -> Decoder {
98 let mut inner = ec_h264::Decoder::new();
99 inner.set_output_order(OutputOrder::Decode);
100 Decoder { inner }
101 }
102
103 /// A decoder that emits pictures in *display* order, which a stream with
104 /// B pictures needs and the incumbent could not do. Pictures then come out
105 /// with the stream's own reordering delay, so a caller that stops feeding
106 /// must call [`Decoder::flush`] to collect the tail.
107 pub fn in_display_order() -> Decoder {
108 let mut inner = ec_h264::Decoder::new();
109 inner.set_output_order(OutputOrder::Display);
110 Decoder { inner }
111 }
112
113 /// Decode one access unit (Annex B, one coded picture), returning the
114 /// picture it completed if any.
115 pub fn decode(&mut self, au: &[u8]) -> Result<Option<YuvFrame>, Error> {
116 self.feed(au)?;
117 if self.inner.picture_open() {
118 self.inner.end_picture()?;
119 }
120 Ok(self.take())
121 }
122
123 /// Decode a whole Annex B stream at once, returning every picture in it —
124 /// what a test that holds an encoder's output in memory asks for, where
125 /// [`Decoder::decode`] serves a demuxer handing over one unit at a time.
126 pub fn decode_stream(&mut self, stream: &[u8]) -> Result<Vec<YuvFrame>, Error> {
127 let mut out = Vec::new();
128 self.feed(stream)?;
129 // The tail: whatever the last picture and the reordering delay hold.
130 self.inner.flush()?;
131 while let Some(frame) = self.take() {
132 out.push(frame);
133 }
134 Ok(out)
135 }
136
137 /// Push every NAL in `bytes`, closing a picture wherever one ends.
138 fn feed(&mut self, bytes: &[u8]) -> Result<(), Error> {
139 for nal in ec_h264_syntax::AnnexBIter::new(bytes) {
140 if self.inner.push_nal(nal)? == NalOutcome::PictureBoundary {
141 // The next picture starts here: close the one before it.
142 self.inner.end_picture()?;
143 self.inner.push_nal(nal)?;
144 }
145 }
146 Ok(())
147 }
148
149 /// Collect a picture the reordering delay is still holding, at end of
150 /// stream.
151 pub fn flush(&mut self) -> Result<Option<YuvFrame>, Error> {
152 self.inner.flush()?;
153 Ok(self.take())
154 }
155
156 fn take(&mut self) -> Option<YuvFrame> {
157 let frame = self.inner.next_frame()?;
158 let (w, h) = (frame.width as usize, frame.height as usize);
159 let plane = |i: usize, pw: usize, ph: usize| -> Vec<u8> {
160 let p = &frame.planes[i];
161 let mut out = Vec::with_capacity(pw * ph);
162 for row in 0..ph {
163 out.extend_from_slice(&p.data[row * p.stride..row * p.stride + pw]);
164 }
165 out
166 };
167 Some(YuvFrame {
168 width: w,
169 height: h,
170 y: plane(0, w, h),
171 u: plane(1, w / 2, h / 2),
172 v: plane(2, w / 2, h / 2),
173 })
174 }
175}
176
177/// Encoder settings, at the incumbent's field names.
178#[derive(Debug, Clone)]
179pub struct EncoderConfig {
180 pub width: usize,
181 pub height: usize,
182 pub framerate: f32,
183 /// Bits per second; zero codes at a constant quantiser instead.
184 pub bitrate: u32,
185 pub gop_size: u32,
186 /// Consecutive B pictures. Accepted at any value and coded as zero: this
187 /// encoder has no B pictures yet, and refusing the field would break a
188 /// caller that sets it.
189 pub bframes: u32,
190 pub preset: Preset,
191}
192
193impl EncoderConfig {
194 /// The incumbent's constructor: geometry now, everything else by field.
195 pub fn new(width: usize, height: usize) -> EncoderConfig {
196 EncoderConfig {
197 width,
198 height,
199 framerate: 30.0,
200 bitrate: 0,
201 gop_size: 250,
202 bframes: 0,
203 preset: Preset::Fast,
204 }
205 }
206}
207
208/// The H.264 software encoder.
209pub struct Encoder {
210 inner: ec_h264::Encoder,
211 width: usize,
212 height: usize,
213}
214
215impl Encoder {
216 pub fn new(cfg: EncoderConfig) -> Result<Encoder, Error> {
217 let mut inner_cfg = ec_h264::EncoderConfig::new(cfg.width as u32, cfg.height as u32);
218 inner_cfg.framerate = cfg.framerate;
219 inner_cfg.bitrate = cfg.bitrate;
220 inner_cfg.gop_size = cfg.gop_size;
221 inner_cfg.bframes = cfg.bframes;
222 inner_cfg.preset = cfg.preset.into();
223 let inner = ec_h264::Encoder::new(inner_cfg)?;
224 Ok(Encoder {
225 inner,
226 width: cfg.width,
227 height: cfg.height,
228 })
229 }
230
231 /// One picture in, its access unit out — always, with no lookahead delay.
232 pub fn try_encode(&mut self, frame: &YuvFrame) -> Result<Vec<u8>, Error> {
233 if frame.width != self.width || frame.height != self.height {
234 return Err(Error::Invalid(format!(
235 "frame is {}x{}, encoder is {}x{}",
236 frame.width, frame.height, self.width, self.height
237 )));
238 }
239 let view = PictureView::i420(
240 self.width as u32,
241 self.height as u32,
242 &frame.y,
243 &frame.u,
244 &frame.v,
245 );
246 Ok(self.inner.encode(&view)?.au)
247 }
248
249 /// Nothing is ever held back, so this is always empty; it exists because
250 /// the caller's drain path calls it.
251 pub fn try_flush(&mut self) -> Result<Vec<u8>, Error> {
252 Ok(Vec::new())
253 }
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259
260 fn frame(w: usize, h: usize, t: usize) -> YuvFrame {
261 YuvFrame {
262 width: w,
263 height: h,
264 y: (0..w * h)
265 .map(|i| ((i / w + i % w + t * 4) % 256) as u8)
266 .collect(),
267 u: vec![110; w / 2 * h / 2],
268 v: vec![150; w / 2 * h / 2],
269 }
270 }
271
272 /// The whole surface edith calls, in the order edith calls it: configure,
273 /// encode picture by picture, drain, then decode what came out.
274 #[test]
275 fn the_edith_call_sequence_round_trips() {
276 let (w, h) = (176usize, 144usize);
277 let mut cfg = EncoderConfig::new(w, h);
278 cfg.framerate = 25.0;
279 cfg.bitrate = 600_000;
280 cfg.gop_size = 5;
281 cfg.bframes = 0;
282 cfg.preset = Preset::Fast;
283 let mut enc = Encoder::new(cfg).expect("encoder");
284 let mut units = Vec::new();
285 for t in 0..6 {
286 let au = enc.try_encode(&frame(w, h, t)).expect("encode");
287 assert!(!au.is_empty(), "picture {t} produced no access unit");
288 units.push(au);
289 }
290 assert!(enc.try_flush().expect("flush").is_empty());
291
292 let mut dec = Decoder::new();
293 for (t, au) in units.iter().enumerate() {
294 let got = dec.decode(au).expect("decode").expect("a picture");
295 assert_eq!((got.width, got.height), (w, h), "picture {t} geometry");
296 assert_eq!(got.y.len(), w * h);
297 assert_eq!(got.u.len(), w / 2 * h / 2);
298 // A coded picture is close to its source; this is the shim's own
299 // proof that the two halves are wired to each other.
300 let src = frame(w, h, t);
301 let mse: f64 = got
302 .y
303 .iter()
304 .zip(&src.y)
305 .map(|(&a, &b)| {
306 let d = f64::from(a) - f64::from(b);
307 d * d
308 })
309 .sum::<f64>()
310 / (w * h) as f64;
311 assert!(mse < 25.0, "picture {t}: mean squared error {mse:.1}");
312 }
313
314 // And the same units as one stream, which is how a test that kept the
315 // encoder's output in a `Vec` decodes it back.
316 let whole: Vec<u8> = units.concat();
317 let frames = Decoder::new().decode_stream(&whole).expect("decode stream");
318 assert_eq!(frames.len(), units.len(), "one picture per access unit");
319 }
320
321 /// A frame whose geometry does not match the encoder is refused by name.
322 #[test]
323 fn geometry_mismatch_is_refused() {
324 let mut enc = Encoder::new(EncoderConfig::new(64, 64)).expect("encoder");
325 let err = enc.try_encode(&frame(32, 32, 0)).unwrap_err();
326 assert!(matches!(err, Error::Invalid(_)), "{err}");
327 }
328}