forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB214cdf2Tahinli3 months ago821 commits

lib.rs503 lines, 15.1 KiBHistoryRawDownload
1//! `oxideav-core` as edith consumes it, over [`ec_core`].
2//!
3//! A shim, not a port: it carries the incumbent's package name and version so a
4//! swap is a `[patch.crates-io]` line and nothing else, and it exposes exactly
5//! the items the replica names — no more, because an item nobody calls is an
6//! item nobody can check. The list, and where each is called from, is in the
7//! subtitle and export paths of the engine: `Packet::new`, `TimeBase::new`,
8//! `Error::NeedMore`, `CodecId`, `CodecParameters::{audio,subtitle}`,
9//! `CodecRegistry`, `Decoder`, `Frame`, `Muxer`, `StreamInfo`, `Result`.
10//!
11//! Where the two IRs differ in *shape* the shim owns the difference:
12//! `oxideav`'s codec id is a string and `ec_core`'s is an enum, its frames own
13//! their bytes and `ec_core`'s share a refcounted buffer. Those are converted
14//! here, once, rather than at every call site of the replica.
15//!
16//! [`Packet`] and [`TimeBase`] are `ec_core`'s own: their signatures already
17//! match what the replica writes, so a re-export is the whole adapter.
18
19#![forbid(unsafe_code)]
20
21use std::collections::HashMap;
22use std::fmt;
23
24pub use ec_core::{Packet, TimeBase};
25
26/// What a call into this family can go wrong with.
27///
28/// `NeedMore` is load-bearing: the replica's AC-3 path treats it as "not an
29/// error, feed me another packet" and everything else as a failure.
30#[derive(Debug)]
31#[non_exhaustive]
32pub enum Error {
33 /// The decoder wants another packet before it can hand back a frame.
34 NeedMore,
35 /// End of stream.
36 Eof,
37 /// Well-formed but not supported.
38 Unsupported(String),
39 /// Malformed input.
40 InvalidData(String),
41 /// No codec in the registry claims these parameters.
42 CodecNotFound(String),
43 /// Underlying I/O.
44 Io(std::io::Error),
45 /// Anything else.
46 Other(String),
47}
48
49impl fmt::Display for Error {
50 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51 match self {
52 Error::NeedMore => write!(f, "more input needed"),
53 Error::Eof => write!(f, "end of stream"),
54 Error::Unsupported(what) => write!(f, "unsupported: {what}"),
55 Error::InvalidData(what) => write!(f, "invalid data: {what}"),
56 Error::CodecNotFound(id) => write!(f, "no codec {id}"),
57 Error::Io(e) => write!(f, "{e}"),
58 Error::Other(what) => write!(f, "{what}"),
59 }
60 }
61}
62
63impl std::error::Error for Error {}
64
65impl From<std::io::Error> for Error {
66 fn from(e: std::io::Error) -> Error {
67 Error::Io(e)
68 }
69}
70
71impl From<ec_core::Error> for Error {
72 fn from(e: ec_core::Error) -> Error {
73 match e {
74 ec_core::Error::NeedMore => Error::NeedMore,
75 ec_core::Error::Eof => Error::Eof,
76 ec_core::Error::Unsupported { what, why } => {
77 Error::Unsupported(format!("{what}: {why}"))
78 }
79 ec_core::Error::Corrupt { context } => Error::InvalidData(context),
80 ec_core::Error::Io(e) => Error::Io(e),
81 }
82 }
83}
84
85/// This family's result.
86pub type Result<T> = std::result::Result<T, Error>;
87
88/// A codec's identifier, as a string: `"ac3"`, `"pgs"`, `"vorbis"`.
89#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
90pub struct CodecId(pub String);
91
92impl CodecId {
93 /// The id named by `s`.
94 pub fn new(s: impl Into<String>) -> CodecId {
95 CodecId(s.into())
96 }
97
98 /// The name itself.
99 pub fn as_str(&self) -> &str {
100 &self.0
101 }
102
103 /// The `ec_core` codec this names, when the family carries it.
104 pub fn to_ec(&self) -> Option<ec_core::CodecId> {
105 use ec_core::CodecId::*;
106 Some(match self.0.as_str() {
107 "h264" | "avc1" => H264,
108 "h265" | "hevc" => H265,
109 "vp8" => Vp8,
110 "vp9" => Vp9,
111 "av1" => Av1,
112 "aac" => Aac,
113 "ac3" => Ac3,
114 "eac3" => EAc3,
115 "alac" => Alac,
116 "flac" => Flac,
117 "mp3" => Mp3,
118 "opus" => Opus,
119 "vorbis" => Vorbis,
120 "srt" | "subrip" => Srt,
121 "webvtt" | "vtt" => WebVtt,
122 "ass" | "ssa" => Ass,
123 "pgs" => Pgs,
124 "tx3g" => Tx3g,
125 _ => return None,
126 })
127 }
128}
129
130impl fmt::Display for CodecId {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 f.write_str(&self.0)
133 }
134}
135
136impl From<&str> for CodecId {
137 fn from(s: &str) -> CodecId {
138 CodecId(s.to_owned())
139 }
140}
141
142impl From<String> for CodecId {
143 fn from(s: String) -> CodecId {
144 CodecId(s)
145 }
146}
147
148/// What kind of stream a set of parameters describes.
149#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
150pub enum MediaType {
151 /// Audio samples.
152 Audio,
153 /// Video pictures.
154 Video,
155 /// Timed text or subtitle bitmaps.
156 Subtitle,
157 /// Opaque payload.
158 Data,
159 /// Not yet determined.
160 #[default]
161 Unknown,
162}
163
164/// Everything a decoder is told before its first packet.
165#[derive(Clone, Debug, Default, PartialEq, Eq)]
166pub struct CodecParameters {
167 /// Which codec.
168 pub codec_id: CodecId,
169 /// Which kind of stream.
170 pub media_type: MediaType,
171 /// Audio sample rate.
172 pub sample_rate: Option<u32>,
173 /// Audio channel count — the replica asks for `Some(2)` to get a downmix.
174 pub channels: Option<u16>,
175 /// Coded width.
176 pub width: Option<u32>,
177 /// Coded height.
178 pub height: Option<u32>,
179 /// Codec setup bytes.
180 pub extradata: Vec<u8>,
181}
182
183impl CodecParameters {
184 /// Audio parameters for `codec_id`.
185 pub fn audio(codec_id: CodecId) -> CodecParameters {
186 CodecParameters {
187 codec_id,
188 media_type: MediaType::Audio,
189 ..CodecParameters::default()
190 }
191 }
192
193 /// Video parameters for `codec_id`.
194 pub fn video(codec_id: CodecId) -> CodecParameters {
195 CodecParameters {
196 codec_id,
197 media_type: MediaType::Video,
198 ..CodecParameters::default()
199 }
200 }
201
202 /// Subtitle parameters for `codec_id`.
203 pub fn subtitle(codec_id: CodecId) -> CodecParameters {
204 CodecParameters {
205 codec_id,
206 media_type: MediaType::Subtitle,
207 ..CodecParameters::default()
208 }
209 }
210
211 /// Data-stream parameters for `codec_id`.
212 pub fn data(codec_id: CodecId) -> CodecParameters {
213 CodecParameters {
214 codec_id,
215 media_type: MediaType::Data,
216 ..CodecParameters::default()
217 }
218 }
219}
220
221/// One stream of a container, as a muxer is told about it.
222#[derive(Clone, Debug, PartialEq, Eq)]
223pub struct StreamInfo {
224 /// Index the stream's packets carry.
225 pub index: u32,
226 /// The unit its timestamps are in.
227 pub time_base: TimeBase,
228 /// Duration in `time_base` ticks.
229 pub duration: Option<i64>,
230 /// First timestamp in `time_base` ticks.
231 pub start_time: Option<i64>,
232 /// What is in it.
233 pub params: CodecParameters,
234}
235
236/// One decoded picture.
237///
238/// No dimensions: the incumbent states them on the stream's
239/// [`CodecParameters`] and puts only the row stride on the plane, and a codec
240/// crate outside this workspace writes the literal (`oxideav-h265`'s decoder
241/// does), so the field list is the incumbent's and not ours to improve.
242#[derive(Clone, Debug, Default, PartialEq, Eq)]
243pub struct VideoFrame {
244 /// Presentation time in the stream's time base.
245 pub pts: Option<i64>,
246 /// One plane per component group; packed formats have exactly one.
247 pub planes: Vec<VideoPlane>,
248}
249
250/// One plane of a [`VideoFrame`].
251#[derive(Clone, Debug, Default, PartialEq, Eq)]
252pub struct VideoPlane {
253 /// Bytes between the starts of two rows.
254 pub stride: usize,
255 /// The plane's bytes.
256 pub data: Vec<u8>,
257}
258
259/// One decoded block of audio.
260#[derive(Clone, Debug, Default, PartialEq, Eq)]
261pub struct AudioFrame {
262 /// Frames per channel in this block.
263 pub samples: u32,
264 /// Presentation time in the stream's time base.
265 pub pts: Option<i64>,
266 /// Interleaved (one entry) or planar (one entry per channel) bytes.
267 pub data: Vec<Vec<u8>>,
268}
269
270/// What a decoder hands back.
271#[derive(Clone, Debug, PartialEq, Eq)]
272pub enum Frame {
273 /// A picture.
274 Video(VideoFrame),
275 /// An audio block.
276 Audio(AudioFrame),
277}
278
279impl From<ec_core::Frame> for Frame {
280 fn from(frame: ec_core::Frame) -> Frame {
281 match frame {
282 ec_core::Frame::Video(video) => Frame::Video(VideoFrame {
283 pts: video.pts.map(|t| t.ticks),
284 planes: video
285 .planes
286 .into_iter()
287 .map(|plane| VideoPlane {
288 stride: plane.stride,
289 data: plane.data.to_vec(),
290 })
291 .collect(),
292 }),
293 ec_core::Frame::Audio(audio) => Frame::Audio(AudioFrame {
294 samples: audio.samples as u32,
295 pts: audio.pts.map(|t| t.ticks),
296 data: audio.data.iter().map(|buf| buf.to_vec()).collect(),
297 }),
298 }
299 }
300}
301
302/// A decoder: packets in, frames out.
303pub trait Decoder: Send {
304 /// The codec this decodes.
305 fn codec_id(&self) -> &CodecId;
306
307 /// Feed one packet.
308 fn send_packet(&mut self, packet: &Packet) -> Result<()>;
309
310 /// Take one frame, or [`Error::NeedMore`] when the decoder wants another
311 /// packet first.
312 fn receive_frame(&mut self) -> Result<Frame>;
313
314 /// Signal end of input, so whatever is held back becomes available through
315 /// [`receive_frame`](Decoder::receive_frame) and then [`Error::Eof`].
316 ///
317 /// The default is for a decoder that holds nothing back — one packet in,
318 /// one frame out, which is what the AC-3 path is.
319 fn flush(&mut self) -> Result<()> {
320 Ok(())
321 }
322}
323
324/// A container writer.
325pub trait Muxer: Send {
326 /// The format's short name.
327 fn format_name(&self) -> &str;
328
329 /// Write whatever precedes the first packet.
330 fn write_header(&mut self) -> Result<()>;
331
332 /// Write one packet.
333 fn write_packet(&mut self, packet: &Packet) -> Result<()>;
334
335 /// Write whatever follows the last one.
336 fn write_trailer(&mut self) -> Result<()>;
337}
338
339/// How a codec crate hands out decoders.
340pub type DecoderFactory = fn(&CodecParameters) -> Result<Box<dyn Decoder>>;
341
342/// One codec's registration.
343#[derive(Clone)]
344pub struct CodecInfo {
345 /// The id this claims.
346 pub id: CodecId,
347 /// How to build a decoder for it.
348 pub decoder_factory: Option<DecoderFactory>,
349}
350
351impl CodecInfo {
352 /// An empty registration for `id`.
353 pub fn new(id: CodecId) -> CodecInfo {
354 CodecInfo {
355 id,
356 decoder_factory: None,
357 }
358 }
359
360 /// The same registration, with a decoder.
361 pub fn decoder(mut self, factory: DecoderFactory) -> CodecInfo {
362 self.decoder_factory = Some(factory);
363 self
364 }
365}
366
367/// The codecs a caller has registered, in registration order per id.
368///
369/// The replica builds one of these per AC-3 segment, registers that crate's
370/// codecs into it and asks for the first decoder that claims the parameters.
371#[derive(Clone, Default)]
372pub struct CodecRegistry {
373 by_id: HashMap<CodecId, Vec<CodecInfo>>,
374}
375
376impl CodecRegistry {
377 /// An empty registry.
378 pub fn new() -> CodecRegistry {
379 CodecRegistry::default()
380 }
381
382 /// Add one codec.
383 pub fn register(&mut self, info: CodecInfo) {
384 self.by_id.entry(info.id.clone()).or_default().push(info);
385 }
386
387 /// True when something registered can decode `id`.
388 pub fn has_decoder(&self, id: &CodecId) -> bool {
389 self.by_id
390 .get(id)
391 .is_some_and(|infos| infos.iter().any(|i| i.decoder_factory.is_some()))
392 }
393
394 /// A decoder from the first registration that offers one.
395 pub fn first_decoder(&self, params: &CodecParameters) -> Result<Box<dyn Decoder>> {
396 let factory = self
397 .by_id
398 .get(&params.codec_id)
399 .and_then(|infos| infos.iter().find_map(|i| i.decoder_factory))
400 .ok_or_else(|| Error::CodecNotFound(params.codec_id.0.clone()))?;
401 factory(params)
402 }
403}
404
405/// A [`Decoder`] over one of the family's own, converting the frames on the way
406/// out. Codec shims are two lines with this: build the `ec_core` decoder, wrap.
407pub struct EcDecoder {
408 id: CodecId,
409 inner: Box<dyn ec_core::Decoder>,
410}
411
412impl EcDecoder {
413 /// Wrap `inner`, which decodes the codec named `id`.
414 pub fn new(id: CodecId, inner: Box<dyn ec_core::Decoder>) -> EcDecoder {
415 EcDecoder { id, inner }
416 }
417}
418
419impl Decoder for EcDecoder {
420 fn codec_id(&self) -> &CodecId {
421 &self.id
422 }
423
424 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
425 Ok(self.inner.send_packet(packet)?)
426 }
427
428 fn receive_frame(&mut self) -> Result<Frame> {
429 Ok(self.inner.receive_frame()?.into())
430 }
431}
432
433#[cfg(test)]
434mod tests {
435 use super::*;
436
437 /// A decoder that answers one frame per packet, for the registry test.
438 struct Stub(CodecId);
439
440 impl Decoder for Stub {
441 fn codec_id(&self) -> &CodecId {
442 &self.0
443 }
444
445 fn send_packet(&mut self, _packet: &Packet) -> Result<()> {
446 Ok(())
447 }
448
449 fn receive_frame(&mut self) -> Result<Frame> {
450 Err(Error::NeedMore)
451 }
452 }
453
454 fn stub(params: &CodecParameters) -> Result<Box<dyn Decoder>> {
455 Ok(Box::new(Stub(params.codec_id.clone())))
456 }
457
458 #[test]
459 fn the_registry_hands_back_what_was_registered_and_names_what_was_not() {
460 let mut registry = CodecRegistry::new();
461 registry.register(CodecInfo::new(CodecId::new("ac3")).decoder(stub));
462 let params = CodecParameters::audio(CodecId::new("ac3"));
463 let mut decoder = registry.first_decoder(&params).unwrap();
464 assert_eq!(decoder.codec_id().as_str(), "ac3");
465 assert!(matches!(decoder.receive_frame(), Err(Error::NeedMore)));
466 assert!(registry.has_decoder(&CodecId::new("ac3")));
467
468 let missing = CodecParameters::audio(CodecId::new("truehd"));
469 assert!(matches!(
470 registry.first_decoder(&missing),
471 Err(Error::CodecNotFound(id)) if id == "truehd"
472 ));
473 }
474
475 #[test]
476 fn frames_and_errors_cross_the_boundary_intact() {
477 let plane = ec_core::Plane::new(vec![1u8, 2, 3, 4], 4);
478 let video =
479 ec_core::VideoFrame::try_new(ec_core::PixelFormat::Rgba8, 1, 1, vec![plane]).unwrap();
480 let Frame::Video(frame) = Frame::from(ec_core::Frame::Video(video)) else {
481 panic!("a video frame stays a video frame");
482 };
483 assert_eq!(frame.planes[0].data, vec![1, 2, 3, 4]);
484 assert_eq!(frame.planes[0].stride, 4);
485
486 // The one error the replica matches on by name.
487 assert!(matches!(
488 Error::from(ec_core::Error::NeedMore),
489 Error::NeedMore
490 ));
491 assert_eq!(
492 Error::from(ec_core::Error::corrupt("torn")).to_string(),
493 "invalid data: torn"
494 );
495 }
496
497 #[test]
498 fn a_packet_is_written_the_way_the_replica_writes_one() {
499 let packet = Packet::new(0, TimeBase::new(1, 90_000), vec![0u8; 8]);
500 assert_eq!(packet.data.len(), 8);
501 assert_eq!(packet.time_base, TimeBase::new(1, 90_000));
502 }
503}