forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB84fa44cTahinli2 months ago3331 commits

registry.rs656 lines, 24.1 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/// The turn a container's display matrix asks a player to make so its pictures
228/// are seen the way they were shot: quarter turns **clockwise**. A phone's
229/// portrait video is the case that names it -- the pixels stay landscape and
230/// the container says which way to turn them.
231///
232/// This is metadata about the *pixels*, not a user's edit, and it is not a
233/// request to touch them here: a demuxer reports it and a consumer (the
234/// preview, the encoder) decides. A matrix that is not a quarter turn -- a
235/// mirror, a shear, a scale, or a 45-degree quirk -- is [`Rotation::Other`]
236/// rather than an approximation, so a caller refuses it by name instead of
237/// showing the picture wrong.
238#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
239pub enum Rotation {
240 /// No turn: an identity display matrix, or a container that states one.
241 #[default]
242 None,
243 /// A quarter turn clockwise.
244 Cw90,
245 /// A half turn (two quarter turns clockwise).
246 Cw180,
247 /// Three quarter turns clockwise, i.e. one quarter counter-clockwise.
248 Cw270,
249 /// A display matrix that is not a quarter turn: a mirror (a negative
250 /// determinant), a shear, an anisotropic scale, or an angle that is not a
251 /// multiple of 90 degrees. The four linear terms are carried verbatim so
252 /// the reading is representable rather than silently dropped -- they are
253 /// the 16.16 fixed-point `a`, `b`, `c`, `d` of an ISO-BMFF `tkhd` matrix
254 /// (`matrix[0][0]`, `[0][1]`, `[1][0]`, `[1][1]`).
255 Other {
256 /// The matrix's `a` term, 16.16 fixed point.
257 a: i32,
258 /// The matrix's `b` term, 16.16 fixed point.
259 b: i32,
260 /// The matrix's `c` term, 16.16 fixed point.
261 c: i32,
262 /// The matrix's `d` term, 16.16 fixed point.
263 d: i32,
264 },
265}
266
267impl Rotation {
268 /// The rotation an ISO-BMFF `tkhd` display matrix states, from its linear
269 /// 2x2 part read as 16.16 fixed-point `i32`s.
270 ///
271 /// The matrix transforms a point `(x, y)` to `(a*x + c*y, b*x + d*y)`, so
272 /// the columns `(a, b)` and `(c, d)` are the turned axes: a pure rotation
273 /// has both columns the same length (isotropic) and one the other's quarter
274 /// turn (`a == d`, `b == -c`). Anything else is [`Rotation::Other`].
275 ///
276 /// The reading is exact integer arithmetic: the four quarter turns are
277 /// recognised by an axis landing on an axis (`b == 0` or `a == 0`). An
278 /// encoder writes 16.16 quarter turns exactly, so a value within a fraction
279 /// of a degree of one that is not exactly one -- a hand-edited or rescaled
280 /// matrix -- reads as [`Rotation::Other`] rather than being rounded onto a
281 /// turn this decoder would then apply for real.
282 pub fn from_matrix(a: i32, b: i32, c: i32, d: i32) -> Rotation {
283 // A pure rotation: isotropic (a == d, b == -c) with something to turn.
284 // `c.checked_neg()` rather than `-c`: a crafted `tkhd` can carry
285 // `i32::MIN`, whose negation is not representable -- the plain form
286 // panics in a debug build and wraps onto a false quarter turn in a
287 // release one. `checked_neg` is `None` there, so the term falls through
288 // to `Other` below, which is the right reading for it anyway.
289 if a == d && c.checked_neg() == Some(b) && (a != 0 || b != 0) {
290 // `(a, b)` is the turned x-axis; a quarter turn lands it on an axis.
291 return match (a.signum(), b.signum()) {
292 (1, 0) => Rotation::None,
293 (-1, 0) => Rotation::Cw180,
294 (0, 1) => Rotation::Cw90,
295 (0, -1) => Rotation::Cw270,
296 _ => Rotation::Other { a, b, c, d },
297 };
298 }
299 Rotation::Other { a, b, c, d }
300 }
301
302 /// Quarter turns clockwise, where the stream is a quarter turn at all --
303 /// `None` for anything [`Rotation::Other`] carries.
304 pub fn steps(self) -> Option<u8> {
305 match self {
306 Rotation::None => Some(0),
307 Rotation::Cw90 => Some(1),
308 Rotation::Cw180 => Some(2),
309 Rotation::Cw270 => Some(3),
310 Rotation::Other { .. } => None,
311 }
312 }
313
314 /// Whether the turned picture's width and height are the coded ones
315 /// swapped.
316 pub fn swaps_axes(self) -> bool {
317 matches!(self, Rotation::Cw90 | Rotation::Cw270)
318 }
319
320 /// Whether there is nothing to do: no turn, the common case of a file that
321 /// was shot the way it is stored.
322 pub fn is_none(self) -> bool {
323 matches!(self, Rotation::None)
324 }
325}
326
327/// One stream of a container, as a demuxer reports it.
328#[derive(Debug, Clone, PartialEq)]
329pub struct StreamInfo {
330 /// Index matching [`Packet::stream`].
331 pub index: u32,
332 /// Base of every timestamp on this stream's packets.
333 pub time_base: TimeBase,
334 /// Codec and setup data.
335 pub params: CodecParameters,
336 /// First presentation timestamp, in `time_base` ticks, when known.
337 pub start_time: Option<i64>,
338 /// Duration in `time_base` ticks, when the container states one.
339 pub duration: Option<i64>,
340 /// ISO 639-2 language tag, when the container carries one.
341 pub language: Option<String>,
342 /// Samples the decoder emits before the first audible one: an MP3's gapless
343 /// encoder delay, an Opus stream's pre-skip. Zero where a stream has none.
344 ///
345 /// It is *not* subtracted from [`duration`](Self::duration), because a
346 /// caller counting decoded samples has to count these too before it can
347 /// drop them -- audible length is `duration - initial_padding`. Trailing
348 /// padding is not reported separately: `duration` already ends at the last
349 /// audible sample.
350 pub initial_padding: u32,
351 /// The container **explicitly** marked this stream as the one to play --
352 /// Matroska's `FlagDefault`, which is what names the language a dual-audio
353 /// remux opens in.
354 ///
355 /// Explicitly is the whole of it: `FlagDefault` is 1 when the element is
356 /// absent, so "flagged" and "eligible" are different questions and only the
357 /// first one picks a track. A file where nobody wrote the element has no
358 /// flagged stream at all, and its first stream of a kind is its default
359 /// ([`crate::registry`] callers, `ec_probe::Reader::default_stream`).
360 pub default: bool,
361 /// The turn this stream's display matrix asks for, where the container
362 /// states one. [`Rotation::None`] for a container that states none, for an
363 /// identity matrix, and for a non-video stream alike -- the common case.
364 ///
365 /// This is metadata, not an edit: nothing about [`params`](Self::params)
366 /// changes because of it, and a caller that wants the displayed picture
367 /// (the preview, the encoder) has to make the turn itself.
368 pub rotation: Rotation,
369}
370
371impl StreamInfo {
372 /// A stream with no timing hints, no language, no padding and no default
373 /// flag.
374 pub fn new(index: u32, time_base: TimeBase, params: CodecParameters) -> StreamInfo {
375 StreamInfo {
376 index,
377 time_base,
378 params,
379 start_time: None,
380 duration: None,
381 language: None,
382 initial_padding: 0,
383 default: false,
384 rotation: Rotation::None,
385 }
386 }
387}
388
389/// Where a seek is allowed to land relative to the requested instant.
390#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
391pub enum SeekMode {
392 /// Nearest random access point at or before the target. The default: it is
393 /// the only mode that lets a decoder reach the target frame exactly, by
394 /// decoding forward and discarding.
395 #[default]
396 SyncBefore,
397 /// Nearest random access point at or after the target.
398 SyncAfter,
399 /// Exact instant, whether or not a random access point sits there; the
400 /// caller handles the pre-roll.
401 Exact,
402}
403
404/// A container reader: streams in, packets out.
405pub trait Demuxer: Send {
406 /// The streams found while opening the container.
407 fn streams(&self) -> &[StreamInfo];
408
409 /// Next packet in storage order, or [`crate::Error::Eof`] at the end.
410 fn next_packet(&mut self) -> Result<Packet>;
411
412 /// Position so that reading resumes near `to` on `stream`.
413 ///
414 /// `to` carries its own [`TimeBase`], so callers never have to know the
415 /// stream's base to seek by wall-clock instant.
416 fn seek(&mut self, stream: u32, to: Timestamp, mode: SeekMode) -> Result<()>;
417}
418
419/// A container writer: streams declared, then packets, then a finish.
420pub trait Muxer: Send {
421 /// Declare a stream; returns the index that its packets must carry.
422 ///
423 /// All streams are declared before the first [`Muxer::write_packet`].
424 fn add_stream(&mut self, info: StreamInfo) -> Result<u32>;
425
426 /// Write one packet. Its `stream` must be an index from
427 /// [`Muxer::add_stream`] and its timestamps are rescaled by the muxer.
428 fn write_packet(&mut self, packet: &Packet) -> Result<()>;
429
430 /// Flush indices and trailers. Takes `&mut self` rather than `self` so a
431 /// muxer stays usable behind `Box<dyn Muxer>`.
432 fn finish(&mut self) -> Result<()>;
433}
434
435/// A decoder: packets in, frames out.
436///
437/// Push/pull rather than `decode(&Packet) -> Vec<Frame>` because the mapping is
438/// genuinely not one to one — a parameter-set packet yields nothing, a
439/// reordering decoder yields nothing until its DPB fills, an audio packet can
440/// yield several blocks — and because end of stream has to be expressible:
441/// [`Decoder::flush`] then drains what reorder delay is still holding. The
442/// `Vec` shape would allocate per packet and still need a second entry point
443/// for the drain.
444pub trait Decoder: Send {
445 /// The parameters this decoder was configured with, updated in place when
446 /// in-band headers change them.
447 fn codec_parameters(&self) -> &CodecParameters;
448
449 /// Submit one packet. Call [`Decoder::receive_frame`] until it answers
450 /// [`crate::Error::NeedMore`] before submitting the next.
451 fn send_packet(&mut self, packet: &Packet) -> Result<()>;
452
453 /// Take one decoded frame; [`crate::Error::NeedMore`] when none is ready,
454 /// [`crate::Error::Eof`] once a flushed decoder is drained.
455 fn receive_frame(&mut self) -> Result<Frame>;
456
457 /// Signal end of stream: after this, `receive_frame` returns the delayed
458 /// frames and then [`crate::Error::Eof`].
459 fn flush(&mut self) -> Result<()>;
460
461 /// Drop all buffered state after a seek. Timestamps and references from
462 /// before the seek are discarded.
463 fn reset(&mut self);
464}
465
466/// An encoder: frames in, packets out — the mirror of [`Decoder`].
467pub trait Encoder: Send {
468 /// Parameters describing the encoder's output, including the `extradata`
469 /// a muxer needs. For codecs whose setup data is derived while encoding
470 /// (AAC ASC, avcC), this is final after the first
471 /// [`Encoder::receive_packet`].
472 fn codec_parameters(&self) -> &CodecParameters;
473
474 /// Submit one frame.
475 fn send_frame(&mut self, frame: &Frame) -> Result<()>;
476
477 /// Take one encoded packet; [`crate::Error::NeedMore`] when none is ready,
478 /// [`crate::Error::Eof`] once a flushed encoder is drained.
479 fn receive_packet(&mut self) -> Result<Packet>;
480
481 /// Signal end of input and drain the lookahead.
482 fn flush(&mut self) -> Result<()>;
483}
484
485#[cfg(test)]
486mod tests {
487 use super::*;
488
489 #[test]
490 fn every_codec_id_has_a_media_type_and_name() {
491 // The set the family must express, spelled out so a later crate cannot
492 // quietly lose one (subtitle packets included: they are Packets, not
493 // Frames).
494 let all = [
495 CodecId::H264,
496 CodecId::H265,
497 CodecId::Vp8,
498 CodecId::Vp9,
499 CodecId::Av1,
500 CodecId::Aac,
501 CodecId::Ac3,
502 CodecId::EAc3,
503 CodecId::TrueHd,
504 CodecId::Dts,
505 CodecId::Alac,
506 CodecId::Flac,
507 CodecId::Mp3,
508 CodecId::Opus,
509 CodecId::Vorbis,
510 CodecId::PcmU8,
511 CodecId::PcmS16Le,
512 CodecId::PcmS16Be,
513 CodecId::PcmS24Le,
514 CodecId::PcmS32Le,
515 CodecId::PcmF32Le,
516 CodecId::Srt,
517 CodecId::WebVtt,
518 CodecId::Ass,
519 CodecId::Pgs,
520 CodecId::Tx3g,
521 ];
522 assert_eq!(all.len(), 26);
523 let mut names: Vec<&str> = all.iter().map(|c| c.name()).collect();
524 names.sort_unstable();
525 names.dedup();
526 assert_eq!(names.len(), all.len(), "codec names must be unique");
527 assert_eq!(CodecId::Av1.media_type(), MediaType::Video);
528 assert_eq!(CodecId::Opus.media_type(), MediaType::Audio);
529 assert_eq!(CodecId::Pgs.media_type(), MediaType::Subtitle);
530 }
531
532 #[test]
533 fn parameters_default_per_media_type() {
534 let v = CodecParameters::new(CodecId::H265);
535 assert!(v.video().is_some() && v.audio().is_none());
536 let a = CodecParameters::new(CodecId::Opus);
537 assert_eq!(a.audio().unwrap().layout, ChannelLayout::Stereo);
538 assert!(matches!(
539 CodecParameters::new(CodecId::Pgs).media,
540 MediaParameters::Subtitle
541 ));
542
543 // NTSC frame rate survives as a rate and inverts into a tick duration.
544 let mut p = CodecParameters::new(CodecId::H264);
545 if let MediaParameters::Video(v) = &mut p.media {
546 v.width = 1920;
547 v.height = 1080;
548 v.frame_rate = Some(TimeBase::new(24_000, 1001));
549 v.format = Some(PixelFormat::I420);
550 }
551 let fr = p.video().unwrap().frame_rate.unwrap();
552 assert_eq!(fr.num(), 24_000);
553 assert_eq!(fr.inverse(), TimeBase::NTSC_FILM);
554 }
555
556 #[test]
557 fn stream_info_carries_language_and_timing() {
558 let mut s = StreamInfo::new(2, TimeBase::MILLIS, CodecParameters::new(CodecId::Srt));
559 s.language = Some("tur".into());
560 s.duration = Some(3_600_000);
561 assert_eq!(s.params.codec.media_type(), MediaType::Subtitle);
562 assert_eq!(s.index, 2);
563 assert_eq!(s.language.as_deref(), Some("tur"));
564 assert_eq!(s.rotation, Rotation::None);
565 }
566
567 #[test]
568 fn quarter_turn_matrices_read_as_typed_rotations() {
569 const ONE: i32 = 65_536; // 16.16 unity.
570 let cases = [
571 // A tkhd matrix and the turn it states, in this crate's clockwise
572 // convention. `(0, -1, 1, 0)` is what ffmpeg's
573 // `-display_rotation 90` writes: it asks the picture to be turned
574 // a quarter counter-clockwise here, which is Cw270.
575 ((ONE, 0, 0, ONE), Rotation::None),
576 ((0, -ONE, ONE, 0), Rotation::Cw270),
577 ((-ONE, 0, 0, -ONE), Rotation::Cw180),
578 ((0, ONE, -ONE, 0), Rotation::Cw90),
579 // A scaled identity is still no turn: the reading normalises by the
580 // matrix's own scale, so a differently-scaled copy reads the same.
581 ((2 * ONE, 0, 0, 2 * ONE), Rotation::None),
582 ];
583 for ((a, b, c, d), want) in cases {
584 assert_eq!(Rotation::from_matrix(a, b, c, d), want, "{a} {b} {c} {d}");
585 }
586 assert_eq!(Rotation::None.steps(), Some(0));
587 assert_eq!(Rotation::Cw90.steps(), Some(1));
588 assert_eq!(Rotation::Cw180.steps(), Some(2));
589 assert_eq!(Rotation::Cw270.steps(), Some(3));
590 assert!(Rotation::Cw90.swaps_axes() && Rotation::Cw270.swaps_axes());
591 assert!(!Rotation::None.swaps_axes() && !Rotation::Cw180.swaps_axes());
592 assert!(Rotation::None.is_none());
593 }
594
595 #[test]
596 fn a_matrix_that_is_not_a_quarter_turn_is_kept_not_rounded() {
597 const ONE: i32 = 65_536;
598 // A 45-degree turn: isotropic and pure, but no axis lands on an axis.
599 assert_eq!(
600 Rotation::from_matrix(46_340, -46_340, 46_340, 46_340),
601 Rotation::Other {
602 a: 46_340,
603 b: -46_340,
604 c: 46_340,
605 d: 46_340,
606 }
607 );
608 // A mirror (negative determinant), a mirror of a quarter turn (b != -c),
609 // a shear (a != d), and the degenerate all-zero matrix: none is a turn.
610 for (a, b, c, d) in [
611 (ONE, 0, 0, -ONE),
612 (0, ONE, ONE, 0),
613 (ONE, 0, ONE, ONE),
614 (0, 0, 0, 0),
615 ] {
616 let got = Rotation::from_matrix(a, b, c, d);
617 assert!(
618 matches!(got, Rotation::Other { .. }),
619 "{a} {b} {c} {d} read as {got:?}"
620 );
621 assert_eq!(got.steps(), None, "Other is not a quarter count");
622 }
623 }
624
625 #[test]
626 fn a_matrix_term_at_i32_min_is_not_a_quarter_turn() {
627 // A crafted `tkhd` can carry `i32::MIN`, whose negation is not
628 // representable. `from_matrix` must not panic (debug) or wrap onto a
629 // false turn (release) deciding `b == -c`, and such a term is no
630 // quarter turn anyway. `(0, MIN, MIN, 0)` is the load-bearing case: the
631 // wrapping form would read it as `Cw270`.
632 for (a, b, c, d) in [
633 (0, i32::MIN, i32::MIN, 0),
634 (65_536, i32::MIN, i32::MIN, 65_536),
635 (i32::MIN, 0, i32::MIN, i32::MIN),
636 ] {
637 let got = Rotation::from_matrix(a, b, c, d);
638 assert!(
639 matches!(got, Rotation::Other { .. }),
640 "{a} {b} {c} {d} read as {got:?}"
641 );
642 assert_eq!(got.steps(), None, "Other is not a quarter count");
643 }
644 }
645
646 #[test]
647 fn trait_objects_are_send() {
648 fn assert_send<T: Send + ?Sized>() {}
649 assert_send::<dyn Demuxer>();
650 assert_send::<dyn Muxer>();
651 assert_send::<dyn Decoder>();
652 assert_send::<dyn Encoder>();
653 assert_send::<Packet>();
654 assert_send::<Frame>();
655 }
656}