forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust375.8 MiB98eeb6cTahinli3 months ago90 commits

lib.rs638 lines, 19.3 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/// How a codec is named by a container, so a demuxer can map what it read to a
149/// registration.
150#[derive(Clone, Debug, PartialEq, Eq, Hash)]
151pub enum CodecTag {
152 /// A four-character code, as mp4 sample entries and RIFF write it.
153 FourCc([u8; 4]),
154 /// An MPEG-4 `ObjectTypeIndication`.
155 Mp4ObjectType(u8),
156 /// A Matroska `CodecID` string.
157 Matroska(String),
158}
159
160impl CodecTag {
161 /// The four-character code `code`.
162 pub fn fourcc(code: &[u8; 4]) -> CodecTag {
163 CodecTag::FourCc(*code)
164 }
165
166 /// The MPEG-4 object type `oti`.
167 pub fn mp4_object_type(oti: u8) -> CodecTag {
168 CodecTag::Mp4ObjectType(oti)
169 }
170
171 /// The Matroska `CodecID` `id`.
172 pub fn matroska(id: impl Into<String>) -> CodecTag {
173 CodecTag::Matroska(id.into())
174 }
175}
176
177/// How samples are laid out in a video frame. Only the format the family's own
178/// encoders take and hand out is named; a caller that needs another adds it.
179#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
180pub enum PixelFormat {
181 /// Planar 4:2:0 8-bit.
182 #[default]
183 Yuv420P,
184}
185
186/// A codec's string-keyed knobs, parsed by whichever codec declares them.
187#[derive(Clone, Debug, Default, PartialEq, Eq)]
188pub struct CodecOptions(HashMap<String, String>);
189
190impl CodecOptions {
191 /// The value set for `key`, if any.
192 pub fn get(&self, key: &str) -> Option<&str> {
193 self.0.get(key).map(String::as_str)
194 }
195
196 /// Set `key` to `value`, replacing what was there.
197 pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
198 self.0.insert(key.into(), value.into());
199 }
200}
201
202/// What kind of stream a set of parameters describes.
203#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
204pub enum MediaType {
205 /// Audio samples.
206 Audio,
207 /// Video pictures.
208 Video,
209 /// Timed text or subtitle bitmaps.
210 Subtitle,
211 /// Opaque payload.
212 Data,
213 /// Not yet determined.
214 #[default]
215 Unknown,
216}
217
218/// Everything a decoder is told before its first packet.
219#[derive(Clone, Debug, Default, PartialEq, Eq)]
220pub struct CodecParameters {
221 /// Which codec.
222 pub codec_id: CodecId,
223 /// Which kind of stream.
224 pub media_type: MediaType,
225 /// Audio sample rate.
226 pub sample_rate: Option<u32>,
227 /// Audio channel count — the replica asks for `Some(2)` to get a downmix.
228 pub channels: Option<u16>,
229 /// Coded width.
230 pub width: Option<u32>,
231 /// Coded height.
232 pub height: Option<u32>,
233 /// How a video stream's samples are laid out.
234 pub pixel_format: Option<PixelFormat>,
235 /// Codec setup bytes.
236 pub extradata: Vec<u8>,
237 /// Codec-specific knobs, read by whichever codec declares them.
238 pub options: CodecOptions,
239}
240
241impl CodecParameters {
242 /// Audio parameters for `codec_id`.
243 pub fn audio(codec_id: CodecId) -> CodecParameters {
244 CodecParameters {
245 codec_id,
246 media_type: MediaType::Audio,
247 ..CodecParameters::default()
248 }
249 }
250
251 /// Video parameters for `codec_id`.
252 pub fn video(codec_id: CodecId) -> CodecParameters {
253 CodecParameters {
254 codec_id,
255 media_type: MediaType::Video,
256 ..CodecParameters::default()
257 }
258 }
259
260 /// Subtitle parameters for `codec_id`.
261 pub fn subtitle(codec_id: CodecId) -> CodecParameters {
262 CodecParameters {
263 codec_id,
264 media_type: MediaType::Subtitle,
265 ..CodecParameters::default()
266 }
267 }
268
269 /// Data-stream parameters for `codec_id`.
270 pub fn data(codec_id: CodecId) -> CodecParameters {
271 CodecParameters {
272 codec_id,
273 media_type: MediaType::Data,
274 ..CodecParameters::default()
275 }
276 }
277}
278
279/// One stream of a container, as a muxer is told about it.
280#[derive(Clone, Debug, PartialEq, Eq)]
281pub struct StreamInfo {
282 /// Index the stream's packets carry.
283 pub index: u32,
284 /// The unit its timestamps are in.
285 pub time_base: TimeBase,
286 /// Duration in `time_base` ticks.
287 pub duration: Option<i64>,
288 /// First timestamp in `time_base` ticks.
289 pub start_time: Option<i64>,
290 /// What is in it.
291 pub params: CodecParameters,
292}
293
294/// One decoded picture.
295///
296/// No dimensions: the incumbent states them on the stream's
297/// [`CodecParameters`] and puts only the row stride on the plane, and a codec
298/// crate outside this workspace writes the literal (`oxideav-h265`'s decoder
299/// does), so the field list is the incumbent's and not ours to improve.
300#[derive(Clone, Debug, Default, PartialEq, Eq)]
301pub struct VideoFrame {
302 /// Presentation time in the stream's time base.
303 pub pts: Option<i64>,
304 /// One plane per component group; packed formats have exactly one.
305 pub planes: Vec<VideoPlane>,
306}
307
308/// One plane of a [`VideoFrame`].
309#[derive(Clone, Debug, Default, PartialEq, Eq)]
310pub struct VideoPlane {
311 /// Bytes between the starts of two rows.
312 pub stride: usize,
313 /// The plane's bytes.
314 pub data: Vec<u8>,
315}
316
317/// One decoded block of audio.
318#[derive(Clone, Debug, Default, PartialEq, Eq)]
319pub struct AudioFrame {
320 /// Frames per channel in this block.
321 pub samples: u32,
322 /// Presentation time in the stream's time base.
323 pub pts: Option<i64>,
324 /// Interleaved (one entry) or planar (one entry per channel) bytes.
325 pub data: Vec<Vec<u8>>,
326}
327
328/// What a decoder hands back.
329#[derive(Clone, Debug, PartialEq, Eq)]
330pub enum Frame {
331 /// A picture.
332 Video(VideoFrame),
333 /// An audio block.
334 Audio(AudioFrame),
335}
336
337impl From<ec_core::Frame> for Frame {
338 fn from(frame: ec_core::Frame) -> Frame {
339 match frame {
340 ec_core::Frame::Video(video) => Frame::Video(VideoFrame {
341 pts: video.pts.map(|t| t.ticks),
342 planes: video
343 .planes
344 .into_iter()
345 .map(|plane| VideoPlane {
346 stride: plane.stride,
347 data: plane.data.to_vec(),
348 })
349 .collect(),
350 }),
351 ec_core::Frame::Audio(audio) => Frame::Audio(AudioFrame {
352 samples: audio.samples as u32,
353 pts: audio.pts.map(|t| t.ticks),
354 data: audio.data.iter().map(|buf| buf.to_vec()).collect(),
355 }),
356 }
357 }
358}
359
360/// A decoder: packets in, frames out.
361pub trait Decoder: Send {
362 /// The codec this decodes.
363 fn codec_id(&self) -> &CodecId;
364
365 /// Feed one packet.
366 fn send_packet(&mut self, packet: &Packet) -> Result<()>;
367
368 /// Take one frame, or [`Error::NeedMore`] when the decoder wants another
369 /// packet first.
370 fn receive_frame(&mut self) -> Result<Frame>;
371
372 /// Signal end of input, so whatever is held back becomes available through
373 /// [`receive_frame`](Decoder::receive_frame) and then [`Error::Eof`].
374 ///
375 /// The default is for a decoder that holds nothing back — one packet in,
376 /// one frame out, which is what the AC-3 path is.
377 fn flush(&mut self) -> Result<()> {
378 Ok(())
379 }
380}
381
382/// An encoder: frames in, packets out.
383pub trait Encoder: Send {
384 /// The codec this produces.
385 fn codec_id(&self) -> &CodecId;
386
387 /// Parameters describing the stream it produces, for the muxer.
388 fn output_params(&self) -> &CodecParameters;
389
390 /// Feed one uncompressed frame.
391 fn send_frame(&mut self, frame: &Frame) -> Result<()>;
392
393 /// Take one packet, or [`Error::NeedMore`] when the encoder wants another
394 /// frame first.
395 fn receive_packet(&mut self) -> Result<Packet>;
396
397 /// Signal end of input, so the lookahead drains into
398 /// [`receive_packet`](Encoder::receive_packet).
399 fn flush(&mut self) -> Result<()>;
400}
401
402/// A container writer.
403pub trait Muxer: Send {
404 /// The format's short name.
405 fn format_name(&self) -> &str;
406
407 /// Write whatever precedes the first packet.
408 fn write_header(&mut self) -> Result<()>;
409
410 /// Write one packet.
411 fn write_packet(&mut self, packet: &Packet) -> Result<()>;
412
413 /// Write whatever follows the last one.
414 fn write_trailer(&mut self) -> Result<()>;
415}
416
417/// How a codec crate hands out decoders.
418pub type DecoderFactory = fn(&CodecParameters) -> Result<Box<dyn Decoder>>;
419
420/// How a codec crate hands out encoders.
421pub type EncoderFactory = fn(&CodecParameters) -> Result<Box<dyn Encoder>>;
422
423/// One codec's registration.
424#[derive(Clone)]
425pub struct CodecInfo {
426 /// The id this claims.
427 pub id: CodecId,
428 /// How to build a decoder for it.
429 pub decoder_factory: Option<DecoderFactory>,
430 /// How to build an encoder for it.
431 pub encoder_factory: Option<EncoderFactory>,
432 /// The container-level names that mean this codec.
433 pub tags: Vec<CodecTag>,
434}
435
436impl CodecInfo {
437 /// An empty registration for `id`.
438 pub fn new(id: CodecId) -> CodecInfo {
439 CodecInfo {
440 id,
441 decoder_factory: None,
442 encoder_factory: None,
443 tags: Vec::new(),
444 }
445 }
446
447 /// The same registration, with a decoder.
448 pub fn decoder(mut self, factory: DecoderFactory) -> CodecInfo {
449 self.decoder_factory = Some(factory);
450 self
451 }
452
453 /// The same registration, with an encoder.
454 pub fn encoder(mut self, factory: EncoderFactory) -> CodecInfo {
455 self.encoder_factory = Some(factory);
456 self
457 }
458
459 /// The same registration, claiming `tags` on top of whatever it claimed.
460 pub fn tags(mut self, tags: impl IntoIterator<Item = CodecTag>) -> CodecInfo {
461 self.tags.extend(tags);
462 self
463 }
464}
465
466/// The codecs a caller has registered, in registration order per id.
467///
468/// The replica builds one of these per AC-3 segment, registers that crate's
469/// codecs into it and asks for the first decoder that claims the parameters.
470#[derive(Clone, Default)]
471pub struct CodecRegistry {
472 by_id: HashMap<CodecId, Vec<CodecInfo>>,
473}
474
475impl CodecRegistry {
476 /// An empty registry.
477 pub fn new() -> CodecRegistry {
478 CodecRegistry::default()
479 }
480
481 /// Add one codec.
482 pub fn register(&mut self, info: CodecInfo) {
483 self.by_id.entry(info.id.clone()).or_default().push(info);
484 }
485
486 /// True when something registered can decode `id`.
487 pub fn has_decoder(&self, id: &CodecId) -> bool {
488 self.by_id
489 .get(id)
490 .is_some_and(|infos| infos.iter().any(|i| i.decoder_factory.is_some()))
491 }
492
493 /// A decoder from the first registration that offers one.
494 pub fn first_decoder(&self, params: &CodecParameters) -> Result<Box<dyn Decoder>> {
495 let factory = self
496 .by_id
497 .get(&params.codec_id)
498 .and_then(|infos| infos.iter().find_map(|i| i.decoder_factory))
499 .ok_or_else(|| Error::CodecNotFound(params.codec_id.0.clone()))?;
500 factory(params)
501 }
502}
503
504/// What a codec crate is handed to register itself into.
505///
506/// The incumbent's context carries four sub-registries; this one carries the
507/// codecs, because a container, source or filter crate registering into the
508/// replica's build does not exist.
509#[derive(Clone, Default)]
510pub struct RuntimeContext {
511 /// Decoder and encoder factories, by codec id.
512 pub codecs: CodecRegistry,
513}
514
515impl RuntimeContext {
516 /// An empty context.
517 pub fn new() -> RuntimeContext {
518 RuntimeContext::default()
519 }
520}
521
522/// Declare a codec crate's registration entry point, as the family's crates
523/// spell it: `oxideav_core::register!("h265", register);`.
524///
525/// The name is carried for documentation only, exactly as the incumbent does —
526/// what the generated `__oxideav_entry` runs is `$func`.
527#[macro_export]
528macro_rules! register {
529 ($name:literal, $func:path) => {
530 /// This crate's registration entry point, generated by
531 /// [`oxideav_core::register!`].
532 #[doc(hidden)]
533 pub fn __oxideav_entry(ctx: &mut $crate::RuntimeContext) {
534 let _ = $name;
535 $func(ctx);
536 }
537 };
538}
539
540/// A [`Decoder`] over one of the family's own, converting the frames on the way
541/// out. Codec shims are two lines with this: build the `ec_core` decoder, wrap.
542pub struct EcDecoder {
543 id: CodecId,
544 inner: Box<dyn ec_core::Decoder>,
545}
546
547impl EcDecoder {
548 /// Wrap `inner`, which decodes the codec named `id`.
549 pub fn new(id: CodecId, inner: Box<dyn ec_core::Decoder>) -> EcDecoder {
550 EcDecoder { id, inner }
551 }
552}
553
554impl Decoder for EcDecoder {
555 fn codec_id(&self) -> &CodecId {
556 &self.id
557 }
558
559 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
560 Ok(self.inner.send_packet(packet)?)
561 }
562
563 fn receive_frame(&mut self) -> Result<Frame> {
564 Ok(self.inner.receive_frame()?.into())
565 }
566}
567
568#[cfg(test)]
569mod tests {
570 use super::*;
571
572 /// A decoder that answers one frame per packet, for the registry test.
573 struct Stub(CodecId);
574
575 impl Decoder for Stub {
576 fn codec_id(&self) -> &CodecId {
577 &self.0
578 }
579
580 fn send_packet(&mut self, _packet: &Packet) -> Result<()> {
581 Ok(())
582 }
583
584 fn receive_frame(&mut self) -> Result<Frame> {
585 Err(Error::NeedMore)
586 }
587 }
588
589 fn stub(params: &CodecParameters) -> Result<Box<dyn Decoder>> {
590 Ok(Box::new(Stub(params.codec_id.clone())))
591 }
592
593 #[test]
594 fn the_registry_hands_back_what_was_registered_and_names_what_was_not() {
595 let mut registry = CodecRegistry::new();
596 registry.register(CodecInfo::new(CodecId::new("ac3")).decoder(stub));
597 let params = CodecParameters::audio(CodecId::new("ac3"));
598 let mut decoder = registry.first_decoder(&params).unwrap();
599 assert_eq!(decoder.codec_id().as_str(), "ac3");
600 assert!(matches!(decoder.receive_frame(), Err(Error::NeedMore)));
601 assert!(registry.has_decoder(&CodecId::new("ac3")));
602
603 let missing = CodecParameters::audio(CodecId::new("truehd"));
604 assert!(matches!(
605 registry.first_decoder(&missing),
606 Err(Error::CodecNotFound(id)) if id == "truehd"
607 ));
608 }
609
610 #[test]
611 fn frames_and_errors_cross_the_boundary_intact() {
612 let plane = ec_core::Plane::new(vec![1u8, 2, 3, 4], 4);
613 let video =
614 ec_core::VideoFrame::try_new(ec_core::PixelFormat::Rgba8, 1, 1, vec![plane]).unwrap();
615 let Frame::Video(frame) = Frame::from(ec_core::Frame::Video(video)) else {
616 panic!("a video frame stays a video frame");
617 };
618 assert_eq!(frame.planes[0].data, vec![1, 2, 3, 4]);
619 assert_eq!(frame.planes[0].stride, 4);
620
621 // The one error the replica matches on by name.
622 assert!(matches!(
623 Error::from(ec_core::Error::NeedMore),
624 Error::NeedMore
625 ));
626 assert_eq!(
627 Error::from(ec_core::Error::corrupt("torn")).to_string(),
628 "invalid data: torn"
629 );
630 }
631
632 #[test]
633 fn a_packet_is_written_the_way_the_replica_writes_one() {
634 let packet = Packet::new(0, TimeBase::new(1, 90_000), vec![0u8; 8]);
635 assert_eq!(packet.data.len(), 8);
636 assert_eq!(packet.time_base, TimeBase::new(1, 90_000));
637 }
638}