Skip to main content

grafton_ndi/
media.rs

1//! Media values shared by frames, packets, receivers and recorded files.
2
3use std::{
4    hash::{Hash, Hasher},
5    num::NonZeroU32,
6    ops::{BitOr, BitOrAssign},
7};
8
9use crate::{AudioFormat, Error, PixelFormat, Result};
10
11/// Maximum compressed frame size, in bytes, that the crate sends or accepts.
12pub const MAX_PACKET_BYTES: usize = 256 * 1024 * 1024;
13
14/// Maximum capacity, in bytes, for a single custom receive allocation.
15///
16/// This ceiling covers uncompressed [video](crate::frames::MAX_VIDEO_BYTES),
17/// uncompressed audio and [compressed packets](MAX_PACKET_BYTES).
18pub const MAX_ALLOCATION_BYTES: usize = {
19    let video = crate::frames::MAX_VIDEO_BYTES;
20    let audio = crate::frames::MAX_AUDIO_BYTES;
21    let uncompressed = if video > audio { video } else { audio };
22    if uncompressed > MAX_PACKET_BYTES {
23        uncompressed
24    } else {
25        MAX_PACKET_BYTES
26    }
27};
28
29// An omitted variant makes index() non-exhaustive; a duplicate cannot define
30// its index twice. Keep decoding and iteration tied to the same checked list.
31macro_rules! decoded_variants {
32    ($name:ident: $($variant:ident),+ $(,)?) => {
33        impl $name {
34            /// Every variant, in declaration order.
35            pub(crate) const ALL: [Self; [$(stringify!($variant)),+].len()] = const_assert!(@value {
36                let variants = [$(Self::$variant),+];
37                let mut index = 0;
38                while index < variants.len() {
39                    assert!(variants[index].index() == index);
40                    index += 1;
41                }
42                variants
43            });
44
45            const fn index(self) -> usize {
46                enum Index { $($variant),+ }
47                match self { $(Self::$variant => Index::$variant as usize),+ }
48            }
49        }
50
51    };
52}
53pub(crate) use decoded_variants;
54
55/// A positive quantity that fits the SDK's signed integer fields.
56/// Construction retains the range proof until the native conversion.
57#[derive(Clone, Copy, PartialEq, Eq, Hash)]
58pub(crate) struct SdkQuantity(NonZeroU32);
59
60// Keep the private range proof out of the public values' numeric Debug fields.
61impl std::fmt::Debug for SdkQuantity {
62    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
63        std::fmt::Debug::fmt(&self.0, f)
64    }
65}
66
67impl SdkQuantity {
68    pub(crate) const fn new(value: i64) -> Option<Self> {
69        // Explicit comparisons keep the shared predicate usable in const
70        // contexts on the minimum supported Rust version.
71        if value < 1 || value > i32::MAX as i64 {
72            return None;
73        }
74        match NonZeroU32::new(value as u32) {
75            Some(value) => Some(Self(value)),
76            None => None,
77        }
78    }
79
80    pub(crate) const fn get(self) -> u32 {
81        self.0.get()
82    }
83
84    pub(crate) const fn to_sdk(self) -> i32 {
85        // Lossless: construction proves the value is in 1..=i32::MAX.
86        self.get() as i32
87    }
88
89    pub(crate) const fn to_usize(self) -> usize {
90        self.get() as usize
91    }
92}
93
94const_assert!(std::mem::size_of::<Option<SdkQuantity>>() == 4);
95
96/// A frame rate in frames per second, as the fraction
97/// `numerator / denominator`.
98///
99/// Equality and hashing compare the rate: `30/1` and `60/2` are equal.
100/// The supplied numerator and denominator are preserved by the accessors and
101/// when submitted to the SDK. Compare both components explicitly when their
102/// exact representation matters.
103///
104/// # Examples
105///
106/// ```
107/// use grafton_ndi::FrameRate;
108///
109/// // NTSC: 29.97 frames per second.
110/// let ntsc = FrameRate::new(30_000, 1_001)?;
111/// assert_eq!((ntsc.numerator(), ntsc.denominator()), (30_000, 1_001));
112/// assert!(FrameRate::new(30, 0).is_err());
113/// # Ok::<(), grafton_ndi::Error>(())
114/// ```
115#[derive(Debug, Clone, Copy, Eq)]
116pub struct FrameRate {
117    numerator: SdkQuantity,
118    denominator: SdkQuantity,
119}
120
121/// The shared default for owned, borrowed and compressed video construction.
122pub(crate) const DEFAULT_VIDEO_FRAME_RATE: FrameRate = FrameRate::per_second(60);
123
124impl PartialEq for FrameRate {
125    fn eq(&self, other: &Self) -> bool {
126        // Each component is at most i32::MAX, so either product fits in u64.
127        u64::from(self.numerator.get()) * u64::from(other.denominator.get())
128            == u64::from(other.numerator.get()) * u64::from(self.denominator.get())
129    }
130}
131
132impl Hash for FrameRate {
133    fn hash<H: Hasher>(&self, state: &mut H) {
134        let (mut a, mut b) = (self.numerator.get(), self.denominator.get());
135        while b != 0 {
136            (a, b) = (b, a % b);
137        }
138        (self.numerator.get() / a, self.denominator.get() / a).hash(state);
139    }
140}
141
142impl FrameRate {
143    /// A frame rate of `numerator / denominator` frames per second.
144    ///
145    /// # Errors
146    ///
147    /// [`Error::InvalidInput`] unless both parts are in `1..=i32::MAX`, the
148    /// range the SDK can carry.
149    pub fn new(numerator: u32, denominator: u32) -> Result<Self> {
150        Self::checked(numerator.into(), denominator.into())
151            .map_err(|cause| Error::InvalidInput(crate::InputDefect::Layout(cause)))
152    }
153
154    /// `frames` frames per second, for the builders' defaults. Call it in a
155    /// `const` block, where a value outside `1..=i32::MAX` fails to compile.
156    pub(crate) const fn per_second(frames: u32) -> Self {
157        Self {
158            numerator: match SdkQuantity::new(frames as i64) {
159                Some(value) => value,
160                #[expect(
161                    clippy::panic,
162                    reason = "invalid frame-rate constants must fail during const evaluation"
163                )]
164                None => panic!("frame rate must be in 1..=i32::MAX"),
165            },
166            denominator: match SdkQuantity::new(1) {
167                Some(value) => value,
168                #[expect(
169                    clippy::unreachable,
170                    reason = "one is in the checked SDK quantity range"
171                )]
172                None => unreachable!(),
173            },
174        }
175    }
176
177    /// The frame rate of a frame the SDK delivered; an invalid one makes the
178    /// frame invalid.
179    pub(crate) fn from_sdk(numerator: i32, denominator: i32) -> Result<Self> {
180        Self::checked(numerator.into(), denominator.into()).map_err(Into::into)
181    }
182
183    /// The one frame-rate check, for values from the API and from the SDK.
184    /// The error is the reason, for the caller to report as its own variant.
185    fn checked(numerator: i64, denominator: i64) -> crate::frames::LayoutResult<Self> {
186        match (SdkQuantity::new(numerator), SdkQuantity::new(denominator)) {
187            (Some(numerator), Some(denominator)) => Ok(Self {
188                numerator,
189                denominator,
190            }),
191            _ => Err(crate::LayoutDefect::FrameRate {
192                detail: crate::CompactDiagnostic::new(crate::FrameRateDefect {
193                    numerator,
194                    denominator,
195                }),
196            }),
197        }
198    }
199
200    /// The number of frames in [`denominator`](Self::denominator) seconds.
201    #[must_use]
202    pub const fn numerator(self) -> u32 {
203        self.numerator.get()
204    }
205
206    /// The number of seconds that [`numerator`](Self::numerator) frames take.
207    #[must_use]
208    pub const fn denominator(self) -> u32 {
209        self.denominator.get()
210    }
211
212    /// The SDK's `frame_rate_N` and `frame_rate_D` fields.
213    pub(crate) const fn to_sdk(self) -> (i32, i32) {
214        (self.numerator.to_sdk(), self.denominator.to_sdk())
215    }
216}
217
218/// The displayed picture's width divided by its height.
219///
220/// Zero asks the SDK to derive the ratio from the frame dimensions (square
221/// pixels). Every other value is finite and positive.
222#[derive(Debug, Clone, Copy, PartialEq)]
223pub struct PictureAspectRatio(f32);
224
225impl Eq for PictureAspectRatio {}
226
227impl Hash for PictureAspectRatio {
228    fn hash<H: Hasher>(&self, state: &mut H) {
229        self.0.to_bits().hash(state);
230    }
231}
232
233impl PictureAspectRatio {
234    /// Derive the displayed aspect ratio from the pixel dimensions.
235    pub const SQUARE_PIXELS: Self = Self(0.0);
236
237    /// A finite, nonnegative ratio; zero means square pixels.
238    ///
239    /// # Errors
240    ///
241    /// [`Error::InvalidInput`] when `ratio` is negative or not finite.
242    pub fn new(ratio: f32) -> Result<Self> {
243        Self::checked(ratio)
244            .map_err(|reason| Error::InvalidInput(crate::InputDefect::Layout(reason)))
245    }
246
247    /// The ratio, with zero representing square pixels.
248    #[must_use]
249    pub const fn get(self) -> f32 {
250        self.0
251    }
252
253    pub(crate) fn from_sdk(ratio: f32) -> Result<Self> {
254        Self::checked(ratio).map_err(Into::into)
255    }
256
257    pub(crate) const fn to_sdk(self) -> f32 {
258        self.0
259    }
260
261    fn checked(ratio: f32) -> crate::frames::LayoutResult<Self> {
262        if !ratio.is_finite() || ratio < 0.0 {
263            return Err(crate::LayoutDefect::PictureAspectRatio(ratio));
264        }
265        // Equality treats both zeros alike; store one bit pattern for hashing.
266        Ok(Self(if ratio == 0.0 { 0.0 } else { ratio }))
267    }
268}
269
270/// A four-character code: the SDK's identifier for a pixel or audio format or codec.
271///
272/// It holds any value, including one this crate does not know, so a value
273/// read from the SDK is never lost. [`PixelFormat`] and [`AudioFormat`] convert
274/// to and from it.
275///
276/// # Examples
277///
278/// ```
279/// use grafton_ndi::{FourCc, PixelFormat};
280///
281/// let fourcc = FourCc::from(PixelFormat::Uyvy);
282/// assert_eq!(fourcc.raw().to_le_bytes(), *b"UYVY");
283/// assert_eq!(PixelFormat::try_from(fourcc)?, PixelFormat::Uyvy);
284/// assert!(PixelFormat::try_from(FourCc::from_raw(u32::from_le_bytes(*b"V210"))).is_err());
285/// # Ok::<(), grafton_ndi::Error>(())
286/// ```
287#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
288pub struct FourCc(u32);
289
290impl FourCc {
291    /// The code with the SDK's numeric value `value`: its four characters in
292    /// little-endian byte order.
293    #[must_use]
294    pub const fn from_raw(value: u32) -> Self {
295        Self(value)
296    }
297
298    /// The SDK's numeric value.
299    #[must_use]
300    pub const fn raw(self) -> u32 {
301        self.0
302    }
303}
304
305impl From<PixelFormat> for FourCc {
306    fn from(format: PixelFormat) -> Self {
307        // Each variant's discriminant is the SDK's FourCC value.
308        Self(format as u32)
309    }
310}
311
312impl PixelFormat {
313    /// Decode an uncompressed format without allocating for an unknown FourCC.
314    pub(crate) fn from_fourcc(fourcc: FourCc) -> Option<Self> {
315        Self::ALL
316            .into_iter()
317            .find(|&format| FourCc::from(format) == fourcc)
318    }
319}
320
321impl TryFrom<FourCc> for PixelFormat {
322    type Error = Error;
323
324    /// The pixel format `fourcc` names.
325    ///
326    /// # Errors
327    ///
328    /// [`Error::InvalidFrame`] when it names no uncompressed pixel format
329    /// this crate supports.
330    fn try_from(fourcc: FourCc) -> Result<Self> {
331        Self::from_fourcc(fourcc).ok_or({
332            Error::InvalidFrame(crate::FrameDefect::UnknownPixelFormat { fourcc: fourcc.0 })
333        })
334    }
335}
336
337impl From<AudioFormat> for FourCc {
338    fn from(format: AudioFormat) -> Self {
339        Self(format.to_sdk())
340    }
341}
342
343impl TryFrom<FourCc> for AudioFormat {
344    type Error = Error;
345
346    /// The audio format `fourcc` names.
347    ///
348    /// # Errors
349    ///
350    /// [`Error::InvalidFrame`] when it names no uncompressed audio format
351    /// this crate supports.
352    fn try_from(fourcc: FourCc) -> Result<Self> {
353        Self::ALL
354            .into_iter()
355            .find(|&format| FourCc::from(format) == fourcc)
356            .ok_or(Error::InvalidFrame(
357                crate::FrameDefect::UnknownAudioFormat {
358                    fourcc: fourcc.raw(),
359                },
360            ))
361    }
362}
363
364/// Which of a source's two video streams: the full-quality program stream or
365/// the low-bandwidth preview stream.
366///
367/// A source can send both. A receiver takes its video from one of them, a
368/// compressed frame belongs to one of them, and a recorded file holds a track
369/// of each it recorded.
370#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
371pub enum StreamTier {
372    /// The full-quality program stream.
373    Program,
374    /// The low-bandwidth preview stream.
375    Preview,
376}
377
378/// A set of media types: any combination of [`VIDEO`](Self::VIDEO),
379/// [`AUDIO`](Self::AUDIO) and [`METADATA`](Self::METADATA).
380///
381/// # Examples
382///
383/// ```
384/// use grafton_ndi::MediaTypes;
385///
386/// let mut types = MediaTypes::VIDEO | MediaTypes::METADATA;
387/// assert!(types.contains(MediaTypes::VIDEO));
388/// assert!(!types.contains(MediaTypes::AUDIO));
389/// types |= MediaTypes::AUDIO;
390/// assert_eq!(types, MediaTypes::ALL);
391/// assert!(MediaTypes::NONE.is_empty());
392/// ```
393#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
394pub struct MediaTypes(u8);
395
396impl MediaTypes {
397    /// No media type.
398    pub const NONE: Self = Self(0);
399    /// Video.
400    pub const VIDEO: Self = Self(1);
401    /// Audio.
402    pub const AUDIO: Self = Self(1 << 1);
403    /// Metadata.
404    pub const METADATA: Self = Self(1 << 2);
405    /// Video, audio and metadata.
406    pub const ALL: Self = Self(Self::VIDEO.0 | Self::AUDIO.0 | Self::METADATA.0);
407
408    /// Whether every type in `other` is in this set.
409    #[must_use]
410    pub const fn contains(self, other: Self) -> bool {
411        self.0 & other.0 == other.0
412    }
413
414    /// Whether the set has no type in it.
415    #[must_use]
416    pub const fn is_empty(self) -> bool {
417        self.0 == 0
418    }
419}
420
421impl BitOr for MediaTypes {
422    type Output = Self;
423
424    fn bitor(self, other: Self) -> Self {
425        Self(self.0 | other.0)
426    }
427}
428
429impl BitOrAssign for MediaTypes {
430    fn bitor_assign(&mut self, other: Self) {
431        self.0 |= other.0;
432    }
433}
434
435#[cfg(test)]
436mod tests {
437    use super::*;
438
439    /// Compile the private const constructor itself, so rejection cannot be
440    /// satisfied accidentally by a visibility or non-const-call error.
441    #[test]
442    #[cfg(not(miri))]
443    fn constant_frame_rates_reject_zero() {
444        fn declaration<'a>(source: &'a str, marker: &str) -> &'a str {
445            let source = &source[source.find(marker).unwrap()..];
446            let mut depth = 0;
447            for (index, byte) in source.bytes().enumerate() {
448                match byte {
449                    b'{' => depth += 1,
450                    b'}' => {
451                        depth -= 1;
452                        if depth == 0 {
453                            return &source[..=index];
454                        }
455                    }
456                    _ => {}
457                }
458            }
459            panic!("unterminated declaration: {marker}")
460        }
461        let source = include_str!("media.rs");
462        let quantity = declaration(source, "impl SdkQuantity {");
463        let rate = declaration(source, "pub struct FrameRate {");
464        let per_second = declaration(source, "pub(crate) const fn per_second(");
465        let fixture = include_str!("../tests/ui/internal/fail/frame_rate_zero_const.rs");
466        let definitions = format!(
467            "#![allow(dead_code)]\nuse std::num::NonZeroU32;\n\
468             struct SdkQuantity(NonZeroU32);\n{quantity}\n{rate}\n\
469             impl FrameRate {{ {per_second} }}\n"
470        );
471        let directory = crate::test_support::FixtureDir::create("const-frame-rate");
472        for (name, fixture, succeeds) in [
473            (
474                "positive",
475                fixture.replace("per_second(0)", "per_second(1)"),
476                true,
477            ),
478            ("zero", fixture.to_owned(), false),
479        ] {
480            let path = directory.join(format!("{name}.rs"));
481            std::fs::write(&path, format!("{definitions}\n{fixture}")).unwrap();
482            let output = std::process::Command::new("rustc")
483                .args(["--edition=2021", "--emit=metadata", "--out-dir"])
484                .arg(directory.path())
485                .arg(path)
486                .output()
487                .unwrap();
488            let error = String::from_utf8(output.stderr).unwrap();
489            assert_eq!(output.status.success(), succeeds, "{name}: {error}");
490            if !succeeds {
491                assert!(error.contains("E0080"), "{error}");
492            }
493        }
494    }
495
496    #[test]
497    fn sdk_quantities_preserve_exactly_the_signed_positive_range() {
498        const ONE: SdkQuantity = SdkQuantity::new(1).unwrap();
499        const MAX: SdkQuantity = SdkQuantity::new(i32::MAX as i64).unwrap();
500        const DEFAULT: FrameRate = FrameRate::per_second(60);
501        assert_eq!((ONE.get(), ONE.to_sdk(), ONE.to_usize()), (1, 1, 1));
502        assert_eq!(MAX.to_sdk(), i32::MAX);
503        assert_eq!(DEFAULT.to_sdk(), (60, 1));
504        assert_eq!(
505            format!("{DEFAULT:?}"),
506            "FrameRate { numerator: 60, denominator: 1 }"
507        );
508        for value in [
509            i64::MIN,
510            -1,
511            0,
512            i32::MAX as i64 + 1,
513            u32::MAX as i64,
514            i64::MAX,
515        ] {
516            assert_eq!(SdkQuantity::new(value), None, "{value}");
517        }
518        for value in [1, 48_000, i32::MAX as i64] {
519            let quantity = SdkQuantity::new(value).unwrap();
520            assert_eq!(i64::from(quantity.get()), value);
521            assert_eq!(i64::from(quantity.to_sdk()), value);
522            assert_eq!(quantity.to_usize() as u64, value as u64);
523        }
524        for value in [0, i32::MAX as u32 + 1, u32::MAX] {
525            assert!(std::panic::catch_unwind(|| FrameRate::per_second(value)).is_err());
526        }
527    }
528
529    #[test]
530    fn picture_aspect_ratio_accepts_only_finite_nonnegative_values() {
531        assert_eq!(PictureAspectRatio::SQUARE_PIXELS.get(), 0.0);
532        for value in [0.0, -0.0, 1.0, 16.0 / 9.0, f32::MAX] {
533            let ratio = PictureAspectRatio::new(value).unwrap();
534            assert_eq!(
535                ratio.get().to_bits(),
536                if value == 0.0 {
537                    0.0f32.to_bits()
538                } else {
539                    value.to_bits()
540                }
541            );
542            assert_eq!(PictureAspectRatio::from_sdk(ratio.to_sdk()).unwrap(), ratio);
543        }
544        for value in [-1.0, f32::NEG_INFINITY, f32::INFINITY, f32::NAN] {
545            assert!(matches!(
546                PictureAspectRatio::new(value),
547                Err(Error::InvalidInput(_))
548            ));
549            assert!(matches!(
550                PictureAspectRatio::from_sdk(value),
551                Err(Error::InvalidFrame(_))
552            ));
553        }
554    }
555
556    #[test]
557    fn picture_aspect_ratio_equality_and_hashing_share_canonical_zero() {
558        let zero = PictureAspectRatio::new(0.0).unwrap();
559        let negative_zero = PictureAspectRatio::new(-0.0).unwrap();
560        assert_eq!(negative_zero.get().to_bits(), 0.0f32.to_bits());
561        let values = std::collections::HashSet::from([zero, negative_zero]);
562        assert_eq!(values.len(), 1);
563        for value in [0.0, 1.0, 16.0 / 9.0, f32::MAX] {
564            assert_eq!(
565                PictureAspectRatio::new(value).unwrap(),
566                PictureAspectRatio::new(value).unwrap()
567            );
568        }
569        assert_ne!(zero, PictureAspectRatio::new(1.0).unwrap());
570    }
571
572    #[test]
573    fn every_audio_format_round_trips_through_its_fourcc() {
574        for format in AudioFormat::ALL {
575            let fourcc = FourCc::from(format);
576            assert_eq!(AudioFormat::try_from(fourcc).unwrap(), format);
577        }
578        assert_eq!(
579            FourCc::from(AudioFormat::Fltp).raw().to_le_bytes(),
580            *b"FLTp"
581        );
582        let unknown = FourCc::from_raw(u32::MAX);
583        assert!(
584            matches!(AudioFormat::try_from(unknown), Err(Error::InvalidFrame(crate::FrameDefect::UnknownAudioFormat { fourcc })) if fourcc == unknown.raw())
585        );
586    }
587
588    #[test]
589    fn frame_rate_accepts_exactly_the_sdk_range_from_both_sides() {
590        let max = i32::MAX.unsigned_abs();
591        for (numerator, denominator, valid) in [
592            (1, 1, true),
593            (30_000, 1_001, true),
594            (max, max, true),
595            (0, 1, false),
596            (1, 0, false),
597            (max + 1, 1, false),
598            (1, u32::MAX, false),
599        ] {
600            let rate = FrameRate::new(numerator, denominator);
601            assert_eq!(rate.is_ok(), valid, "{numerator}/{denominator}");
602            if let Ok(rate) = rate {
603                assert_eq!(
604                    (rate.numerator(), rate.denominator()),
605                    (numerator, denominator)
606                );
607                let (n, d) = rate.to_sdk();
608                assert_eq!(FrameRate::from_sdk(n, d).unwrap(), rate);
609            }
610        }
611        for (numerator, denominator) in [(-1, 1), (1, -1), (0, 0), (i32::MIN, i32::MIN)] {
612            assert!(matches!(
613                FrameRate::from_sdk(numerator, denominator),
614                Err(Error::InvalidFrame(message)) if matches!(&message, crate::FrameDefect::Layout(crate::LayoutDefect::FrameRate {detail}) if detail.numerator==i64::from(numerator) && detail.denominator==i64::from(denominator))
615            ));
616        }
617    }
618
619    #[test]
620    fn equivalent_frame_rates_compare_and_hash_equally_without_losing_components() {
621        use std::collections::{HashMap, HashSet};
622        let rate = |n, d| FrameRate::new(n, d).unwrap();
623        let max = i32::MAX as u32;
624        for (left, right) in [
625            (rate(30, 1), rate(60, 2)),
626            (rate(30_000, 1001), rate(60_000, 2002)),
627            (rate(1, 1), rate(max, max)),
628        ] {
629            assert_eq!(left, right);
630            assert_eq!(HashSet::from([left, right]).len(), 1);
631            assert_eq!(HashMap::from([(left, "rate")]).get(&right), Some(&"rate"));
632        }
633        assert_ne!(rate(30, 1), rate(30_000, 1001));
634        assert_ne!(rate(max, max - 1), rate(max - 1, max - 2));
635        assert_eq!(
636            (rate(60, 2).numerator(), rate(60, 2).denominator()),
637            (60, 2)
638        );
639        assert_eq!(rate(60, 2).to_sdk(), (60, 2));
640        assert_eq!(FrameRate::from_sdk(60, 2).unwrap().to_sdk(), (60, 2));
641    }
642
643    #[test]
644    fn every_pixel_format_round_trips_through_its_fourcc() {
645        for format in PixelFormat::ALL {
646            let fourcc = FourCc::from(format);
647            assert_eq!(PixelFormat::try_from(fourcc).unwrap(), format);
648            assert!(fourcc
649                .raw()
650                .to_le_bytes()
651                .iter()
652                .all(u8::is_ascii_alphanumeric));
653        }
654        assert_eq!(
655            FourCc::from(PixelFormat::Nb4g).raw().to_le_bytes(),
656            *b"NB4G"
657        );
658        let v210 = FourCc::from_raw(u32::from_le_bytes(*b"V210"));
659        assert!(matches!(
660            PixelFormat::try_from(v210),
661            Err(Error::InvalidFrame(message)) if matches!(message, crate::FrameDefect::UnknownPixelFormat {fourcc} if fourcc==v210.raw())
662        ));
663    }
664
665    #[test]
666    fn every_scan_type_round_trips_through_its_sdk_code() {
667        for scan in crate::ScanType::ALL {
668            assert_eq!(crate::ScanType::from_sdk(scan.to_sdk()), Some(scan));
669        }
670        assert_eq!(crate::ScanType::from_sdk(u32::MAX), None);
671    }
672
673    #[test]
674    fn media_types_combine_as_a_set() {
675        let singles = [MediaTypes::VIDEO, MediaTypes::AUDIO, MediaTypes::METADATA];
676        for (index, single) in singles.into_iter().enumerate() {
677            assert!(!single.is_empty());
678            assert!(MediaTypes::ALL.contains(single));
679            assert!(!MediaTypes::NONE.contains(single));
680            for (other_index, other) in singles.into_iter().enumerate() {
681                assert_eq!(single.contains(other), index == other_index);
682            }
683        }
684        let mut all = MediaTypes::NONE;
685        for single in singles {
686            all |= single;
687        }
688        assert_eq!(all, MediaTypes::ALL);
689        assert_eq!(
690            MediaTypes::VIDEO | MediaTypes::AUDIO | MediaTypes::METADATA,
691            MediaTypes::ALL
692        );
693        assert!(MediaTypes::NONE.is_empty());
694        assert!(MediaTypes::ALL.contains(MediaTypes::NONE));
695        assert!(!(MediaTypes::VIDEO | MediaTypes::AUDIO).contains(MediaTypes::ALL));
696    }
697}