forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB6828b15Tahinli3 months ago393 commits

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