forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.5 MiB98eeb6cTahinli3 months ago90 commits

lib.rs302 lines, 9.7 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 for nal in ec_h264_syntax::AnnexBIter::new(au) {
117 if self.inner.push_nal(nal)? == NalOutcome::PictureBoundary {
118 // Two pictures in one access unit: close the first one.
119 self.inner.end_picture()?;
120 self.inner.push_nal(nal)?;
121 }
122 }
123 if self.inner.picture_open() {
124 self.inner.end_picture()?;
125 }
126 Ok(self.take())
127 }
128
129 /// Collect a picture the reordering delay is still holding, at end of
130 /// stream.
131 pub fn flush(&mut self) -> Result<Option<YuvFrame>, Error> {
132 self.inner.flush()?;
133 Ok(self.take())
134 }
135
136 fn take(&mut self) -> Option<YuvFrame> {
137 let frame = self.inner.next_frame()?;
138 let (w, h) = (frame.width as usize, frame.height as usize);
139 let plane = |i: usize, pw: usize, ph: usize| -> Vec<u8> {
140 let p = &frame.planes[i];
141 let mut out = Vec::with_capacity(pw * ph);
142 for row in 0..ph {
143 out.extend_from_slice(&p.data[row * p.stride..row * p.stride + pw]);
144 }
145 out
146 };
147 Some(YuvFrame {
148 width: w,
149 height: h,
150 y: plane(0, w, h),
151 u: plane(1, w / 2, h / 2),
152 v: plane(2, w / 2, h / 2),
153 })
154 }
155}
156
157/// Encoder settings, at the incumbent's field names.
158#[derive(Debug, Clone)]
159pub struct EncoderConfig {
160 pub width: usize,
161 pub height: usize,
162 pub framerate: f32,
163 /// Bits per second; zero codes at a constant quantiser instead.
164 pub bitrate: u32,
165 pub gop_size: u32,
166 /// Consecutive B pictures. Accepted at any value and coded as zero: this
167 /// encoder has no B pictures yet, and refusing the field would break a
168 /// caller that sets it.
169 pub bframes: u32,
170 pub preset: Preset,
171}
172
173impl EncoderConfig {
174 /// The incumbent's constructor: geometry now, everything else by field.
175 pub fn new(width: usize, height: usize) -> EncoderConfig {
176 EncoderConfig {
177 width,
178 height,
179 framerate: 30.0,
180 bitrate: 0,
181 gop_size: 250,
182 bframes: 0,
183 preset: Preset::Fast,
184 }
185 }
186}
187
188/// The H.264 software encoder.
189pub struct Encoder {
190 inner: ec_h264::Encoder,
191 width: usize,
192 height: usize,
193}
194
195impl Encoder {
196 pub fn new(cfg: EncoderConfig) -> Result<Encoder, Error> {
197 let mut inner_cfg = ec_h264::EncoderConfig::new(cfg.width as u32, cfg.height as u32);
198 inner_cfg.framerate = cfg.framerate;
199 inner_cfg.bitrate = cfg.bitrate;
200 inner_cfg.gop_size = cfg.gop_size;
201 inner_cfg.bframes = cfg.bframes;
202 inner_cfg.preset = cfg.preset.into();
203 let inner = ec_h264::Encoder::new(inner_cfg)?;
204 Ok(Encoder {
205 inner,
206 width: cfg.width,
207 height: cfg.height,
208 })
209 }
210
211 /// One picture in, its access unit out — always, with no lookahead delay.
212 pub fn try_encode(&mut self, frame: &YuvFrame) -> Result<Vec<u8>, Error> {
213 if frame.width != self.width || frame.height != self.height {
214 return Err(Error::Invalid(format!(
215 "frame is {}x{}, encoder is {}x{}",
216 frame.width, frame.height, self.width, self.height
217 )));
218 }
219 let view = PictureView::i420(
220 self.width as u32,
221 self.height as u32,
222 &frame.y,
223 &frame.u,
224 &frame.v,
225 );
226 Ok(self.inner.encode(&view)?.au)
227 }
228
229 /// Nothing is ever held back, so this is always empty; it exists because
230 /// the caller's drain path calls it.
231 pub fn try_flush(&mut self) -> Result<Vec<u8>, Error> {
232 Ok(Vec::new())
233 }
234}
235
236#[cfg(test)]
237mod tests {
238 use super::*;
239
240 fn frame(w: usize, h: usize, t: usize) -> YuvFrame {
241 YuvFrame {
242 width: w,
243 height: h,
244 y: (0..w * h)
245 .map(|i| ((i / w + i % w + t * 4) % 256) as u8)
246 .collect(),
247 u: vec![110; w / 2 * h / 2],
248 v: vec![150; w / 2 * h / 2],
249 }
250 }
251
252 /// The whole surface edith calls, in the order edith calls it: configure,
253 /// encode picture by picture, drain, then decode what came out.
254 #[test]
255 fn the_edith_call_sequence_round_trips() {
256 let (w, h) = (176usize, 144usize);
257 let mut cfg = EncoderConfig::new(w, h);
258 cfg.framerate = 25.0;
259 cfg.bitrate = 600_000;
260 cfg.gop_size = 5;
261 cfg.bframes = 0;
262 cfg.preset = Preset::Fast;
263 let mut enc = Encoder::new(cfg).expect("encoder");
264 let mut units = Vec::new();
265 for t in 0..6 {
266 let au = enc.try_encode(&frame(w, h, t)).expect("encode");
267 assert!(!au.is_empty(), "picture {t} produced no access unit");
268 units.push(au);
269 }
270 assert!(enc.try_flush().expect("flush").is_empty());
271
272 let mut dec = Decoder::new();
273 for (t, au) in units.iter().enumerate() {
274 let got = dec.decode(au).expect("decode").expect("a picture");
275 assert_eq!((got.width, got.height), (w, h), "picture {t} geometry");
276 assert_eq!(got.y.len(), w * h);
277 assert_eq!(got.u.len(), w / 2 * h / 2);
278 // A coded picture is close to its source; this is the shim's own
279 // proof that the two halves are wired to each other.
280 let src = frame(w, h, t);
281 let mse: f64 = got
282 .y
283 .iter()
284 .zip(&src.y)
285 .map(|(&a, &b)| {
286 let d = f64::from(a) - f64::from(b);
287 d * d
288 })
289 .sum::<f64>()
290 / (w * h) as f64;
291 assert!(mse < 25.0, "picture {t}: mean squared error {mse:.1}");
292 }
293 }
294
295 /// A frame whose geometry does not match the encoder is refused by name.
296 #[test]
297 fn geometry_mismatch_is_refused() {
298 let mut enc = Encoder::new(EncoderConfig::new(64, 64)).expect("encoder");
299 let err = enc.try_encode(&frame(32, 32, 0)).unwrap_err();
300 assert!(matches!(err, Error::Invalid(_)), "{err}");
301 }
302}