forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust376.5 MiB30d372eTahinli3 months ago42 commits

registry.rs437 lines, 14.3 KiBHistoryRawDownload
1//! Codec identities, stream descriptions and the four trait contracts every
2//! container and codec crate in the family implements.
3
4use crate::color::ContentLight;
5use crate::error::Result;
6use crate::frame::{ChannelLayout, ColorInfo, Frame, PixelFormat, SampleFormat};
7use crate::packet::{Buf, Packet};
8use crate::timebase::{TimeBase, Timestamp};
9
10/// Which kind of stream something belongs to.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12pub enum MediaType {
13 /// Pictures.
14 Video,
15 /// Sound.
16 Audio,
17 /// Timed text or bitmap overlays.
18 Subtitle,
19}
20
21/// Every codec the family carries.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
23#[non_exhaustive]
24pub enum CodecId {
25 /// ITU-T H.264 / MPEG-4 AVC.
26 H264,
27 /// ITU-T H.265 / MPEG-H HEVC.
28 H265,
29 /// Google VP8 (also the lossy half of WebP).
30 Vp8,
31 /// Google VP9.
32 Vp9,
33 /// AOMedia AV1.
34 Av1,
35 /// MPEG-4 AAC (LC and friends).
36 Aac,
37 /// Dolby AC-3.
38 Ac3,
39 /// Dolby Digital Plus (E-AC-3).
40 EAc3,
41 /// Apple Lossless.
42 Alac,
43 /// Xiph FLAC.
44 Flac,
45 /// MPEG-1/2 Layer III.
46 Mp3,
47 /// Xiph Opus.
48 Opus,
49 /// Xiph Vorbis.
50 Vorbis,
51 /// Unsigned 8-bit PCM.
52 PcmU8,
53 /// Signed 16-bit little-endian PCM.
54 PcmS16Le,
55 /// Signed 16-bit big-endian PCM.
56 PcmS16Be,
57 /// Signed 24-bit little-endian packed PCM.
58 PcmS24Le,
59 /// Signed 32-bit little-endian PCM.
60 PcmS32Le,
61 /// 32-bit float little-endian PCM.
62 PcmF32Le,
63 /// SubRip text.
64 Srt,
65 /// WebVTT text.
66 WebVtt,
67 /// Advanced SubStation Alpha (and SSA).
68 Ass,
69 /// Blu-ray Presentation Graphic Stream bitmaps.
70 Pgs,
71 /// MPEG-4 timed text (3GPP `tx3g`).
72 Tx3g,
73}
74
75impl CodecId {
76 /// The media type this codec produces.
77 pub fn media_type(&self) -> MediaType {
78 use CodecId::*;
79 match self {
80 H264 | H265 | Vp8 | Vp9 | Av1 => MediaType::Video,
81 Aac | Ac3 | EAc3 | Alac | Flac | Mp3 | Opus | Vorbis | PcmU8 | PcmS16Le | PcmS16Be
82 | PcmS24Le | PcmS32Le | PcmF32Le => MediaType::Audio,
83 Srt | WebVtt | Ass | Pgs | Tx3g => MediaType::Subtitle,
84 }
85 }
86
87 /// Short lowercase name, stable enough for logs and capability tables.
88 pub fn name(&self) -> &'static str {
89 use CodecId::*;
90 match self {
91 H264 => "h264",
92 H265 => "h265",
93 Vp8 => "vp8",
94 Vp9 => "vp9",
95 Av1 => "av1",
96 Aac => "aac",
97 Ac3 => "ac3",
98 EAc3 => "eac3",
99 Alac => "alac",
100 Flac => "flac",
101 Mp3 => "mp3",
102 Opus => "opus",
103 Vorbis => "vorbis",
104 PcmU8 => "pcm_u8",
105 PcmS16Le => "pcm_s16le",
106 PcmS16Be => "pcm_s16be",
107 PcmS24Le => "pcm_s24le",
108 PcmS32Le => "pcm_s32le",
109 PcmF32Le => "pcm_f32le",
110 Srt => "srt",
111 WebVtt => "webvtt",
112 Ass => "ass",
113 Pgs => "pgs",
114 Tx3g => "tx3g",
115 }
116 }
117}
118
119/// Video half of [`CodecParameters`].
120#[derive(Debug, Clone, PartialEq, Default)]
121pub struct VideoParameters {
122 /// Coded width in pixels.
123 pub width: u32,
124 /// Coded height in pixels.
125 pub height: u32,
126 /// Decoded pixel layout, when the container or headers state one.
127 pub format: Option<PixelFormat>,
128 /// Frame rate *as a rate*: `num/den` is frames per second, so NTSC film is
129 /// `24000/1001`. Invert it with [`TimeBase::inverse`] for a tick duration.
130 pub frame_rate: Option<TimeBase>,
131 /// Sample aspect ratio (`num/den`), when not square.
132 pub sample_aspect_ratio: Option<TimeBase>,
133 /// H.273 colour description.
134 pub color: ColorInfo,
135 /// How bright the grade says this stream gets: MaxCLL/MaxFALL and the
136 /// mastering display, when the container or an HDR SEI stated them. All
137 /// [`None`] for SDR, which is what a tone map falls back on.
138 pub light: ContentLight,
139}
140
141/// Audio half of [`CodecParameters`].
142#[derive(Debug, Clone, PartialEq, Eq)]
143pub struct AudioParameters {
144 /// Sample rate in Hz.
145 pub sample_rate: u32,
146 /// Channel count, order and meaning.
147 pub layout: ChannelLayout,
148 /// Decoded sample format, when known before the first frame.
149 pub format: Option<SampleFormat>,
150 /// Coded bit depth, when the codec has one (FLAC 24, ALAC 16/24).
151 pub bits_per_sample: Option<u32>,
152}
153
154impl Default for AudioParameters {
155 fn default() -> Self {
156 AudioParameters {
157 sample_rate: 0,
158 layout: ChannelLayout::Stereo,
159 format: None,
160 bits_per_sample: None,
161 }
162 }
163}
164
165/// Per-media-type parameters.
166#[derive(Debug, Clone, PartialEq)]
167pub enum MediaParameters {
168 /// Video stream parameters.
169 Video(VideoParameters),
170 /// Audio stream parameters.
171 Audio(AudioParameters),
172 /// Subtitle streams carry no dimensions; their setup lives in `extradata`
173 /// (the ASS header, the PGS palette, ...).
174 Subtitle,
175}
176
177/// Everything a decoder needs before it sees its first packet.
178#[derive(Debug, Clone, PartialEq)]
179pub struct CodecParameters {
180 /// Which codec.
181 pub codec: CodecId,
182 /// Codec-defined setup bytes: avcC, hvcC, av1C, AudioSpecificConfig, the
183 /// FLAC STREAMINFO block, the Vorbis header triplet, and so on.
184 pub extradata: Option<Buf>,
185 /// Media-type-specific parameters.
186 pub media: MediaParameters,
187}
188
189impl CodecParameters {
190 /// Parameters for `codec` with defaults for its media type and no extradata.
191 pub fn new(codec: CodecId) -> CodecParameters {
192 let media = match codec.media_type() {
193 MediaType::Video => MediaParameters::Video(VideoParameters::default()),
194 MediaType::Audio => MediaParameters::Audio(AudioParameters::default()),
195 MediaType::Subtitle => MediaParameters::Subtitle,
196 };
197 CodecParameters {
198 codec,
199 extradata: None,
200 media,
201 }
202 }
203
204 /// Video parameters, when this is a video stream.
205 pub fn video(&self) -> Option<&VideoParameters> {
206 match &self.media {
207 MediaParameters::Video(v) => Some(v),
208 _ => None,
209 }
210 }
211
212 /// Audio parameters, when this is an audio stream.
213 pub fn audio(&self) -> Option<&AudioParameters> {
214 match &self.media {
215 MediaParameters::Audio(a) => Some(a),
216 _ => None,
217 }
218 }
219}
220
221/// One stream of a container, as a demuxer reports it.
222#[derive(Debug, Clone, PartialEq)]
223pub struct StreamInfo {
224 /// Index matching [`Packet::stream`].
225 pub index: u32,
226 /// Base of every timestamp on this stream's packets.
227 pub time_base: TimeBase,
228 /// Codec and setup data.
229 pub params: CodecParameters,
230 /// First presentation timestamp, in `time_base` ticks, when known.
231 pub start_time: Option<i64>,
232 /// Duration in `time_base` ticks, when the container states one.
233 pub duration: Option<i64>,
234 /// ISO 639-2 language tag, when the container carries one.
235 pub language: Option<String>,
236}
237
238impl StreamInfo {
239 /// A stream with no timing hints and no language.
240 pub fn new(index: u32, time_base: TimeBase, params: CodecParameters) -> StreamInfo {
241 StreamInfo {
242 index,
243 time_base,
244 params,
245 start_time: None,
246 duration: None,
247 language: None,
248 }
249 }
250}
251
252/// Where a seek is allowed to land relative to the requested instant.
253#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
254pub enum SeekMode {
255 /// Nearest random access point at or before the target. The default: it is
256 /// the only mode that lets a decoder reach the target frame exactly, by
257 /// decoding forward and discarding.
258 #[default]
259 SyncBefore,
260 /// Nearest random access point at or after the target.
261 SyncAfter,
262 /// Exact instant, whether or not a random access point sits there; the
263 /// caller handles the pre-roll.
264 Exact,
265}
266
267/// A container reader: streams in, packets out.
268pub trait Demuxer: Send {
269 /// The streams found while opening the container.
270 fn streams(&self) -> &[StreamInfo];
271
272 /// Next packet in storage order, or [`crate::Error::Eof`] at the end.
273 fn next_packet(&mut self) -> Result<Packet>;
274
275 /// Position so that reading resumes near `to` on `stream`.
276 ///
277 /// `to` carries its own [`TimeBase`], so callers never have to know the
278 /// stream's base to seek by wall-clock instant.
279 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()>;
280}
281
282/// A container writer: streams declared, then packets, then a finish.
283pub trait Muxer: Send {
284 /// Declare a stream; returns the index that its packets must carry.
285 ///
286 /// All streams are declared before the first [`Muxer::write_packet`].
287 fn add_stream(&mut self, info: StreamInfo) -> Result<u32>;
288
289 /// Write one packet. Its `stream` must be an index from
290 /// [`Muxer::add_stream`] and its timestamps are rescaled by the muxer.
291 fn write_packet(&mut self, packet: &Packet) -> Result<()>;
292
293 /// Flush indices and trailers. Takes `&mut self` rather than `self` so a
294 /// muxer stays usable behind `Box<dyn Muxer>`.
295 fn finish(&mut self) -> Result<()>;
296}
297
298/// A decoder: packets in, frames out.
299///
300/// Push/pull rather than `decode(&Packet) -> Vec<Frame>` because the mapping is
301/// genuinely not one to one — a parameter-set packet yields nothing, a
302/// reordering decoder yields nothing until its DPB fills, an audio packet can
303/// yield several blocks — and because end of stream has to be expressible:
304/// [`Decoder::flush`] then drains what reorder delay is still holding. The
305/// `Vec` shape would allocate per packet and still need a second entry point
306/// for the drain.
307pub trait Decoder: Send {
308 /// The parameters this decoder was configured with, updated in place when
309 /// in-band headers change them.
310 fn codec_parameters(&self) -> &CodecParameters;
311
312 /// Submit one packet. Call [`Decoder::receive_frame`] until it answers
313 /// [`crate::Error::NeedMore`] before submitting the next.
314 fn send_packet(&mut self, packet: &Packet) -> Result<()>;
315
316 /// Take one decoded frame; [`crate::Error::NeedMore`] when none is ready,
317 /// [`crate::Error::Eof`] once a flushed decoder is drained.
318 fn receive_frame(&mut self) -> Result<Frame>;
319
320 /// Signal end of stream: after this, `receive_frame` returns the delayed
321 /// frames and then [`crate::Error::Eof`].
322 fn flush(&mut self) -> Result<()>;
323
324 /// Drop all buffered state after a seek. Timestamps and references from
325 /// before the seek are discarded.
326 fn reset(&mut self);
327}
328
329/// An encoder: frames in, packets out — the mirror of [`Decoder`].
330pub trait Encoder: Send {
331 /// Parameters describing the encoder's output, including the `extradata`
332 /// a muxer needs. For codecs whose setup data is derived while encoding
333 /// (AAC ASC, avcC), this is final after the first
334 /// [`Encoder::receive_packet`].
335 fn codec_parameters(&self) -> &CodecParameters;
336
337 /// Submit one frame.
338 fn send_frame(&mut self, frame: &Frame) -> Result<()>;
339
340 /// Take one encoded packet; [`crate::Error::NeedMore`] when none is ready,
341 /// [`crate::Error::Eof`] once a flushed encoder is drained.
342 fn receive_packet(&mut self) -> Result<Packet>;
343
344 /// Signal end of input and drain the lookahead.
345 fn flush(&mut self) -> Result<()>;
346}
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351
352 #[test]
353 fn every_codec_id_has_a_media_type_and_name() {
354 // The set the family must express, spelled out so a later crate cannot
355 // quietly lose one (subtitle packets included: they are Packets, not
356 // Frames).
357 let all = [
358 CodecId::H264,
359 CodecId::H265,
360 CodecId::Vp8,
361 CodecId::Vp9,
362 CodecId::Av1,
363 CodecId::Aac,
364 CodecId::Ac3,
365 CodecId::EAc3,
366 CodecId::Alac,
367 CodecId::Flac,
368 CodecId::Mp3,
369 CodecId::Opus,
370 CodecId::Vorbis,
371 CodecId::PcmU8,
372 CodecId::PcmS16Le,
373 CodecId::PcmS16Be,
374 CodecId::PcmS24Le,
375 CodecId::PcmS32Le,
376 CodecId::PcmF32Le,
377 CodecId::Srt,
378 CodecId::WebVtt,
379 CodecId::Ass,
380 CodecId::Pgs,
381 CodecId::Tx3g,
382 ];
383 assert_eq!(all.len(), 24);
384 let mut names: Vec<&str> = all.iter().map(|c| c.name()).collect();
385 names.sort_unstable();
386 names.dedup();
387 assert_eq!(names.len(), all.len(), "codec names must be unique");
388 assert_eq!(CodecId::Av1.media_type(), MediaType::Video);
389 assert_eq!(CodecId::Opus.media_type(), MediaType::Audio);
390 assert_eq!(CodecId::Pgs.media_type(), MediaType::Subtitle);
391 }
392
393 #[test]
394 fn parameters_default_per_media_type() {
395 let v = CodecParameters::new(CodecId::H265);
396 assert!(v.video().is_some() && v.audio().is_none());
397 let a = CodecParameters::new(CodecId::Opus);
398 assert_eq!(a.audio().unwrap().layout, ChannelLayout::Stereo);
399 assert!(matches!(
400 CodecParameters::new(CodecId::Pgs).media,
401 MediaParameters::Subtitle
402 ));
403
404 // NTSC frame rate survives as a rate and inverts into a tick duration.
405 let mut p = CodecParameters::new(CodecId::H264);
406 if let MediaParameters::Video(v) = &mut p.media {
407 v.width = 1920;
408 v.height = 1080;
409 v.frame_rate = Some(TimeBase::new(24_000, 1001));
410 v.format = Some(PixelFormat::I420);
411 }
412 let fr = p.video().unwrap().frame_rate.unwrap();
413 assert_eq!(fr.num(), 24_000);
414 assert_eq!(fr.inverse(), TimeBase::NTSC_FILM);
415 }
416
417 #[test]
418 fn stream_info_carries_language_and_timing() {
419 let mut s = StreamInfo::new(2, TimeBase::MILLIS, CodecParameters::new(CodecId::Srt));
420 s.language = Some("tur".into());
421 s.duration = Some(3_600_000);
422 assert_eq!(s.params.codec.media_type(), MediaType::Subtitle);
423 assert_eq!(s.index, 2);
424 assert_eq!(s.language.as_deref(), Some("tur"));
425 }
426
427 #[test]
428 fn trait_objects_are_send() {
429 fn assert_send<T: Send + ?Sized>() {}
430 assert_send::<dyn Demuxer>();
431 assert_send::<dyn Muxer>();
432 assert_send::<dyn Decoder>();
433 assert_send::<dyn Encoder>();
434 assert_send::<Packet>();
435 assert_send::<Frame>();
436 }
437}