forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

registry.rs756 lines, 27.5 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 /// Apple ProRes (all six profiles, 422 Proxy to 4444 XQ).
36 ProRes,
37 /// MPEG-2 video (ISO/IEC 13818-2); MPEG-1 video (11172-2) is carried under the same id.
38 Mpeg2Video,
39 /// Motion JPEG (ITU-T T.81 frames as video; JFIF full range).
40 Mjpeg,
41 /// Avid DNxHD / DNxHR (SMPTE VC-3).
42 Dnxhd,
43 /// MPEG-4 Part 2 Visual (Simple/Advanced Simple profile: XviD, DivX 4/5, `mp4v`) and H.263 baseline.
44 Mpeg4Part2,
45 /// Microsoft MPEG-4 version 1 (MPG4 / DIV1).
46 MsMpeg4V1,
47 /// Microsoft MPEG-4 version 2 (MP42 / DIV2).
48 MsMpeg4V2,
49 /// Microsoft MPEG-4 version 3 (DivX 3: DIV3 / MP43 / DIV4 ...).
50 MsMpeg4V3,
51 /// MPEG-4 AAC (LC and friends).
52 Aac,
53 /// Dolby AC-3.
54 Ac3,
55 /// Dolby Digital Plus (E-AC-3).
56 EAc3,
57 /// Dolby TrueHD (MLP), including the Atmos substream.
58 TrueHd,
59 /// DTS and its extensions (DTS-HD, DTS:X).
60 Dts,
61 /// ALAC.
62 Alac,
63 /// Xiph FLAC.
64 Flac,
65 /// MPEG-1/2 Layer III.
66 Mp3,
67 /// MPEG-1/2/2.5 Layer II (MP2).
68 Mp2,
69 /// MPEG-1/2/2.5 Layer I (MP1).
70 Mp1,
71 /// Xiph Opus.
72 Opus,
73 /// Xiph Vorbis.
74 Vorbis,
75 /// Unsigned 8-bit PCM.
76 PcmU8,
77 /// Signed 16-bit little-endian PCM.
78 PcmS16Le,
79 /// Signed 16-bit big-endian PCM.
80 PcmS16Be,
81 /// Signed 24-bit little-endian packed PCM.
82 PcmS24Le,
83 /// Signed 32-bit little-endian PCM.
84 PcmS32Le,
85 /// 32-bit float little-endian PCM.
86 PcmF32Le,
87 /// Signed 24-bit big-endian packed PCM.
88 PcmS24Be,
89 /// Signed 32-bit big-endian PCM.
90 PcmS32Be,
91 /// 32-bit float big-endian PCM.
92 PcmF32Be,
93 /// SubRip text.
94 Srt,
95 /// WebVTT text.
96 WebVtt,
97 /// Advanced SubStation Alpha (and SSA).
98 Ass,
99 /// Blu-ray Presentation Graphic Stream bitmaps.
100 Pgs,
101 /// MPEG-4 timed text (3GPP `tx3g`).
102 Tx3g,
103 /// DV video (IEC 61834, SMPTE 314M/370M): DV25, DVCPRO25/50, DVCPRO HD.
104 DvVideo,
105 /// Uncompressed video (AVI `BI_RGB` / YUY2 / UYVY / I420 / YV12 ...).
106 RawVideo,
107 /// IMA ADPCM (WAV 0x0011 / AVI).
108 ImaAdpcmWav,
109 /// Microsoft ADPCM (WAV 0x0002 / AVI).
110 MsAdpcm,
111 /// QuickTime IMA4 (`ima4`).
112 ImaAdpcmQt,
113 /// G.711 A-law (WAV 0x0006, mov `alaw`).
114 PcmAlaw,
115 /// G.711 mu-law (WAV 0x0007, mov `ulaw`).
116 PcmMulaw,
117 /// AMR narrow-band (3GPP TS 26.071, `samr`).
118 AmrNb,
119 /// AMR wide-band (3GPP TS 26.171, `sawb`).
120 AmrWb,
121 /// DVD-Video subpictures (VobSub, RLE SPU).
122 DvdSub,
123 /// DVB subtitles (ETSI EN 300 743).
124 DvbSub,
125}
126
127impl CodecId {
128 /// The media type this codec produces.
129 pub fn media_type(&self) -> MediaType {
130 use CodecId::*;
131 match self {
132 H264 | H265 | Vp8 | Vp9 | Av1 | ProRes | Mpeg2Video | Mjpeg | Dnxhd | Mpeg4Part2
133 | MsMpeg4V1 | MsMpeg4V2 | MsMpeg4V3 => MediaType::Video,
134 Aac | Ac3 | EAc3 | TrueHd | Dts | Alac | Flac | Mp3 | Mp2 | Mp1 | Opus | Vorbis
135 | PcmU8 | PcmS16Le | PcmS16Be | PcmS24Le | PcmS32Le | PcmF32Le
136 | PcmS24Be | PcmS32Be | PcmF32Be | ImaAdpcmWav | MsAdpcm | ImaAdpcmQt | PcmAlaw
137 | PcmMulaw | AmrNb | AmrWb => MediaType::Audio,
138 Srt | WebVtt | Ass | Pgs | Tx3g | DvdSub | DvbSub => MediaType::Subtitle,
139 DvVideo | RawVideo => MediaType::Video,
140 }
141 }
142
143 /// Short lowercase name, stable enough for logs and capability tables.
144 pub fn name(&self) -> &'static str {
145 use CodecId::*;
146 match self {
147 H264 => "h264",
148 H265 => "h265",
149 Vp8 => "vp8",
150 Vp9 => "vp9",
151 Av1 => "av1",
152 ProRes => "prores",
153 Mpeg2Video => "mpeg2video",
154 Mjpeg => "mjpeg",
155 Dnxhd => "dnxhd",
156 Mpeg4Part2 => "mpeg4",
157 MsMpeg4V1 => "msmpeg4v1",
158 MsMpeg4V2 => "msmpeg4v2",
159 MsMpeg4V3 => "msmpeg4v3",
160 Aac => "aac",
161 Ac3 => "ac3",
162 EAc3 => "eac3",
163 TrueHd => "truehd",
164 Dts => "dts",
165 Alac => "alac",
166 Flac => "flac",
167 Mp3 => "mp3",
168 Mp2 => "mp2",
169 Mp1 => "mp1",
170 Opus => "opus",
171 Vorbis => "vorbis",
172 PcmU8 => "pcm_u8",
173 PcmS16Le => "pcm_s16le",
174 PcmS16Be => "pcm_s16be",
175 PcmS24Le => "pcm_s24le",
176 PcmS32Le => "pcm_s32le",
177 PcmF32Le => "pcm_f32le",
178 PcmS24Be => "pcm_s24be",
179 PcmS32Be => "pcm_s32be",
180 PcmF32Be => "pcm_f32be",
181 Srt => "srt",
182 WebVtt => "webvtt",
183 Ass => "ass",
184 Pgs => "pgs",
185 Tx3g => "tx3g",
186 DvVideo => "dvvideo",
187 RawVideo => "rawvideo",
188 ImaAdpcmWav => "adpcm_ima_wav",
189 MsAdpcm => "adpcm_ms",
190 ImaAdpcmQt => "adpcm_ima_qt",
191 PcmAlaw => "pcm_alaw",
192 PcmMulaw => "pcm_mulaw",
193 AmrNb => "amr_nb",
194 AmrWb => "amr_wb",
195 DvdSub => "dvd_subtitle",
196 DvbSub => "dvb_subtitle",
197 }
198 }
199}
200
201/// Video half of [`CodecParameters`].
202#[derive(Debug, Clone, PartialEq, Default)]
203pub struct VideoParameters {
204 /// Coded width in pixels.
205 pub width: u32,
206 /// Coded height in pixels.
207 pub height: u32,
208 /// Decoded pixel layout, when the container or headers state one.
209 pub format: Option<PixelFormat>,
210 /// Frame rate *as a rate*: `num/den` is frames per second, so NTSC film is
211 /// `24000/1001`. Invert it with [`TimeBase::inverse`] for a tick duration.
212 pub frame_rate: Option<TimeBase>,
213 /// Sample aspect ratio (`num/den`), when not square.
214 pub sample_aspect_ratio: Option<TimeBase>,
215 /// H.273 colour description.
216 pub color: ColorInfo,
217 /// How bright the grade says this stream gets: MaxCLL/MaxFALL and the
218 /// mastering display, when the container or an HDR SEI stated them. All
219 /// [`None`] for SDR, which is what a tone map falls back on.
220 pub light: ContentLight,
221}
222
223/// Audio half of [`CodecParameters`].
224#[derive(Debug, Clone, PartialEq, Eq)]
225pub struct AudioParameters {
226 /// Sample rate in Hz.
227 pub sample_rate: u32,
228 /// Channel count, order and meaning.
229 pub layout: ChannelLayout,
230 /// Decoded sample format, when known before the first frame.
231 pub format: Option<SampleFormat>,
232 /// Coded bit depth, when the codec has one (FLAC 24, ALAC 16/24).
233 pub bits_per_sample: Option<u32>,
234}
235
236impl Default for AudioParameters {
237 fn default() -> Self {
238 AudioParameters {
239 sample_rate: 0,
240 layout: ChannelLayout::Stereo,
241 format: None,
242 bits_per_sample: None,
243 }
244 }
245}
246
247/// Per-media-type parameters.
248#[derive(Debug, Clone, PartialEq)]
249pub enum MediaParameters {
250 /// Video stream parameters.
251 Video(VideoParameters),
252 /// Audio stream parameters.
253 Audio(AudioParameters),
254 /// Subtitle streams carry no dimensions; their setup lives in `extradata`
255 /// (the ASS header, the PGS palette, ...).
256 Subtitle,
257}
258
259/// Everything a decoder needs before it sees its first packet.
260#[derive(Debug, Clone, PartialEq)]
261pub struct CodecParameters {
262 /// Which codec.
263 pub codec: CodecId,
264 /// Codec-defined setup bytes: avcC, hvcC, av1C, AudioSpecificConfig, the
265 /// FLAC STREAMINFO block, the Vorbis header triplet, and so on.
266 pub extradata: Option<Buf>,
267 /// Media-type-specific parameters.
268 pub media: MediaParameters,
269}
270
271impl CodecParameters {
272 /// Parameters for `codec` with defaults for its media type and no extradata.
273 pub fn new(codec: CodecId) -> CodecParameters {
274 let media = match codec.media_type() {
275 MediaType::Video => MediaParameters::Video(VideoParameters::default()),
276 MediaType::Audio => MediaParameters::Audio(AudioParameters::default()),
277 MediaType::Subtitle => MediaParameters::Subtitle,
278 };
279 CodecParameters {
280 codec,
281 extradata: None,
282 media,
283 }
284 }
285
286 /// Video parameters, when this is a video stream.
287 pub fn video(&self) -> Option<&VideoParameters> {
288 match &self.media {
289 MediaParameters::Video(v) => Some(v),
290 _ => None,
291 }
292 }
293
294 /// Audio parameters, when this is an audio stream.
295 pub fn audio(&self) -> Option<&AudioParameters> {
296 match &self.media {
297 MediaParameters::Audio(a) => Some(a),
298 _ => None,
299 }
300 }
301}
302
303/// The turn a container's display matrix asks a player to make so its pictures
304/// are seen the way they were shot: quarter turns **clockwise**. A phone's
305/// portrait video is the case that names it -- the pixels stay landscape and
306/// the container says which way to turn them.
307///
308/// This is metadata about the *pixels*, not a user's edit, and it is not a
309/// request to touch them here: a demuxer reports it and a consumer (the
310/// preview, the encoder) decides. A matrix that is not a quarter turn -- a
311/// mirror, a shear, a scale, or a 45-degree quirk -- is [`Rotation::Other`]
312/// rather than an approximation, so a caller refuses it by name instead of
313/// showing the picture wrong.
314#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
315pub enum Rotation {
316 /// No turn: an identity display matrix, or a container that states one.
317 #[default]
318 None,
319 /// A quarter turn clockwise.
320 Cw90,
321 /// A half turn (two quarter turns clockwise).
322 Cw180,
323 /// Three quarter turns clockwise, i.e. one quarter counter-clockwise.
324 Cw270,
325 /// A display matrix that is not a quarter turn: a mirror (a negative
326 /// determinant), a shear, an anisotropic scale, or an angle that is not a
327 /// multiple of 90 degrees. The four linear terms are carried verbatim so
328 /// the reading is representable rather than silently dropped -- they are
329 /// the 16.16 fixed-point `a`, `b`, `c`, `d` of an ISO-BMFF `tkhd` matrix
330 /// (`matrix[0][0]`, `[0][1]`, `[1][0]`, `[1][1]`).
331 Other {
332 /// The matrix's `a` term, 16.16 fixed point.
333 a: i32,
334 /// The matrix's `b` term, 16.16 fixed point.
335 b: i32,
336 /// The matrix's `c` term, 16.16 fixed point.
337 c: i32,
338 /// The matrix's `d` term, 16.16 fixed point.
339 d: i32,
340 },
341}
342
343impl Rotation {
344 /// The rotation an ISO-BMFF `tkhd` display matrix states, from its linear
345 /// 2x2 part read as 16.16 fixed-point `i32`s.
346 ///
347 /// The matrix transforms a point `(x, y)` to `(a*x + c*y, b*x + d*y)`, so
348 /// the columns `(a, b)` and `(c, d)` are the turned axes: a pure rotation
349 /// has both columns the same length (isotropic) and one the other's quarter
350 /// turn (`a == d`, `b == -c`). Anything else is [`Rotation::Other`].
351 ///
352 /// The reading is exact integer arithmetic: the four quarter turns are
353 /// recognised by an axis landing on an axis (`b == 0` or `a == 0`). An
354 /// encoder writes 16.16 quarter turns exactly, so a value within a fraction
355 /// of a degree of one that is not exactly one -- a hand-edited or rescaled
356 /// matrix -- reads as [`Rotation::Other`] rather than being rounded onto a
357 /// turn this decoder would then apply for real.
358 pub fn from_matrix(a: i32, b: i32, c: i32, d: i32) -> Rotation {
359 // A pure rotation: isotropic (a == d, b == -c) with something to turn.
360 // `c.checked_neg()` rather than `-c`: a crafted `tkhd` can carry
361 // `i32::MIN`, whose negation is not representable -- the plain form
362 // panics in a debug build and wraps onto a false quarter turn in a
363 // release one. `checked_neg` is `None` there, so the term falls through
364 // to `Other` below, which is the right reading for it anyway.
365 if a == d && c.checked_neg() == Some(b) && (a != 0 || b != 0) {
366 // `(a, b)` is the turned x-axis; a quarter turn lands it on an axis.
367 return match (a.signum(), b.signum()) {
368 (1, 0) => Rotation::None,
369 (-1, 0) => Rotation::Cw180,
370 (0, 1) => Rotation::Cw90,
371 (0, -1) => Rotation::Cw270,
372 _ => Rotation::Other { a, b, c, d },
373 };
374 }
375 Rotation::Other { a, b, c, d }
376 }
377
378 /// Quarter turns clockwise, where the stream is a quarter turn at all --
379 /// `None` for anything [`Rotation::Other`] carries.
380 pub fn steps(self) -> Option<u8> {
381 match self {
382 Rotation::None => Some(0),
383 Rotation::Cw90 => Some(1),
384 Rotation::Cw180 => Some(2),
385 Rotation::Cw270 => Some(3),
386 Rotation::Other { .. } => None,
387 }
388 }
389
390 /// Whether the turned picture's width and height are the coded ones
391 /// swapped.
392 pub fn swaps_axes(self) -> bool {
393 matches!(self, Rotation::Cw90 | Rotation::Cw270)
394 }
395
396 /// Whether there is nothing to do: no turn, the common case of a file that
397 /// was shot the way it is stored.
398 pub fn is_none(self) -> bool {
399 matches!(self, Rotation::None)
400 }
401}
402
403/// One stream of a container, as a demuxer reports it.
404#[derive(Debug, Clone, PartialEq)]
405pub struct StreamInfo {
406 /// Index matching [`Packet::stream`].
407 pub index: u32,
408 /// Base of every timestamp on this stream's packets.
409 pub time_base: TimeBase,
410 /// Codec and setup data.
411 pub params: CodecParameters,
412 /// First presentation timestamp, in `time_base` ticks, when known.
413 pub start_time: Option<i64>,
414 /// Duration in `time_base` ticks, when the container states one.
415 pub duration: Option<i64>,
416 /// ISO 639-2 language tag, when the container carries one.
417 pub language: Option<String>,
418 /// Samples the decoder emits before the first audible one: an MP3's gapless
419 /// encoder delay, an Opus stream's pre-skip. Zero where a stream has none.
420 ///
421 /// It is *not* subtracted from [`duration`](Self::duration), because a
422 /// caller counting decoded samples has to count these too before it can
423 /// drop them -- audible length is `duration - initial_padding`. Trailing
424 /// padding is not reported separately: `duration` already ends at the last
425 /// audible sample.
426 pub initial_padding: u32,
427 /// The container **explicitly** marked this stream as the one to play --
428 /// Matroska's `FlagDefault`, which is what names the language a dual-audio
429 /// remux opens in.
430 ///
431 /// Explicitly is the whole of it: `FlagDefault` is 1 when the element is
432 /// absent, so "flagged" and "eligible" are different questions and only the
433 /// first one picks a track. A file where nobody wrote the element has no
434 /// flagged stream at all, and its first stream of a kind is its default
435 /// ([`crate::registry`] callers, `ec_probe::Reader::default_stream`).
436 pub default: bool,
437 /// The turn this stream's display matrix asks for, where the container
438 /// states one. [`Rotation::None`] for a container that states none, for an
439 /// identity matrix, and for a non-video stream alike -- the common case.
440 ///
441 /// This is metadata, not an edit: nothing about [`params`](Self::params)
442 /// changes because of it, and a caller that wants the displayed picture
443 /// (the preview, the encoder) has to make the turn itself.
444 pub rotation: Rotation,
445}
446
447impl StreamInfo {
448 /// A stream with no timing hints, no language, no padding and no default
449 /// flag.
450 pub fn new(index: u32, time_base: TimeBase, params: CodecParameters) -> StreamInfo {
451 StreamInfo {
452 index,
453 time_base,
454 params,
455 start_time: None,
456 duration: None,
457 language: None,
458 initial_padding: 0,
459 default: false,
460 rotation: Rotation::None,
461 }
462 }
463}
464
465/// Where a seek is allowed to land relative to the requested instant.
466#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
467pub enum SeekMode {
468 /// Nearest random access point at or before the target. The default: it is
469 /// the only mode that lets a decoder reach the target frame exactly, by
470 /// decoding forward and discarding.
471 #[default]
472 SyncBefore,
473 /// Nearest random access point at or after the target.
474 SyncAfter,
475 /// Exact instant, whether or not a random access point sits there; the
476 /// caller handles the pre-roll.
477 Exact,
478}
479
480/// A container reader: streams in, packets out.
481pub trait Demuxer: Send {
482 /// The streams found while opening the container.
483 fn streams(&self) -> &[StreamInfo];
484
485 /// Next packet in storage order, or [`crate::Error::Eof`] at the end.
486 fn next_packet(&mut self) -> Result<Packet>;
487
488 /// Position so that reading resumes near `to` on `stream`.
489 ///
490 /// `to` carries its own [`TimeBase`], so callers never have to know the
491 /// stream's base to seek by wall-clock instant.
492 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()>;
493}
494
495/// A container writer: streams declared, then packets, then a finish.
496pub trait Muxer: Send {
497 /// Declare a stream; returns the index that its packets must carry.
498 ///
499 /// All streams are declared before the first [`Muxer::write_packet`].
500 fn add_stream(&mut self, info: StreamInfo) -> Result<u32>;
501
502 /// Write one packet. Its `stream` must be an index from
503 /// [`Muxer::add_stream`] and its timestamps are rescaled by the muxer.
504 fn write_packet(&mut self, packet: &Packet) -> Result<()>;
505
506 /// Flush indices and trailers. Takes `&mut self` rather than `self` so a
507 /// muxer stays usable behind `Box<dyn Muxer>`.
508 fn finish(&mut self) -> Result<()>;
509}
510
511/// A decoder: packets in, frames out.
512///
513/// Push/pull rather than `decode(&Packet) -> Vec<Frame>` because the mapping is
514/// genuinely not one to one — a parameter-set packet yields nothing, a
515/// reordering decoder yields nothing until its DPB fills, an audio packet can
516/// yield several blocks — and because end of stream has to be expressible:
517/// [`Decoder::flush`] then drains what reorder delay is still holding. The
518/// `Vec` shape would allocate per packet and still need a second entry point
519/// for the drain.
520pub trait Decoder: Send {
521 /// The parameters this decoder was configured with, updated in place when
522 /// in-band headers change them.
523 fn codec_parameters(&self) -> &CodecParameters;
524
525 /// Submit one packet. Call [`Decoder::receive_frame`] until it answers
526 /// [`crate::Error::NeedMore`] before submitting the next.
527 fn send_packet(&mut self, packet: &Packet) -> Result<()>;
528
529 /// Take one decoded frame; [`crate::Error::NeedMore`] when none is ready,
530 /// [`crate::Error::Eof`] once a flushed decoder is drained.
531 fn receive_frame(&mut self) -> Result<Frame>;
532
533 /// Signal end of stream: after this, `receive_frame` returns the delayed
534 /// frames and then [`crate::Error::Eof`].
535 fn flush(&mut self) -> Result<()>;
536
537 /// Drop all buffered state after a seek. Timestamps and references from
538 /// before the seek are discarded.
539 fn reset(&mut self);
540}
541
542/// An encoder: frames in, packets out — the mirror of [`Decoder`].
543pub trait Encoder: Send {
544 /// Parameters describing the encoder's output, including the `extradata`
545 /// a muxer needs. For codecs whose setup data is derived while encoding
546 /// (AAC ASC, avcC), this is final after the first
547 /// [`Encoder::receive_packet`].
548 fn codec_parameters(&self) -> &CodecParameters;
549
550 /// Submit one frame.
551 fn send_frame(&mut self, frame: &Frame) -> Result<()>;
552
553 /// Take one encoded packet; [`crate::Error::NeedMore`] when none is ready,
554 /// [`crate::Error::Eof`] once a flushed encoder is drained.
555 fn receive_packet(&mut self) -> Result<Packet>;
556
557 /// Signal end of input and drain the lookahead.
558 fn flush(&mut self) -> Result<()>;
559}
560
561#[cfg(test)]
562mod tests {
563 use super::*;
564
565 #[test]
566 fn every_codec_id_has_a_media_type_and_name() {
567 // The set the family must express, spelled out so a later crate cannot
568 // quietly lose one (subtitle packets included: they are Packets, not
569 // Frames).
570 let all = [
571 CodecId::H264,
572 CodecId::H265,
573 CodecId::Vp8,
574 CodecId::Vp9,
575 CodecId::Av1,
576 CodecId::ProRes,
577 CodecId::Mpeg2Video,
578 CodecId::Mjpeg,
579 CodecId::Dnxhd,
580 CodecId::Mpeg4Part2,
581 CodecId::MsMpeg4V1,
582 CodecId::MsMpeg4V2,
583 CodecId::MsMpeg4V3,
584 CodecId::Aac,
585 CodecId::Ac3,
586 CodecId::EAc3,
587 CodecId::TrueHd,
588 CodecId::Dts,
589 CodecId::Alac,
590 CodecId::Flac,
591 CodecId::Mp3,
592 CodecId::Mp2,
593 CodecId::Mp1,
594 CodecId::Opus,
595 CodecId::Vorbis,
596 CodecId::PcmU8,
597 CodecId::PcmS16Le,
598 CodecId::PcmS16Be,
599 CodecId::PcmS24Le,
600 CodecId::PcmS32Le,
601 CodecId::PcmF32Le,
602 CodecId::PcmS24Be,
603 CodecId::PcmS32Be,
604 CodecId::PcmF32Be,
605 CodecId::Srt,
606 CodecId::WebVtt,
607 CodecId::Ass,
608 CodecId::Pgs,
609 CodecId::ImaAdpcmWav,
610 CodecId::MsAdpcm,
611 CodecId::ImaAdpcmQt,
612 CodecId::PcmAlaw,
613 CodecId::PcmMulaw,
614 CodecId::AmrNb,
615 CodecId::AmrWb,
616 CodecId::Tx3g,
617 CodecId::DvVideo,
618 CodecId::RawVideo,
619 CodecId::DvdSub,
620 CodecId::DvbSub,
621 ];
622 assert_eq!(all.len(), 50);
623 let mut names: Vec<&str> = all.iter().map(|c| c.name()).collect();
624 names.sort_unstable();
625 names.dedup();
626 assert_eq!(names.len(), all.len(), "codec names must be unique");
627 assert_eq!(CodecId::Av1.media_type(), MediaType::Video);
628 assert_eq!(CodecId::Opus.media_type(), MediaType::Audio);
629 assert_eq!(CodecId::Pgs.media_type(), MediaType::Subtitle);
630 }
631
632 #[test]
633 fn parameters_default_per_media_type() {
634 let v = CodecParameters::new(CodecId::H265);
635 assert!(v.video().is_some() && v.audio().is_none());
636 let a = CodecParameters::new(CodecId::Opus);
637 assert_eq!(a.audio().unwrap().layout, ChannelLayout::Stereo);
638 assert!(matches!(
639 CodecParameters::new(CodecId::Pgs).media,
640 MediaParameters::Subtitle
641 ));
642
643 // NTSC frame rate survives as a rate and inverts into a tick duration.
644 let mut p = CodecParameters::new(CodecId::H264);
645 if let MediaParameters::Video(v) = &mut p.media {
646 v.width = 1920;
647 v.height = 1080;
648 v.frame_rate = Some(TimeBase::new(24_000, 1001));
649 v.format = Some(PixelFormat::I420);
650 }
651 let fr = p.video().unwrap().frame_rate.unwrap();
652 assert_eq!(fr.num(), 24_000);
653 assert_eq!(fr.inverse(), TimeBase::NTSC_FILM);
654 }
655
656 #[test]
657 fn stream_info_carries_language_and_timing() {
658 let mut s = StreamInfo::new(2, TimeBase::MILLIS, CodecParameters::new(CodecId::Srt));
659 s.language = Some("tur".into());
660 s.duration = Some(3_600_000);
661 assert_eq!(s.params.codec.media_type(), MediaType::Subtitle);
662 assert_eq!(s.index, 2);
663 assert_eq!(s.language.as_deref(), Some("tur"));
664 assert_eq!(s.rotation, Rotation::None);
665 }
666
667 #[test]
668 fn quarter_turn_matrices_read_as_typed_rotations() {
669 const ONE: i32 = 65_536; // 16.16 unity.
670 let cases = [
671 // A tkhd matrix and the turn it states, in this crate's clockwise
672 // convention. `(0, -1, 1, 0)` is what ffmpeg's
673 // `-display_rotation 90` writes: it asks the picture to be turned
674 // a quarter counter-clockwise here, which is Cw270.
675 ((ONE, 0, 0, ONE), Rotation::None),
676 ((0, -ONE, ONE, 0), Rotation::Cw270),
677 ((-ONE, 0, 0, -ONE), Rotation::Cw180),
678 ((0, ONE, -ONE, 0), Rotation::Cw90),
679 // A scaled identity is still no turn: the reading normalises by the
680 // matrix's own scale, so a differently-scaled copy reads the same.
681 ((2 * ONE, 0, 0, 2 * ONE), Rotation::None),
682 ];
683 for ((a, b, c, d), want) in cases {
684 assert_eq!(Rotation::from_matrix(a, b, c, d), want, "{a} {b} {c} {d}");
685 }
686 assert_eq!(Rotation::None.steps(), Some(0));
687 assert_eq!(Rotation::Cw90.steps(), Some(1));
688 assert_eq!(Rotation::Cw180.steps(), Some(2));
689 assert_eq!(Rotation::Cw270.steps(), Some(3));
690 assert!(Rotation::Cw90.swaps_axes() && Rotation::Cw270.swaps_axes());
691 assert!(!Rotation::None.swaps_axes() && !Rotation::Cw180.swaps_axes());
692 assert!(Rotation::None.is_none());
693 }
694
695 #[test]
696 fn a_matrix_that_is_not_a_quarter_turn_is_kept_not_rounded() {
697 const ONE: i32 = 65_536;
698 // A 45-degree turn: isotropic and pure, but no axis lands on an axis.
699 assert_eq!(
700 Rotation::from_matrix(46_340, -46_340, 46_340, 46_340),
701 Rotation::Other {
702 a: 46_340,
703 b: -46_340,
704 c: 46_340,
705 d: 46_340,
706 }
707 );
708 // A mirror (negative determinant), a mirror of a quarter turn (b != -c),
709 // a shear (a != d), and the degenerate all-zero matrix: none is a turn.
710 for (a, b, c, d) in [
711 (ONE, 0, 0, -ONE),
712 (0, ONE, ONE, 0),
713 (ONE, 0, ONE, ONE),
714 (0, 0, 0, 0),
715 ] {
716 let got = Rotation::from_matrix(a, b, c, d);
717 assert!(
718 matches!(got, Rotation::Other { .. }),
719 "{a} {b} {c} {d} read as {got:?}"
720 );
721 assert_eq!(got.steps(), None, "Other is not a quarter count");
722 }
723 }
724
725 #[test]
726 fn a_matrix_term_at_i32_min_is_not_a_quarter_turn() {
727 // A crafted `tkhd` can carry `i32::MIN`, whose negation is not
728 // representable. `from_matrix` must not panic (debug) or wrap onto a
729 // false turn (release) deciding `b == -c`, and such a term is no
730 // quarter turn anyway. `(0, MIN, MIN, 0)` is the load-bearing case: the
731 // wrapping form would read it as `Cw270`.
732 for (a, b, c, d) in [
733 (0, i32::MIN, i32::MIN, 0),
734 (65_536, i32::MIN, i32::MIN, 65_536),
735 (i32::MIN, 0, i32::MIN, i32::MIN),
736 ] {
737 let got = Rotation::from_matrix(a, b, c, d);
738 assert!(
739 matches!(got, Rotation::Other { .. }),
740 "{a} {b} {c} {d} read as {got:?}"
741 );
742 assert_eq!(got.steps(), None, "Other is not a quarter count");
743 }
744 }
745
746 #[test]
747 fn trait_objects_are_send() {
748 fn assert_send<T: Send + ?Sized>() {}
749 assert_send::<dyn Demuxer>();
750 assert_send::<dyn Muxer>();
751 assert_send::<dyn Decoder>();
752 assert_send::<dyn Encoder>();
753 assert_send::<Packet>();
754 assert_send::<Frame>();
755 }
756}