forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB30d372eTahinli3 months ago42 commits

lib.rs484 lines, 14.5 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
136/// What kind of stream a set of parameters describes.
137#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
138pub enum MediaType {
139 /// Audio samples.
140 Audio,
141 /// Video pictures.
142 Video,
143 /// Timed text or subtitle bitmaps.
144 Subtitle,
145 /// Opaque payload.
146 Data,
147 /// Not yet determined.
148 #[default]
149 Unknown,
150}
151
152/// Everything a decoder is told before its first packet.
153#[derive(Clone, Debug, Default, PartialEq, Eq)]
154pub struct CodecParameters {
155 /// Which codec.
156 pub codec_id: CodecId,
157 /// Which kind of stream.
158 pub media_type: MediaType,
159 /// Audio sample rate.
160 pub sample_rate: Option<u32>,
161 /// Audio channel count — the replica asks for `Some(2)` to get a downmix.
162 pub channels: Option<u16>,
163 /// Coded width.
164 pub width: Option<u32>,
165 /// Coded height.
166 pub height: Option<u32>,
167 /// Codec setup bytes.
168 pub extradata: Vec<u8>,
169}
170
171impl CodecParameters {
172 /// Audio parameters for `codec_id`.
173 pub fn audio(codec_id: CodecId) -> CodecParameters {
174 CodecParameters {
175 codec_id,
176 media_type: MediaType::Audio,
177 ..CodecParameters::default()
178 }
179 }
180
181 /// Video parameters for `codec_id`.
182 pub fn video(codec_id: CodecId) -> CodecParameters {
183 CodecParameters {
184 codec_id,
185 media_type: MediaType::Video,
186 ..CodecParameters::default()
187 }
188 }
189
190 /// Subtitle parameters for `codec_id`.
191 pub fn subtitle(codec_id: CodecId) -> CodecParameters {
192 CodecParameters {
193 codec_id,
194 media_type: MediaType::Subtitle,
195 ..CodecParameters::default()
196 }
197 }
198
199 /// Data-stream parameters for `codec_id`.
200 pub fn data(codec_id: CodecId) -> CodecParameters {
201 CodecParameters {
202 codec_id,
203 media_type: MediaType::Data,
204 ..CodecParameters::default()
205 }
206 }
207}
208
209/// One stream of a container, as a muxer is told about it.
210#[derive(Clone, Debug, PartialEq, Eq)]
211pub struct StreamInfo {
212 /// Index the stream's packets carry.
213 pub index: u32,
214 /// The unit its timestamps are in.
215 pub time_base: TimeBase,
216 /// Duration in `time_base` ticks.
217 pub duration: Option<i64>,
218 /// First timestamp in `time_base` ticks.
219 pub start_time: Option<i64>,
220 /// What is in it.
221 pub params: CodecParameters,
222}
223
224/// One decoded picture.
225#[derive(Clone, Debug, Default, PartialEq, Eq)]
226pub struct VideoFrame {
227 /// Width in pixels.
228 pub width: u32,
229 /// Height in pixels.
230 pub height: u32,
231 /// Presentation time in the stream's time base.
232 pub pts: Option<i64>,
233 /// One plane per component group; packed formats have exactly one.
234 pub planes: Vec<VideoPlane>,
235}
236
237/// One plane of a [`VideoFrame`].
238#[derive(Clone, Debug, Default, PartialEq, Eq)]
239pub struct VideoPlane {
240 /// Bytes between the starts of two rows.
241 pub stride: usize,
242 /// The plane's bytes.
243 pub data: Vec<u8>,
244}
245
246/// One decoded block of audio.
247#[derive(Clone, Debug, Default, PartialEq, Eq)]
248pub struct AudioFrame {
249 /// Frames per channel in this block.
250 pub samples: u32,
251 /// Presentation time in the stream's time base.
252 pub pts: Option<i64>,
253 /// Interleaved (one entry) or planar (one entry per channel) bytes.
254 pub data: Vec<Vec<u8>>,
255}
256
257/// What a decoder hands back.
258#[derive(Clone, Debug, PartialEq, Eq)]
259pub enum Frame {
260 /// A picture.
261 Video(VideoFrame),
262 /// An audio block.
263 Audio(AudioFrame),
264}
265
266impl From<ec_core::Frame> for Frame {
267 fn from(frame: ec_core::Frame) -> Frame {
268 match frame {
269 ec_core::Frame::Video(video) => Frame::Video(VideoFrame {
270 width: video.width,
271 height: video.height,
272 pts: video.pts.map(|t| t.ticks),
273 planes: video
274 .planes
275 .into_iter()
276 .map(|plane| VideoPlane {
277 stride: plane.stride,
278 data: plane.data.to_vec(),
279 })
280 .collect(),
281 }),
282 ec_core::Frame::Audio(audio) => Frame::Audio(AudioFrame {
283 samples: audio.samples as u32,
284 pts: audio.pts.map(|t| t.ticks),
285 data: audio.data.iter().map(|buf| buf.to_vec()).collect(),
286 }),
287 }
288 }
289}
290
291/// A decoder: packets in, frames out.
292pub trait Decoder: Send {
293 /// The codec this decodes.
294 fn codec_id(&self) -> &CodecId;
295
296 /// Feed one packet.
297 fn send_packet(&mut self, packet: &Packet) -> Result<()>;
298
299 /// Take one frame, or [`Error::NeedMore`] when the decoder wants another
300 /// packet first.
301 fn receive_frame(&mut self) -> Result<Frame>;
302}
303
304/// A container writer.
305pub trait Muxer: Send {
306 /// The format's short name.
307 fn format_name(&self) -> &str;
308
309 /// Write whatever precedes the first packet.
310 fn write_header(&mut self) -> Result<()>;
311
312 /// Write one packet.
313 fn write_packet(&mut self, packet: &Packet) -> Result<()>;
314
315 /// Write whatever follows the last one.
316 fn write_trailer(&mut self) -> Result<()>;
317}
318
319/// How a codec crate hands out decoders.
320pub type DecoderFactory = fn(&CodecParameters) -> Result<Box<dyn Decoder>>;
321
322/// One codec's registration.
323#[derive(Clone)]
324pub struct CodecInfo {
325 /// The id this claims.
326 pub id: CodecId,
327 /// How to build a decoder for it.
328 pub decoder_factory: Option<DecoderFactory>,
329}
330
331impl CodecInfo {
332 /// An empty registration for `id`.
333 pub fn new(id: CodecId) -> CodecInfo {
334 CodecInfo {
335 id,
336 decoder_factory: None,
337 }
338 }
339
340 /// The same registration, with a decoder.
341 pub fn decoder(mut self, factory: DecoderFactory) -> CodecInfo {
342 self.decoder_factory = Some(factory);
343 self
344 }
345}
346
347/// The codecs a caller has registered, in registration order per id.
348///
349/// The replica builds one of these per AC-3 segment, registers that crate's
350/// codecs into it and asks for the first decoder that claims the parameters.
351#[derive(Clone, Default)]
352pub struct CodecRegistry {
353 by_id: HashMap<CodecId, Vec<CodecInfo>>,
354}
355
356impl CodecRegistry {
357 /// An empty registry.
358 pub fn new() -> CodecRegistry {
359 CodecRegistry::default()
360 }
361
362 /// Add one codec.
363 pub fn register(&mut self, info: CodecInfo) {
364 self.by_id.entry(info.id.clone()).or_default().push(info);
365 }
366
367 /// True when something registered can decode `id`.
368 pub fn has_decoder(&self, id: &CodecId) -> bool {
369 self.by_id
370 .get(id)
371 .is_some_and(|infos| infos.iter().any(|i| i.decoder_factory.is_some()))
372 }
373
374 /// A decoder from the first registration that offers one.
375 pub fn first_decoder(&self, params: &CodecParameters) -> Result<Box<dyn Decoder>> {
376 let factory = self
377 .by_id
378 .get(&params.codec_id)
379 .and_then(|infos| infos.iter().find_map(|i| i.decoder_factory))
380 .ok_or_else(|| Error::CodecNotFound(params.codec_id.0.clone()))?;
381 factory(params)
382 }
383}
384
385/// A [`Decoder`] over one of the family's own, converting the frames on the way
386/// out. Codec shims are two lines with this: build the `ec_core` decoder, wrap.
387pub struct EcDecoder {
388 id: CodecId,
389 inner: Box<dyn ec_core::Decoder>,
390}
391
392impl EcDecoder {
393 /// Wrap `inner`, which decodes the codec named `id`.
394 pub fn new(id: CodecId, inner: Box<dyn ec_core::Decoder>) -> EcDecoder {
395 EcDecoder { id, inner }
396 }
397}
398
399impl Decoder for EcDecoder {
400 fn codec_id(&self) -> &CodecId {
401 &self.id
402 }
403
404 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
405 Ok(self.inner.send_packet(packet)?)
406 }
407
408 fn receive_frame(&mut self) -> Result<Frame> {
409 Ok(self.inner.receive_frame()?.into())
410 }
411}
412
413#[cfg(test)]
414mod tests {
415 use super::*;
416
417 /// A decoder that answers one frame per packet, for the registry test.
418 struct Stub(CodecId);
419
420 impl Decoder for Stub {
421 fn codec_id(&self) -> &CodecId {
422 &self.0
423 }
424
425 fn send_packet(&mut self, _packet: &Packet) -> Result<()> {
426 Ok(())
427 }
428
429 fn receive_frame(&mut self) -> Result<Frame> {
430 Err(Error::NeedMore)
431 }
432 }
433
434 fn stub(params: &CodecParameters) -> Result<Box<dyn Decoder>> {
435 Ok(Box::new(Stub(params.codec_id.clone())))
436 }
437
438 #[test]
439 fn the_registry_hands_back_what_was_registered_and_names_what_was_not() {
440 let mut registry = CodecRegistry::new();
441 registry.register(CodecInfo::new(CodecId::new("ac3")).decoder(stub));
442 let params = CodecParameters::audio(CodecId::new("ac3"));
443 let mut decoder = registry.first_decoder(&params).unwrap();
444 assert_eq!(decoder.codec_id().as_str(), "ac3");
445 assert!(matches!(decoder.receive_frame(), Err(Error::NeedMore)));
446 assert!(registry.has_decoder(&CodecId::new("ac3")));
447
448 let missing = CodecParameters::audio(CodecId::new("truehd"));
449 assert!(matches!(
450 registry.first_decoder(&missing),
451 Err(Error::CodecNotFound(id)) if id == "truehd"
452 ));
453 }
454
455 #[test]
456 fn frames_and_errors_cross_the_boundary_intact() {
457 let plane = ec_core::Plane::new(vec![1u8, 2, 3, 4], 4);
458 let video =
459 ec_core::VideoFrame::try_new(ec_core::PixelFormat::Rgba8, 1, 1, vec![plane]).unwrap();
460 let Frame::Video(frame) = Frame::from(ec_core::Frame::Video(video)) else {
461 panic!("a video frame stays a video frame");
462 };
463 assert_eq!((frame.width, frame.height), (1, 1));
464 assert_eq!(frame.planes[0].data, vec![1, 2, 3, 4]);
465 assert_eq!(frame.planes[0].stride, 4);
466
467 // The one error the replica matches on by name.
468 assert!(matches!(
469 Error::from(ec_core::Error::NeedMore),
470 Error::NeedMore
471 ));
472 assert_eq!(
473 Error::from(ec_core::Error::corrupt("torn")).to_string(),
474 "invalid data: torn"
475 );
476 }
477
478 #[test]
479 fn a_packet_is_written_the_way_the_replica_writes_one() {
480 let packet = Packet::new(0, TimeBase::new(1, 90_000), vec![0u8; 8]);
481 assert_eq!(packet.data.len(), 8);
482 assert_eq!(packet.time_base, TimeBase::new(1, 90_000));
483 }
484}