Skip to main content

grafton_ndi/advanced/
packets.rs

1//! Compressed frames and the packet envelope that frames H.264, HEVC and AAC
2//! payloads on the wire.
3
4use std::{ffi::c_char, num::NonZeroU32};
5
6use super::{descriptors, invalid_frame};
7
8#[path = "packets/payload.rs"]
9mod payload;
10use crate::media::SdkQuantity;
11use crate::{
12    frames::{FrameMetadataRef, OwnedFrameMetadata, VideoHeader},
13    sys::bindings::*,
14    Error, FourCc, FrameRate, PictureAspectRatio, ReceivedTimestamp, Rejected, Result, ScanType,
15    StreamTier, Timecode,
16};
17pub(crate) use payload::{PacketBytes, PacketSlice};
18
19pub use crate::media::MAX_PACKET_BYTES;
20
21const_assert!(MAX_PACKET_BYTES <= i32::MAX as usize);
22
23/// A nonempty packet extent, retained until its SDK descriptor is built.
24#[derive(Clone, Copy, Debug, PartialEq, Eq)]
25#[repr(transparent)]
26pub(crate) struct PacketLen(NonZeroU32);
27
28impl PacketLen {
29    pub(crate) fn new(bytes: usize) -> Option<Self> {
30        if !(1..=MAX_PACKET_BYTES).contains(&bytes) {
31            return None;
32        }
33        NonZeroU32::new(u32::try_from(bytes).ok()?).map(Self)
34    }
35
36    pub(crate) fn checked_add(self, other: Self) -> Option<Self> {
37        self.to_usize()
38            .checked_add(other.to_usize())
39            .and_then(Self::new)
40    }
41
42    pub(crate) fn from_sdk(bytes: i32) -> Option<Self> {
43        usize::try_from(bytes).ok().and_then(Self::new)
44    }
45
46    pub(crate) fn to_usize(self) -> usize {
47        self.0.get() as usize
48    }
49
50    pub(crate) fn to_sdk(self) -> i32 {
51        // Construction and the const assertion prove this conversion lossless.
52        self.0.get().cast_signed()
53    }
54
55    fn to_u32(self) -> u32 {
56        self.0.get()
57    }
58}
59
60/// Size in bytes of the version-0 envelope header.
61pub(crate) const ENVELOPE_HEADER_BYTES: usize = 44;
62
63/// Set in every byte of the FourCC of a protected stream.
64pub(crate) const PROTECTED: u32 = 0x8080_8080;
65
66/// The envelope flag that marks a keyframe.
67const KEYFRAME: u32 = 1;
68
69/// Size in bytes of the header that begins a SpeedHQ frame.
70const SPEEDHQ_HEADER_BYTES: usize = 4;
71
72/// One more than the largest quality the first byte of a SpeedHQ frame states.
73const SPEEDHQ_QUALITY_LIMIT: u8 = 100;
74
75/// The largest width and height of an H.264 or HEVC picture on the preview
76/// stream.
77const MAX_PREVIEW_DIMENSION: u32 = 640;
78
79// Byte offsets of the envelope header fields.
80const VERSION_OFFSET: usize = 0;
81const CODEC_OFFSET: usize = 4;
82const PTS_OFFSET: usize = 8;
83const DTS_OFFSET: usize = 16;
84const RESERVED_OFFSET: usize = 24;
85const FLAGS_OFFSET: usize = 32;
86const DATA_SIZE_OFFSET: usize = 36;
87const EXTRA_DATA_SIZE_OFFSET: usize = 40;
88
89const fn fourcc(bytes: &[u8; 4]) -> u32 {
90    u32::from_le_bytes(*bytes)
91}
92
93/// `N` bytes of `bytes` starting at `offset`. The caller has checked the length.
94fn field<const N: usize>(bytes: &[u8], offset: usize) -> [u8; N] {
95    let mut value = [0; N];
96    value.copy_from_slice(&bytes[offset..offset + N]);
97    value
98}
99
100/// A compressed video codec.
101///
102/// The codec, the [`StreamTier`] and stream protection together select the
103/// FourCC a frame is sent with.
104///
105/// # Delivery
106///
107/// The SDK takes any compressed video frame and silently discards the ones it
108/// does not accept, so this module refuses to build or send those:
109///
110/// * A SpeedHQ frame begins with its quality, a byte below 100.
111/// * An H.264 or HEVC picture on the preview stream is at most 640 pixels
112///   wide and 640 high.
113///
114/// Which frames reach a receiver also depends on the order they are sent in;
115/// see [`CompressedSender`](super::CompressedSender).
116#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
117#[non_exhaustive]
118pub enum VideoCodec {
119    /// SpeedHQ 4:2:0.
120    SpeedHq420,
121    /// SpeedHQ 4:2:2.
122    SpeedHq422,
123    /// SpeedHQ 4:2:2 with alpha.
124    SpeedHq422Alpha,
125    /// H.264 in a packet envelope.
126    H264,
127    /// HEVC in a packet envelope.
128    Hevc,
129    /// H.264 with alpha in a packet envelope.
130    H264Alpha,
131    /// HEVC with alpha in a packet envelope.
132    HevcAlpha,
133}
134
135crate::media::decoded_variants!(VideoCodec:
136    SpeedHq420, SpeedHq422, SpeedHq422Alpha, H264, Hevc, H264Alpha, HevcAlpha,
137);
138
139impl VideoCodec {
140    /// The FourCC a frame of this codec is sent with.
141    pub(crate) const fn outer(self, tier: StreamTier, protected: bool) -> u32 {
142        let bytes = match (self, tier) {
143            (Self::SpeedHq420, StreamTier::Program) => b"SHQ0",
144            (Self::SpeedHq420, StreamTier::Preview) => b"shq0",
145            (Self::SpeedHq422, StreamTier::Program) => b"SHQ2",
146            (Self::SpeedHq422, StreamTier::Preview) => b"shq2",
147            (Self::SpeedHq422Alpha, StreamTier::Program) => b"SHQ7",
148            (Self::SpeedHq422Alpha, StreamTier::Preview) => b"shq7",
149            (Self::H264, StreamTier::Program) => b"H264",
150            (Self::H264, StreamTier::Preview) => b"h264",
151            (Self::Hevc, StreamTier::Program) => b"HEVC",
152            (Self::Hevc, StreamTier::Preview) => b"hevc",
153            (Self::H264Alpha, StreamTier::Program) => b"A264",
154            (Self::H264Alpha, StreamTier::Preview) => b"a264",
155            (Self::HevcAlpha, StreamTier::Program) => b"AEVC",
156            (Self::HevcAlpha, StreamTier::Preview) => b"aevc",
157        };
158        fourcc(bytes) | if protected { PROTECTED } else { 0 }
159    }
160
161    /// The codec, tier and protection a frame FourCC names, if it is compressed
162    /// video this module knows.
163    pub(crate) fn from_outer(value: u32) -> Option<(Self, StreamTier, bool)> {
164        let protected = value & PROTECTED == PROTECTED;
165        Self::ALL.into_iter().find_map(|codec| {
166            [StreamTier::Program, StreamTier::Preview]
167                .into_iter()
168                .find(|tier| value == codec.outer(*tier, protected))
169                .map(|tier| (codec, tier, protected))
170        })
171    }
172
173    /// The envelope codec that frames this codec's payload. SpeedHQ frames
174    /// have no envelope.
175    pub fn envelope_codec(self) -> Option<EnvelopeCodec> {
176        match self {
177            Self::H264 | Self::H264Alpha => Some(EnvelopeCodec::H264),
178            Self::Hevc | Self::HevcAlpha => Some(EnvelopeCodec::Hevc),
179            Self::SpeedHq420 | Self::SpeedHq422 | Self::SpeedHq422Alpha => None,
180        }
181    }
182}
183
184/// A codec whose payload travels inside a packet envelope.
185#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
186#[non_exhaustive]
187pub enum EnvelopeCodec {
188    /// H.264 video.
189    H264,
190    /// HEVC video.
191    Hevc,
192    /// AAC audio.
193    Aac,
194}
195
196crate::media::decoded_variants!(EnvelopeCodec: H264, Hevc, Aac);
197
198impl EnvelopeCodec {
199    const fn raw_fourcc(self) -> u32 {
200        match self {
201            Self::H264 => fourcc(b"H264"),
202            Self::Hevc => fourcc(b"HEVC"),
203            Self::Aac => 0xff,
204        }
205    }
206}
207
208impl From<EnvelopeCodec> for FourCc {
209    /// The FourCC carried by the codec's envelope header.
210    fn from(codec: EnvelopeCodec) -> Self {
211        Self::from_raw(codec.raw_fourcc())
212    }
213}
214
215impl TryFrom<FourCc> for EnvelopeCodec {
216    type Error = Error;
217
218    /// Decode a packet-envelope codec from its FourCC.
219    ///
220    /// # Errors
221    ///
222    /// [`Error::InvalidFrame`] when the FourCC names no supported envelope codec.
223    fn try_from(fourcc: FourCc) -> Result<Self> {
224        Self::ALL
225            .into_iter()
226            .find(|&codec| FourCc::from(codec) == fourcc)
227            .ok_or_else(|| {
228                invalid_frame(crate::FrameDefect::UnknownEnvelopeCodec {
229                    fourcc: fourcc.raw(),
230                })
231            })
232    }
233}
234
235/// The extents established when an envelope is admitted.
236#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
237pub(crate) struct EnvelopeExtents {
238    size: usize,
239    data_len: usize,
240    extra_len: usize,
241}
242
243impl EnvelopeExtents {
244    fn checked_end(self) -> Option<usize> {
245        self.size
246            .checked_add(self.data_len)?
247            .checked_add(self.extra_len)
248    }
249
250    fn check_extent(self, total: usize) -> Result<usize> {
251        let end = self
252            .checked_end()
253            .ok_or_else(|| invalid_frame(crate::FrameDefect::PacketLengthOverflow))?;
254        if end > total {
255            return Err(invalid_frame(crate::FrameDefect::PacketTruncated));
256        }
257        Ok(end)
258    }
259
260    fn extra_offset(self) -> usize {
261        self.size + self.data_len
262    }
263}
264
265/// The fields that decide whether an envelope is admissible.
266struct EnvelopeHeader {
267    extents: EnvelopeExtents,
268    codec: FourCc,
269    flags: u32,
270}
271
272impl EnvelopeHeader {
273    /// Read the header at the start of `bytes`.
274    fn read(bytes: &[u8]) -> Result<Self> {
275        if bytes.len() < ENVELOPE_HEADER_BYTES {
276            return Err(invalid_frame(crate::FrameDefect::PacketHeaderTruncated));
277        }
278        let size = usize::try_from(i32::from_ne_bytes(field(bytes, VERSION_OFFSET)))
279            .ok()
280            .filter(|size| *size >= ENVELOPE_HEADER_BYTES)
281            .ok_or_else(|| invalid_frame(crate::FrameDefect::PacketHeaderSize))?;
282        Ok(Self {
283            extents: EnvelopeExtents {
284                size,
285                data_len: u32::from_ne_bytes(field(bytes, DATA_SIZE_OFFSET)) as usize,
286                extra_len: u32::from_ne_bytes(field(bytes, EXTRA_DATA_SIZE_OFFSET)) as usize,
287            },
288            codec: FourCc::from_raw(u32::from_ne_bytes(field(bytes, CODEC_OFFSET))),
289            flags: u32::from_ne_bytes(field(bytes, FLAGS_OFFSET)),
290        })
291    }
292
293    fn is_keyframe(&self) -> bool {
294        self.flags & KEYFRAME != 0
295    }
296
297    /// Check the codec, payload and declared lengths once for every container.
298    /// Sending additionally requires the current header version, known flags
299    /// and lengths that account for every byte. Receiving retains extensions
300    /// and trailing bytes without loss.
301    ///
302    /// The reserved field takes no part. It belongs to the SDK, which
303    /// overwrites it in every packet it sends, so a packet that has been sent
304    /// or received carries whatever the SDK left there.
305    fn validate(
306        &self,
307        codec: EnvelopeCodec,
308        total: usize,
309        purpose: Use,
310    ) -> Result<EnvelopeExtents> {
311        if purpose == Use::Send
312            && (self.extents.size != ENVELOPE_HEADER_BYTES || self.flags & !KEYFRAME != 0)
313        {
314            return Err(invalid_frame(crate::FrameDefect::PacketHeaderUnsupported));
315        }
316        if self.codec != FourCc::from(codec) {
317            return Err(invalid_frame(crate::FrameDefect::PacketCodecMismatch));
318        }
319        if self.extents.data_len == 0 {
320            return Err(invalid_frame(crate::FrameDefect::EmptyCodecPayload));
321        }
322        let declared = self.extents.check_extent(total)?;
323        if purpose == Use::Send && declared < total {
324            return Err(invalid_frame(crate::FrameDefect::PacketLengthsMismatch));
325        }
326        Ok(self.extents)
327    }
328
329    /// Check the codec configuration of a video packet that is about to be
330    /// sent: a decoder cannot start on a keyframe without its parameter sets.
331    pub(crate) fn validate_video_configuration(&self) -> Result<()> {
332        if self.is_keyframe() && self.extents.extra_len == 0 {
333            return Err(invalid_frame(
334                crate::FrameDefect::KeyframeConfigurationMissing,
335            ));
336        }
337        Ok(())
338    }
339
340    /// Check what the SDK needs of an AAC packet to deliver it as audio with
341    /// `parameters`. `config` is the first two bytes of the packet's codec
342    /// configuration, when it has that many.
343    ///
344    /// The SDK reads the sample rate and the channel layout from those bytes,
345    /// where an AudioSpecificConfig keeps them, and discards a packet whose
346    /// frame says otherwise.
347    pub(crate) fn validate_aac(
348        &self,
349        config: Option<[u8; 2]>,
350        parameters: AudioPacketFormat,
351    ) -> Result<()> {
352        if !self.is_keyframe() {
353            return Err(invalid_frame(crate::FrameDefect::AacKeyframeMissing));
354        }
355        let Some(config) = config else {
356            return Err(invalid_frame(crate::FrameDefect::AacConfigurationMissing));
357        };
358        // Five bits of object type, four of sampling-frequency index, four of
359        // channel configuration.
360        let bits = u16::from_be_bytes(config);
361        let frequency_index = usize::from((bits >> 7) & 0xf);
362        let channel_configuration = usize::from((bits >> 3) & 0xf);
363        if AAC_SAMPLE_RATES.get(frequency_index) != Some(&parameters.sample_rate()) {
364            return Err(invalid_frame(crate::FrameDefect::AacRateMismatch));
365        }
366        if channel_configuration
367            .checked_sub(1)
368            .and_then(|index| AAC_CHANNELS.get(index))
369            != Some(&parameters.num_channels())
370        {
371            return Err(invalid_frame(crate::FrameDefect::AacChannelsMismatch));
372        }
373        Ok(())
374    }
375}
376
377/// A bounds-checked view of a packet envelope: its header, codec payload and
378/// codec configuration data. [`encode`](Self::encode) builds one.
379///
380/// Parsing keeps what it does not understand. Flags, the reserved field and
381/// header bytes added by a later envelope version are all readable, so a
382/// received packet can be inspected or stored without loss.
383#[derive(Clone, Copy, PartialEq, Eq, Hash)]
384pub struct PacketEnvelope<'a> {
385    bytes: &'a [u8],
386    extents: EnvelopeExtents,
387}
388
389impl std::fmt::Debug for PacketEnvelope<'_> {
390    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
391        f.debug_struct("PacketEnvelope")
392            .field("codec", &self.codec())
393            .field("fourcc", &self.fourcc())
394            .field("presentation_time", &self.presentation_time())
395            .field("decode_time", &self.decode_time())
396            .field("keyframe", &self.is_keyframe())
397            .field("flags", &self.flags())
398            .field("known_version", &self.is_known_version())
399            .field("header_extension_bytes", &self.header_extension().len())
400            .field("payload_bytes", &self.data().len())
401            .field("configuration_bytes", &self.extra_data().len())
402            .field("trailing_bytes", &self.trailing_bytes().len())
403            .finish()
404    }
405}
406
407impl<'a> PacketEnvelope<'a> {
408    /// View bytes with the extents their containing packet validated.
409    fn from_validated(bytes: &'a [u8], extents: EnvelopeExtents) -> Self {
410        Self { bytes, extents }
411    }
412
413    /// Parse `bytes` as one packet envelope.
414    ///
415    /// # Errors
416    ///
417    /// [`Error::InvalidFrame`] when the slice is shorter than a header, longer
418    /// than [`MAX_PACKET_BYTES`], or shorter than the lengths its header
419    /// declares.
420    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
421        PacketLen::new(bytes.len()).ok_or_else(|| {
422            invalid_frame(if bytes.is_empty() {
423                crate::FrameDefect::PacketHeaderTruncated
424            } else {
425                crate::FrameDefect::PacketLength
426            })
427        })?;
428        let extents = EnvelopeHeader::read(bytes)?.extents;
429        extents.check_extent(bytes.len())?;
430        Ok(Self::from_validated(bytes, extents))
431    }
432
433    /// Build a version-0 packet envelope around one codec payload.
434    ///
435    /// `presentation_time` and `decode_time` are in the stream's own units.
436    /// `keyframe` marks a video keyframe; AAC has no other kind of packet, so
437    /// an AAC envelope carries the flag whatever `keyframe` says. `extra_data`
438    /// is the codec configuration (parameter sets for H.264 and HEVC, the
439    /// AudioSpecificConfig for AAC); video keyframes and every AAC packet need
440    /// it to be sendable.
441    ///
442    /// # Errors
443    ///
444    /// [`Error::InvalidFrame`] when `data` is empty or the packet would exceed
445    /// [`MAX_PACKET_BYTES`].
446    ///
447    /// # Examples
448    ///
449    /// ```
450    /// use grafton_ndi::advanced::{EnvelopeCodec, PacketEnvelope};
451    ///
452    /// let packet = PacketEnvelope::encode(EnvelopeCodec::H264, 0, 0, true, &[0x65, 0x88], &[0x67, 0x42])?;
453    /// let view = PacketEnvelope::parse(&packet)?;
454    /// assert!(view.is_keyframe());
455    /// assert_eq!(view.data(), [0x65, 0x88]);
456    /// assert_eq!(view.extra_data(), [0x67, 0x42]);
457    /// # Ok::<(), grafton_ndi::Error>(())
458    /// ```
459    pub fn encode(
460        codec: EnvelopeCodec,
461        presentation_time: i64,
462        decode_time: i64,
463        keyframe: bool,
464        data: &[u8],
465        extra_data: &[u8],
466    ) -> Result<Vec<u8>> {
467        let size = ENVELOPE_HEADER_BYTES
468            .checked_add(data.len())
469            .and_then(|n| n.checked_add(extra_data.len()))
470            .ok_or_else(|| invalid_frame(crate::FrameDefect::PacketSizeOverflow))?;
471        let size = PacketLen::new(size)
472            .ok_or_else(|| invalid_frame(crate::FrameDefect::PacketPayloadSize))?;
473        let data_len = PacketLen::new(data.len())
474            .ok_or_else(|| invalid_frame(crate::FrameDefect::PacketPayloadSize))?;
475        let extra_len = if extra_data.is_empty() {
476            None
477        } else {
478            Some(
479                PacketLen::new(extra_data.len())
480                    .ok_or_else(|| invalid_frame(crate::FrameDefect::PacketPayloadSize))?,
481            )
482        };
483        let mut bytes = vec![0; size.to_usize()];
484        let mut put = |offset: usize, value: &[u8]| {
485            bytes[offset..offset + value.len()].copy_from_slice(value);
486        };
487        put(
488            VERSION_OFFSET,
489            &(ENVELOPE_HEADER_BYTES as i32).to_ne_bytes(),
490        );
491        put(CODEC_OFFSET, &FourCc::from(codec).raw().to_ne_bytes());
492        put(PTS_OFFSET, &presentation_time.to_ne_bytes());
493        put(DTS_OFFSET, &decode_time.to_ne_bytes());
494        // The SDK delivers no AAC packet without the flag.
495        let keyframe = keyframe || codec == EnvelopeCodec::Aac;
496        put(
497            FLAGS_OFFSET,
498            &(if keyframe { KEYFRAME } else { 0 }).to_ne_bytes(),
499        );
500        put(DATA_SIZE_OFFSET, &data_len.to_u32().to_ne_bytes());
501        put(
502            EXTRA_DATA_SIZE_OFFSET,
503            &extra_len.map_or(0, PacketLen::to_u32).to_ne_bytes(),
504        );
505        put(ENVELOPE_HEADER_BYTES, data);
506        put(ENVELOPE_HEADER_BYTES + data.len(), extra_data);
507        Ok(bytes)
508    }
509
510    /// The codec, when the header names one this module knows.
511    pub fn codec(self) -> Option<EnvelopeCodec> {
512        EnvelopeCodec::try_from(self.fourcc()).ok()
513    }
514
515    /// The codec's FourCC exactly as the header carries it.
516    pub fn fourcc(self) -> FourCc {
517        FourCc::from_raw(u32::from_ne_bytes(field(self.bytes, CODEC_OFFSET)))
518    }
519
520    /// Presentation timestamp, in the stream's own units.
521    pub fn presentation_time(self) -> i64 {
522        i64::from_ne_bytes(field(self.bytes, PTS_OFFSET))
523    }
524
525    /// Decode timestamp, in the stream's own units.
526    pub fn decode_time(self) -> i64 {
527        i64::from_ne_bytes(field(self.bytes, DTS_OFFSET))
528    }
529
530    /// Whether the keyframe flag is set.
531    pub fn is_keyframe(self) -> bool {
532        self.flags() & KEYFRAME != 0
533    }
534
535    /// The header's flags field, every bit as the packet carries it,
536    /// including bits this module does not interpret.
537    /// [`is_keyframe`](Self::is_keyframe) reads the one it does.
538    pub fn flags(self) -> u32 {
539        u32::from_ne_bytes(field(self.bytes, FLAGS_OFFSET))
540    }
541
542    /// The header's reserved field.
543    ///
544    /// The field belongs to the SDK, which overwrites it in every packet it
545    /// sends. Its value says nothing about whether a packet can be sent.
546    pub fn reserved(self) -> u64 {
547        u64::from_ne_bytes(field(self.bytes, RESERVED_OFFSET))
548    }
549
550    /// Header bytes beyond the version-0 fields. Empty for version 0.
551    pub fn header_extension(self) -> &'a [u8] {
552        &self.bytes[ENVELOPE_HEADER_BYTES..self.extents.size]
553    }
554
555    /// The codec payload.
556    pub fn data(self) -> &'a [u8] {
557        let start = self.extents.size;
558        &self.bytes[start..start + self.extents.data_len]
559    }
560
561    /// Codec configuration data (parameter sets, or the AAC configuration),
562    /// which follows the payload. Empty when the packet carries none.
563    pub fn extra_data(self) -> &'a [u8] {
564        let start = self.extents.extra_offset();
565        &self.bytes[start..start + self.extents.extra_len]
566    }
567
568    /// Bytes after the lengths the header declares.
569    pub fn trailing_bytes(self) -> &'a [u8] {
570        &self.bytes[self.extents.extra_offset() + self.extents.extra_len..]
571    }
572
573    /// Whether the header is exactly version 0, the version this module writes.
574    pub fn is_known_version(self) -> bool {
575        self.extents.size == ENVELOPE_HEADER_BYTES
576    }
577}
578
579/// The codec, geometry and timing of compressed video, independent of any
580/// one frame's bytes.
581///
582/// # Examples
583///
584/// ```
585/// use grafton_ndi::{
586///     advanced::{VideoCodec, VideoPacketFormat},
587///     FrameRate, StreamTier,
588/// };
589///
590/// let format = VideoPacketFormat::new(VideoCodec::Hevc, 1920, 1080)?
591///     .with_frame_rate(FrameRate::new(60_000, 1001)?)
592///     .with_tier(StreamTier::Program);
593/// assert_eq!(format.frame_rate(), FrameRate::new(60_000, 1001)?);
594/// assert!(VideoPacketFormat::new(VideoCodec::Hevc, 0, 1080).is_err());
595/// # Ok::<(), grafton_ndi::Error>(())
596/// ```
597#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
598pub struct VideoPacketFormat {
599    codec: VideoCodec,
600    tier: StreamTier,
601    protected: bool,
602    width: SdkQuantity,
603    height: SdkQuantity,
604    frame_rate: FrameRate,
605    picture_aspect_ratio: PictureAspectRatio,
606    scan_type: ScanType,
607}
608
609impl VideoPacketFormat {
610    /// A progressive program-tier format at 60 frames per second with square
611    /// pixels. Adjust it with the `with_*` methods.
612    ///
613    /// # Errors
614    ///
615    /// [`Error::InvalidInput`] unless both dimensions are in `1..=i32::MAX`,
616    /// the range the SDK can carry.
617    pub fn new(codec: VideoCodec, width: u32, height: u32) -> Result<Self> {
618        Self::checked(codec, width.into(), height.into())
619            .map_err(|cause| Error::InvalidInput(crate::InputDefect::Layout(cause)))
620    }
621
622    /// The one dimension check, for values from the API and from the SDK.
623    /// The error is the reason, for the caller to report as its own variant.
624    fn checked(codec: VideoCodec, width: i64, height: i64) -> crate::frames::LayoutResult<Self> {
625        match (SdkQuantity::new(width), SdkQuantity::new(height)) {
626            (Some(width), Some(height)) => Ok(Self {
627                codec,
628                tier: StreamTier::Program,
629                protected: false,
630                width,
631                height,
632                frame_rate: crate::media::DEFAULT_VIDEO_FRAME_RATE,
633                picture_aspect_ratio: PictureAspectRatio::SQUARE_PIXELS,
634                scan_type: ScanType::Progressive,
635            }),
636            _ => Err(crate::LayoutDefect::CompressedVideoDimensions {
637                detail: crate::CompactDiagnostic::new(crate::VideoDimensionsDefect {
638                    width,
639                    height,
640                }),
641            }),
642        }
643    }
644
645    /// The format of a compressed frame the SDK delivered; a value out of
646    /// range makes the frame invalid.
647    pub(crate) fn from_sdk(raw: &NDIlib_video_frame_v2_t) -> Result<Self> {
648        let (codec, tier, protected) = VideoCodec::from_outer(raw.FourCC)
649            .ok_or_else(|| invalid_frame(crate::FrameDefect::UnknownCompressedVideo))?;
650        let format = Self::checked(codec, raw.xres.into(), raw.yres.into()).map_err(Error::from)?;
651        let header = VideoHeader::from_sdk(raw)?;
652        Ok(Self {
653            tier,
654            protected,
655            frame_rate: header.frame_rate(),
656            picture_aspect_ratio: header.picture_aspect_ratio(),
657            scan_type: header.scan_type(),
658            ..format
659        })
660    }
661
662    /// The same format at `frame_rate`.
663    #[must_use]
664    pub fn with_frame_rate(self, frame_rate: FrameRate) -> Self {
665        Self { frame_rate, ..self }
666    }
667
668    /// The same format with the validated displayed picture aspect ratio.
669    /// [`PictureAspectRatio::SQUARE_PIXELS`] asks the SDK to derive it from
670    /// the pixel dimensions.
671    #[must_use]
672    pub fn with_picture_aspect_ratio(self, ratio: PictureAspectRatio) -> Self {
673        Self {
674            picture_aspect_ratio: ratio,
675            ..self
676        }
677    }
678
679    /// The same format on the program or preview stream.
680    #[must_use]
681    pub fn with_tier(self, tier: StreamTier) -> Self {
682        Self { tier, ..self }
683    }
684
685    /// The same format with scan type `scan_type`.
686    #[must_use]
687    pub fn with_scan_type(self, scan_type: ScanType) -> Self {
688        Self { scan_type, ..self }
689    }
690
691    /// The same format, marked as a protected stream or not.
692    #[must_use]
693    pub fn with_protected(self, protected: bool) -> Self {
694        Self { protected, ..self }
695    }
696
697    /// The codec.
698    pub fn codec(self) -> VideoCodec {
699        self.codec
700    }
701
702    /// Width in pixels.
703    pub fn width(self) -> u32 {
704        self.width.get()
705    }
706
707    /// Height in pixels.
708    pub fn height(self) -> u32 {
709        self.height.get()
710    }
711
712    /// The frame rate.
713    pub fn frame_rate(self) -> FrameRate {
714        self.frame_rate
715    }
716
717    /// The picture aspect ratio; `0.0` means square pixels.
718    pub fn picture_aspect_ratio(self) -> PictureAspectRatio {
719        self.picture_aspect_ratio
720    }
721
722    /// The stream this format belongs to.
723    pub fn tier(self) -> StreamTier {
724        self.tier
725    }
726
727    /// The scan type.
728    pub fn scan_type(self) -> ScanType {
729        self.scan_type
730    }
731
732    /// Whether the stream is protected.
733    pub fn is_protected(self) -> bool {
734        self.protected
735    }
736
737    /// A native frame descriptor with this format and no data, no timecode
738    /// and no metadata.
739    pub(crate) fn raw(self) -> NDIlib_video_frame_v2_t {
740        let (numerator, denominator) = self.frame_rate.to_sdk();
741        NDIlib_video_frame_v2_t {
742            xres: self.width.to_sdk(),
743            yres: self.height.to_sdk(),
744            FourCC: self.codec.outer(self.tier, self.protected),
745            frame_rate_N: numerator,
746            frame_rate_D: denominator,
747            picture_aspect_ratio: self.picture_aspect_ratio.to_sdk(),
748            frame_format_type: self.scan_type.to_sdk(),
749            ..descriptors::video_frame()
750        }
751    }
752
753    /// A native descriptor of a frame with this format and `extras`, without
754    /// data.
755    pub(crate) fn descriptor(self, extras: &FrameExtras) -> NDIlib_video_frame_v2_t {
756        let (timecode, timestamp, p_metadata) = extras.to_sdk();
757        NDIlib_video_frame_v2_t {
758            timecode,
759            timestamp,
760            p_metadata,
761            ..self.raw()
762        }
763    }
764}
765
766/// The timecode, timestamp and metadata every compressed and scatter frame
767/// carries, with the single checked way to set the metadata.
768///
769/// The default is what a frame built for sending carries: a timecode for the
770/// SDK to synthesize, no timestamp and no metadata.
771#[derive(Clone, Debug, Default)]
772pub(crate) struct FrameExtras {
773    timecode: Timecode,
774    timestamp: Option<ReceivedTimestamp>,
775    metadata: OwnedFrameMetadata,
776}
777
778impl FrameExtras {
779    /// The values the SDK delivered with a received frame.
780    ///
781    /// # Safety
782    ///
783    /// `metadata` is null or readable through its first NUL or the metadata cap.
784    #[cfg(test)]
785    unsafe fn received(timecode: i64, timestamp: i64, metadata: *const c_char) -> Result<Self> {
786        let descriptor = NDIlib_video_frame_v2_t {
787            p_metadata: metadata,
788            ..Default::default()
789        };
790        // SAFETY: only metadata is inspected; the caller retains its bounded
791        // readable text while this synthetic descriptor is borrowed.
792        let frame =
793            unsafe { crate::frames::ValidatedFrame::validate_descriptor(&descriptor, |_| Ok(()))? };
794        let mut extras = Self::default();
795        extras.copy_received(
796            Timecode::from_ticks(timecode),
797            ReceivedTimestamp::from_sdk(timestamp),
798            frame.frame_metadata(),
799        );
800        Ok(extras)
801    }
802
803    /// Reuse storage while copying the borrowed frame's one metadata value.
804    fn copy_received(
805        &mut self,
806        timecode: Timecode,
807        timestamp: Option<ReceivedTimestamp>,
808        metadata: FrameMetadataRef<'_>,
809    ) {
810        self.metadata.copy_from(metadata);
811        self.timecode = timecode;
812        self.timestamp = timestamp;
813    }
814
815    /// The timecode.
816    pub(crate) fn timecode(&self) -> Timecode {
817        self.timecode
818    }
819
820    /// The timestamp of a received frame.
821    pub(crate) fn timestamp(&self) -> Option<ReceivedTimestamp> {
822        self.timestamp
823    }
824
825    /// The metadata text, if any.
826    pub(crate) fn metadata(&self) -> Option<&str> {
827        self.metadata
828            .view()
829            .text()
830            .map(crate::frames::MetadataText::as_str)
831    }
832
833    pub(crate) fn metadata_status(&self) -> crate::FrameMetadataStatus {
834        self.metadata.view().status()
835    }
836
837    pub(crate) fn set_timecode(&mut self, timecode: Timecode) {
838        self.timecode = timecode;
839    }
840
841    pub(crate) fn set_metadata(
842        &mut self,
843        metadata: impl Into<String>,
844    ) -> std::result::Result<(), Rejected<String>> {
845        self.metadata.set(metadata)
846    }
847
848    pub(crate) fn clear_metadata(&mut self) {
849        // Explicit packet clearing releases retained metadata storage as before;
850        // copying an absent observation instead preserves it for later frames.
851        self.metadata = OwnedFrameMetadata::default();
852    }
853
854    /// Bytes the metadata keeps allocated, including terminator and spare capacity.
855    pub(crate) fn retained_bytes(&self) -> usize {
856        self.metadata.retained_bytes()
857    }
858
859    /// The timecode, timestamp and metadata fields of a native descriptor.
860    /// The metadata pointer is null without metadata, and valid for as long
861    /// as these extras are.
862    fn to_sdk(&self) -> (i64, i64, *const c_char) {
863        (
864            self.timecode.ticks(),
865            ReceivedTimestamp::to_sdk(self.timestamp),
866            self.metadata.view().as_ptr(),
867        )
868    }
869}
870
871#[path = "packets/roles.rs"]
872mod roles;
873pub use roles::{CompressedFrame, CompressedRef, PacketFormat, ReceivedPacket, ScatterFrame};
874#[cfg(test)]
875use roles::{NativePacketFormat, PacketContent};
876
877/// What a packet is being checked for.
878#[derive(Clone, Copy, PartialEq, Eq)]
879pub(crate) enum Use {
880    /// Keeping a received packet: later envelope versions are accepted.
881    Receive,
882    /// Sending: only what this module fully understands is accepted.
883    Send,
884}
885
886#[cfg(test)]
887fn validate_video_packet(
888    format: VideoPacketFormat,
889    bytes: &[u8],
890    purpose: Use,
891) -> Result<PacketLen> {
892    let bytes = PacketSlice::new(bytes)
893        .ok_or_else(|| invalid_frame(crate::FrameDefect::CompressedVideoSize))?;
894    format.admit(PacketContent::Contiguous(bytes), purpose)?;
895    Ok(bytes.len())
896}
897
898/// The sample rates an AAC configuration can name, in the order of its
899/// sampling-frequency index.
900const AAC_SAMPLE_RATES: [u32; 13] = [
901    96_000, 88_200, 64_000, 48_000, 44_100, 32_000, 24_000, 22_050, 16_000, 12_000, 11_025, 8_000,
902    7_350,
903];
904
905/// The channel counts an AAC configuration can name, in the order of its
906/// channel configuration, which starts at one.
907const AAC_CHANNELS: [u32; 7] = [1, 2, 3, 4, 5, 6, 8];
908
909/// The number of samples per channel in an AAC frame.
910const AAC_FRAME_SAMPLES: u32 = 1024;
911
912/// The sample rates Opus runs at.
913const OPUS_SAMPLE_RATES: [u32; 5] = [8_000, 12_000, 16_000, 24_000, 48_000];
914
915/// The durations of an Opus frame, in units of 2.5 ms.
916const OPUS_FRAME_DURATIONS: [u64; 6] = [1, 2, 4, 8, 16, 24];
917
918/// A compressed audio codec.
919///
920/// AAC travels in a packet envelope; Opus is sent as bare codec packets.
921///
922/// # Delivery
923///
924/// The SDK takes any compressed audio frame and silently discards the ones
925/// whose parameters it does not accept, so this module refuses to build or
926/// send those:
927///
928/// * Opus runs at 8, 12, 16, 24 or 48 kHz, and a frame holds 2.5, 5, 10, 20,
929///   40 or 60 ms of audio.
930/// * An AAC frame holds 1024 samples per channel and carries its
931///   AudioSpecificConfig as codec configuration data. The sample rate and the
932///   channel layout the configuration names must be the frame's own, which
933///   allows the thirteen indexed sample rates from 7350 Hz to 96 kHz and one
934///   to six or eight channels.
935#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
936#[non_exhaustive]
937pub enum AudioCodec {
938    /// AAC in a packet envelope.
939    Aac,
940    /// Opus, without an envelope.
941    Opus,
942}
943
944crate::media::decoded_variants!(AudioCodec: Aac, Opus);
945
946/// The codec, protection and decoded dimensions of one compressed audio frame.
947///
948/// Quantities are in `1..=i32::MAX`, the range of the SDK's signed fields.
949/// Codec delivery rules are checked when a frame is admitted for sending,
950/// preserving lossless inspection of received packets.
951#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
952pub struct AudioPacketFormat {
953    codec: AudioCodec,
954    protected: bool,
955    sample_rate: SdkQuantity,
956    num_channels: SdkQuantity,
957    num_samples: SdkQuantity,
958}
959
960impl AudioPacketFormat {
961    /// Describe a compressed audio frame of `codec` with the given quantities.
962    ///
963    /// # Errors
964    ///
965    /// [`Error::InvalidInput`] unless each quantity is in `1..=i32::MAX`.
966    pub fn new(
967        codec: AudioCodec,
968        sample_rate: u32,
969        num_channels: u32,
970        num_samples: u32,
971    ) -> Result<Self> {
972        Self::checked(
973            codec,
974            false,
975            sample_rate.into(),
976            num_channels.into(),
977            num_samples.into(),
978        )
979        .map_err(|cause| Error::InvalidInput(crate::InputDefect::Layout(cause)))
980    }
981
982    /// The same format with the requested stream protection.
983    #[must_use]
984    pub fn with_protected(self, protected: bool) -> Self {
985        Self { protected, ..self }
986    }
987
988    /// The compressed audio codec.
989    pub fn codec(self) -> AudioCodec {
990        self.codec
991    }
992
993    /// Whether the stream is protected.
994    pub fn is_protected(self) -> bool {
995        self.protected
996    }
997
998    /// Sample rate in hertz.
999    pub fn sample_rate(self) -> u32 {
1000        self.sample_rate.get()
1001    }
1002
1003    /// Number of channels.
1004    pub fn num_channels(self) -> u32 {
1005        self.num_channels.get()
1006    }
1007
1008    /// Samples per channel the frame decodes to.
1009    pub fn num_samples(self) -> u32 {
1010        self.num_samples.get()
1011    }
1012
1013    /// The format of a frame the SDK delivered.
1014    fn from_sdk(raw: &NDIlib_audio_frame_v3_t) -> Result<Self> {
1015        let (codec, protected) = AudioCodec::from_outer(raw.FourCC)
1016            .ok_or_else(|| invalid_frame(crate::FrameDefect::UnknownCompressedAudio))?;
1017        Self::checked(
1018            codec,
1019            protected,
1020            raw.sample_rate.into(),
1021            raw.no_channels.into(),
1022            raw.no_samples.into(),
1023        )
1024        .map_err(|cause| invalid_frame(crate::FrameDefect::Layout(cause)))
1025    }
1026
1027    /// The one quantity check, for values from the API and from the SDK.
1028    fn checked(
1029        codec: AudioCodec,
1030        protected: bool,
1031        sample_rate: i64,
1032        num_channels: i64,
1033        num_samples: i64,
1034    ) -> crate::frames::LayoutResult<Self> {
1035        let sample_rate = crate::frames::validate_audio_sample_rate(sample_rate)?;
1036        let (num_channels, num_samples) =
1037            crate::frames::validate_positive_audio_counts(num_channels, num_samples)?;
1038        Ok(Self {
1039            codec,
1040            protected,
1041            sample_rate,
1042            num_channels,
1043            num_samples,
1044        })
1045    }
1046
1047    /// A native descriptor without data, carrying this format and `extras`.
1048    pub(crate) fn descriptor(self, extras: &FrameExtras) -> NDIlib_audio_frame_v3_t {
1049        let (timecode, timestamp, p_metadata) = extras.to_sdk();
1050        NDIlib_audio_frame_v3_t {
1051            sample_rate: self.sample_rate.to_sdk(),
1052            no_channels: self.num_channels.to_sdk(),
1053            no_samples: self.num_samples.to_sdk(),
1054            FourCC: self.codec.outer(self.protected),
1055            timecode,
1056            timestamp,
1057            p_metadata,
1058            ..descriptors::audio_frame()
1059        }
1060    }
1061}
1062
1063impl AudioCodec {
1064    /// Check the parameters a frame of this codec is delivered with; see
1065    /// [`AudioCodec`]. An AAC frame's configuration is checked separately,
1066    /// against its envelope.
1067    fn validate_delivery(self, parameters: AudioPacketFormat) -> Result<()> {
1068        let sample_rate = parameters.sample_rate();
1069        let num_channels = parameters.num_channels();
1070        let num_samples = parameters.num_samples();
1071        match self {
1072            Self::Opus => {
1073                if !OPUS_SAMPLE_RATES.contains(&sample_rate) {
1074                    return Err(invalid_frame(crate::FrameDefect::OpusSampleRate));
1075                }
1076                // One unit is 2.5 ms, which is a four-hundredth of a second.
1077                let units = u64::from(num_samples) * 400;
1078                if !OPUS_FRAME_DURATIONS
1079                    .iter()
1080                    .any(|duration| units == duration * u64::from(sample_rate))
1081                {
1082                    return Err(invalid_frame(crate::FrameDefect::OpusDuration));
1083                }
1084            }
1085            Self::Aac => {
1086                if num_samples != AAC_FRAME_SAMPLES {
1087                    return Err(invalid_frame(crate::FrameDefect::AacSampleCount));
1088                }
1089                if !AAC_SAMPLE_RATES.contains(&sample_rate) {
1090                    return Err(invalid_frame(crate::FrameDefect::AacSampleRate));
1091                }
1092                if !AAC_CHANNELS.contains(&num_channels) {
1093                    return Err(invalid_frame(crate::FrameDefect::AacChannels));
1094                }
1095            }
1096        }
1097        Ok(())
1098    }
1099
1100    /// The FourCC a frame of this codec is sent with.
1101    pub(crate) const fn outer(self, protected: bool) -> u32 {
1102        (match self {
1103            Self::Aac => EnvelopeCodec::Aac.raw_fourcc(),
1104            Self::Opus => fourcc(b"Opus"),
1105        }) | if protected { PROTECTED } else { 0 }
1106    }
1107
1108    /// The codec and protection a frame FourCC names, if it is compressed
1109    /// audio this module knows.
1110    pub(crate) fn from_outer(value: u32) -> Option<(Self, bool)> {
1111        Self::ALL.into_iter().find_map(|codec| {
1112            [false, true]
1113                .into_iter()
1114                .find(|protected| value == codec.outer(*protected))
1115                .map(|protected| (codec, protected))
1116        })
1117    }
1118}
1119
1120#[cfg(test)]
1121fn validate_audio_for_send(format: AudioPacketFormat, bytes: &[u8]) -> Result<PacketLen> {
1122    let bytes = PacketSlice::new(bytes)
1123        .ok_or_else(|| invalid_frame(crate::FrameDefect::CompressedAudioSize))?;
1124    format.admit(PacketContent::Contiguous(bytes), Use::Send)?;
1125    Ok(bytes.len())
1126}
1127
1128#[cfg(test)]
1129#[path = "packets/received_tests.rs"]
1130mod received;
1131
1132/// Copy a compressed video frame the SDK delivered.
1133///
1134/// # Safety
1135///
1136/// `raw` describes a compressed frame: its union holds the data size, its data
1137/// pointer is readable for that size, and its metadata pointer is null or a
1138/// readable string through its first NUL or the metadata cap.
1139#[cfg(test)]
1140pub(crate) unsafe fn copy_video_packet(
1141    raw: &NDIlib_video_frame_v2_t,
1142) -> Result<ReceivedPacket<VideoPacketFormat>> {
1143    // SAFETY: the test caller retains raw's storage, and the synthetic guard
1144    // borrows it until the copy completes; its release callback frees nothing.
1145    let guard =
1146        unsafe { crate::capture::Guard::with_test_free(std::ptr::null_mut(), *raw, |_, _| {}) };
1147    CompressedRef::<VideoPacketFormat>::new(guard).map(|frame| frame.to_owned())
1148}
1149
1150/// Copy a compressed audio frame the SDK delivered.
1151///
1152/// # Safety
1153///
1154/// As for [`copy_video_packet`].
1155#[cfg(test)]
1156pub(crate) unsafe fn copy_audio_packet(
1157    raw: &NDIlib_audio_frame_v3_t,
1158) -> Result<ReceivedPacket<AudioPacketFormat>> {
1159    // SAFETY: as for the video fixture above.
1160    let guard =
1161        unsafe { crate::capture::Guard::with_test_free(std::ptr::null_mut(), *raw, |_, _| {}) };
1162    CompressedRef::<AudioPacketFormat>::new(guard).map(|frame| frame.to_owned())
1163}
1164
1165// The values above are the NDI wire format, which the data types in this file
1166// implement in every build. Where the build has the Advanced SDK declarations,
1167// each value is checked against them.
1168#[cfg(ndi_has_advanced_header)]
1169const_assert!({
1170    // Enum constants of the Advanced-only headers take the target's C enum
1171    // type, which is signed on some targets; compare bit patterns.
1172    macro_rules! same_bits {
1173        ($ours:expr, $native:ident) => {
1174            crate::sys::advanced::declared! { $native {
1175                assert!($ours == u32::from_ne_bytes(
1176                    crate::sys::advanced_bindings::$native.to_ne_bytes()
1177                ));
1178            } else {} }
1179        };
1180    }
1181
1182    same_bits!(
1183        VideoCodec::SpeedHq420.outer(StreamTier::Program, false),
1184        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ0_highest_bandwidth
1185    );
1186    same_bits!(
1187        VideoCodec::SpeedHq420.outer(StreamTier::Program, true),
1188        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ0_highest_bandwidth_protected
1189    );
1190    same_bits!(
1191        VideoCodec::SpeedHq420.outer(StreamTier::Preview, false),
1192        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ0_lowest_bandwidth
1193    );
1194    same_bits!(
1195        VideoCodec::SpeedHq420.outer(StreamTier::Preview, true),
1196        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ0_lowest_bandwidth_protected
1197    );
1198    same_bits!(
1199        VideoCodec::SpeedHq422.outer(StreamTier::Program, false),
1200        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ2_highest_bandwidth
1201    );
1202    same_bits!(
1203        VideoCodec::SpeedHq422.outer(StreamTier::Program, true),
1204        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ2_highest_bandwidth_protected
1205    );
1206    same_bits!(
1207        VideoCodec::SpeedHq422.outer(StreamTier::Preview, false),
1208        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ2_lowest_bandwidth
1209    );
1210    same_bits!(
1211        VideoCodec::SpeedHq422.outer(StreamTier::Preview, true),
1212        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ2_lowest_bandwidth_protected
1213    );
1214    same_bits!(
1215        VideoCodec::SpeedHq422Alpha.outer(StreamTier::Program, false),
1216        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ7_highest_bandwidth
1217    );
1218    same_bits!(
1219        VideoCodec::SpeedHq422Alpha.outer(StreamTier::Program, true),
1220        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ7_highest_bandwidth_protected
1221    );
1222    same_bits!(
1223        VideoCodec::SpeedHq422Alpha.outer(StreamTier::Preview, false),
1224        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ7_lowest_bandwidth
1225    );
1226    same_bits!(
1227        VideoCodec::SpeedHq422Alpha.outer(StreamTier::Preview, true),
1228        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_SHQ7_lowest_bandwidth_protected
1229    );
1230    same_bits!(
1231        VideoCodec::H264.outer(StreamTier::Program, false),
1232        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_H264_highest_bandwidth
1233    );
1234    same_bits!(
1235        VideoCodec::H264.outer(StreamTier::Program, true),
1236        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_H264_highest_bandwidth_protected
1237    );
1238    same_bits!(
1239        VideoCodec::H264.outer(StreamTier::Preview, false),
1240        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_H264_lowest_bandwidth
1241    );
1242    same_bits!(
1243        VideoCodec::H264.outer(StreamTier::Preview, true),
1244        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_H264_lowest_bandwidth_protected
1245    );
1246    same_bits!(
1247        VideoCodec::Hevc.outer(StreamTier::Program, false),
1248        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_HEVC_highest_bandwidth
1249    );
1250    same_bits!(
1251        VideoCodec::Hevc.outer(StreamTier::Program, true),
1252        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_HEVC_highest_bandwidth_protected
1253    );
1254    same_bits!(
1255        VideoCodec::Hevc.outer(StreamTier::Preview, false),
1256        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_HEVC_lowest_bandwidth
1257    );
1258    same_bits!(
1259        VideoCodec::Hevc.outer(StreamTier::Preview, true),
1260        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_HEVC_lowest_bandwidth_protected
1261    );
1262    same_bits!(
1263        VideoCodec::H264Alpha.outer(StreamTier::Program, false),
1264        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_H264_alpha_highest_bandwidth
1265    );
1266    same_bits!(
1267        VideoCodec::H264Alpha.outer(StreamTier::Program, true),
1268        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_H264_alpha_highest_bandwidth_protected
1269    );
1270    same_bits!(
1271        VideoCodec::H264Alpha.outer(StreamTier::Preview, false),
1272        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_H264_alpha_lowest_bandwidth
1273    );
1274    same_bits!(
1275        VideoCodec::H264Alpha.outer(StreamTier::Preview, true),
1276        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_H264_alpha_lowest_bandwidth_protected
1277    );
1278    same_bits!(
1279        VideoCodec::HevcAlpha.outer(StreamTier::Program, false),
1280        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_HEVC_alpha_highest_bandwidth
1281    );
1282    same_bits!(
1283        VideoCodec::HevcAlpha.outer(StreamTier::Program, true),
1284        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_HEVC_alpha_highest_bandwidth_protected
1285    );
1286    same_bits!(
1287        VideoCodec::HevcAlpha.outer(StreamTier::Preview, false),
1288        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_HEVC_alpha_lowest_bandwidth
1289    );
1290    same_bits!(
1291        VideoCodec::HevcAlpha.outer(StreamTier::Preview, true),
1292        NDIlib_FourCC_video_type_ex_e_NDIlib_FourCC_video_type_ex_HEVC_alpha_lowest_bandwidth_protected
1293    );
1294
1295    same_bits!(
1296        AudioCodec::Aac.outer(false),
1297        NDIlib_FourCC_audio_type_ex_e_NDIlib_FourCC_audio_type_ex_AAC
1298    );
1299    same_bits!(
1300        AudioCodec::Aac.outer(true),
1301        NDIlib_FourCC_audio_type_ex_e_NDIlib_FourCC_audio_type_ex_AAC_protected
1302    );
1303    same_bits!(
1304        AudioCodec::Opus.outer(false),
1305        NDIlib_FourCC_audio_type_ex_e_NDIlib_FourCC_audio_type_ex_OPUS
1306    );
1307    same_bits!(
1308        AudioCodec::Opus.outer(true),
1309        NDIlib_FourCC_audio_type_ex_e_NDIlib_FourCC_audio_type_ex_OPUS_protected
1310    );
1311
1312    same_bits!(
1313        EnvelopeCodec::H264.raw_fourcc(),
1314        NDIlib_compressed_FourCC_type_e_NDIlib_compressed_FourCC_type_H264
1315    );
1316    same_bits!(
1317        EnvelopeCodec::Hevc.raw_fourcc(),
1318        NDIlib_compressed_FourCC_type_e_NDIlib_compressed_FourCC_type_HEVC
1319    );
1320    same_bits!(
1321        EnvelopeCodec::Aac.raw_fourcc(),
1322        NDIlib_compressed_FourCC_type_e_NDIlib_compressed_FourCC_type_AAC
1323    );
1324
1325    crate::sys::advanced::declared! { NDIlib_compressed_packet_flags_keyframe {
1326        assert!(KEYFRAME == crate::sys::advanced_bindings::NDIlib_compressed_packet_flags_keyframe);
1327    } else {} }
1328    crate::sys::advanced::declared! { NDIlib_compressed_packet_version_0 {
1329        assert!(ENVELOPE_HEADER_BYTES as i32 == crate::sys::advanced_bindings::NDIlib_compressed_packet_version_0);
1330    } else {} }
1331    crate::sys::advanced::declared! { NDIlib_compressed_packet_t {
1332    use crate::sys::advanced_bindings::NDIlib_compressed_packet_t;
1333    use std::mem::{offset_of, size_of};
1334
1335    assert!(size_of::<NDIlib_compressed_packet_t>() == ENVELOPE_HEADER_BYTES);
1336    assert!(offset_of!(NDIlib_compressed_packet_t, version) == VERSION_OFFSET);
1337    assert!(offset_of!(NDIlib_compressed_packet_t, fourCC) == CODEC_OFFSET);
1338    assert!(offset_of!(NDIlib_compressed_packet_t, pts) == PTS_OFFSET);
1339    assert!(offset_of!(NDIlib_compressed_packet_t, dts) == DTS_OFFSET);
1340    assert!(offset_of!(NDIlib_compressed_packet_t, reserved) == RESERVED_OFFSET);
1341    assert!(offset_of!(NDIlib_compressed_packet_t, flags) == FLAGS_OFFSET);
1342    assert!(offset_of!(NDIlib_compressed_packet_t, data_size) == DATA_SIZE_OFFSET);
1343    assert!(offset_of!(NDIlib_compressed_packet_t, extra_data_size) == EXTRA_DATA_SIZE_OFFSET);
1344    } else {} }
1345});
1346
1347/// Frames for this module's unit tests.
1348#[cfg(test)]
1349pub(crate) mod testing {
1350    use super::*;
1351
1352    /// A two-byte AAC-LC AudioSpecificConfig for an indexed sample rate and a
1353    /// channel count the configuration can name.
1354    pub(crate) fn aac_config(sample_rate: u32, channels: u32) -> [u8; 2] {
1355        let position = |values: &[u32], value| {
1356            values
1357                .iter()
1358                .position(|candidate| *candidate == value)
1359                .expect("a value the AAC configuration can name") as u16
1360        };
1361        let frequency_index = position(&AAC_SAMPLE_RATES, sample_rate);
1362        let channel_configuration = position(&AAC_CHANNELS, channels) + 1;
1363        ((2 << 11) | (frequency_index << 7) | (channel_configuration << 3)).to_be_bytes()
1364    }
1365
1366    /// An AAC packet envelope with a matching configuration.
1367    pub(crate) fn aac_packet(sample_rate: u32, channels: u32, payload: &[u8]) -> Vec<u8> {
1368        PacketEnvelope::encode(
1369            EnvelopeCodec::Aac,
1370            0,
1371            0,
1372            true,
1373            payload,
1374            &aac_config(sample_rate, channels),
1375        )
1376        .unwrap()
1377    }
1378}
1379
1380#[cfg(test)]
1381mod tests {
1382    use super::{testing::*, *};
1383
1384    #[test]
1385    fn packet_lengths_keep_the_sdk_bound() {
1386        for bytes in [0, MAX_PACKET_BYTES + 1, usize::MAX] {
1387            assert_eq!(PacketLen::new(bytes), None);
1388        }
1389        for bytes in [1, MAX_PACKET_BYTES] {
1390            let len = PacketLen::new(bytes).unwrap();
1391            assert_eq!(len.to_usize(), bytes);
1392            assert_eq!(PacketLen::from_sdk(len.to_sdk()), Some(len));
1393        }
1394        for bytes in [
1395            -1,
1396            i32::MIN,
1397            0,
1398            i32::try_from(MAX_PACKET_BYTES + 1).unwrap(),
1399            i32::MAX,
1400        ] {
1401            assert_eq!(PacketLen::from_sdk(bytes), None);
1402        }
1403    }
1404
1405    #[test]
1406    fn empty_packet_lengths_keep_their_container_causes() {
1407        let cause = |result: Result<()>| match result.unwrap_err() {
1408            Error::InvalidFrame(cause) => cause,
1409            error => panic!("unexpected packet error: {error:?}"),
1410        };
1411        assert_eq!(
1412            cause(PacketEnvelope::parse(&[]).map(|_| ())),
1413            crate::FrameDefect::PacketHeaderTruncated
1414        );
1415        assert_eq!(
1416            cause(PacketEnvelope::encode(EnvelopeCodec::H264, 0, 0, false, &[], &[]).map(|_| ())),
1417            crate::FrameDefect::PacketPayloadSize
1418        );
1419        assert_eq!(
1420            cause(validate_video_packet(h264_format(), &[], Use::Send).map(|_| ())),
1421            crate::FrameDefect::CompressedVideoSize
1422        );
1423        let audio = AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap();
1424        assert_eq!(
1425            cause(validate_audio_for_send(audio, &[]).map(|_| ())),
1426            crate::FrameDefect::CompressedAudioSize
1427        );
1428        for (blocks, expected) in [
1429            (vec![], crate::FrameDefect::ScatterBlockCount),
1430            (vec![vec![]], crate::FrameDefect::EmptyScatterBlock),
1431        ] {
1432            let rejected = super::super::ScatterFrame::<super::super::VideoPacketFormat>::new(
1433                h264_format(),
1434                blocks,
1435            )
1436            .unwrap_err();
1437            assert!(matches!(rejected.error(), Error::InvalidFrame(actual) if *actual == expected));
1438        }
1439        // SAFETY: a zero extent is refused before a slice is formed.
1440        assert_eq!(
1441            cause(
1442                unsafe { PacketSlice::from_sdk(std::ptr::NonNull::dangling().as_ptr(), 0) }
1443                    .map(|_| ())
1444            ),
1445            crate::FrameDefect::CompressedBuffer
1446        );
1447    }
1448
1449    #[test]
1450    #[cfg_attr(
1451        miri,
1452        ignore = "the full packet extent is covered by the native test run"
1453    )]
1454    fn oversized_packet_lengths_keep_their_container_causes() {
1455        let bytes = vec![0; MAX_PACKET_BYTES + 1];
1456        let cause = |result: Result<()>| match result.unwrap_err() {
1457            Error::InvalidFrame(cause) => cause,
1458            error => panic!("unexpected packet error: {error:?}"),
1459        };
1460        assert_eq!(
1461            cause(PacketEnvelope::parse(&bytes).map(|_| ())),
1462            crate::FrameDefect::PacketLength
1463        );
1464        assert_eq!(
1465            cause(
1466                PacketEnvelope::encode(EnvelopeCodec::H264, 0, 0, false, &bytes, &[]).map(|_| ())
1467            ),
1468            crate::FrameDefect::PacketPayloadSize
1469        );
1470        let rejected = CompressedFrame::<VideoPacketFormat>::new(h264_format(), bytes).unwrap_err();
1471        assert!(matches!(
1472            rejected.error(),
1473            Error::InvalidFrame(crate::FrameDefect::CompressedVideoSize)
1474        ));
1475        let audio = AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap();
1476        let rejected =
1477            CompressedFrame::<AudioPacketFormat>::new(audio, rejected.into_inner()).unwrap_err();
1478        assert!(matches!(
1479            rejected.error(),
1480            Error::InvalidFrame(crate::FrameDefect::CompressedAudioSize)
1481        ));
1482        let bytes = rejected.into_inner();
1483        // SAFETY: the allocation covers the declared size, which is refused
1484        // before packet_bytes forms a slice or reads any byte.
1485        let received =
1486            unsafe { PacketSlice::from_sdk(bytes.as_ptr(), i32::try_from(bytes.len()).unwrap()) };
1487        assert_eq!(
1488            cause(received.map(|_| ())),
1489            crate::FrameDefect::CompressedBuffer
1490        );
1491        let rejected = super::super::ScatterFrame::<super::super::VideoPacketFormat>::new(
1492            h264_format(),
1493            vec![bytes],
1494        )
1495        .unwrap_err();
1496        assert!(matches!(
1497            rejected.error(),
1498            Error::InvalidFrame(crate::FrameDefect::ScatterSize)
1499        ));
1500    }
1501
1502    fn h264_format() -> VideoPacketFormat {
1503        VideoPacketFormat::new(VideoCodec::H264, 16, 16).unwrap()
1504    }
1505
1506    fn h264_packet(keyframe: bool, extra_data: &[u8]) -> Vec<u8> {
1507        PacketEnvelope::encode(EnvelopeCodec::H264, 0, 0, keyframe, &[1], extra_data).unwrap()
1508    }
1509
1510    #[test]
1511    fn packet_debug_summarizes_every_leaf_and_public_holder() {
1512        use crate::advanced::{
1513            AudioPacketFormat, PacketItem, QueuedVideoFrame, ReceivedAudio, ReceivedVideo,
1514            ReclaimedVideo, ScatterFrame, SubmittedVideo, VideoPacketFormat,
1515        };
1516        use crate::capture::Guard;
1517
1518        fn summaries(size: usize) -> Vec<String> {
1519            let bytes =
1520                PacketEnvelope::encode(EnvelopeCodec::H264, 17, 13, true, &vec![7; size], &[1, 2])
1521                    .unwrap();
1522            let mut video =
1523                CompressedFrame::<VideoPacketFormat>::new(h264_format(), bytes.clone()).unwrap();
1524            let raw = video.raw();
1525            // SAFETY: video owns the readable descriptor storage until the
1526            // synthetic non-owning receive guard is dropped.
1527            let guard = unsafe { Guard::with_test_free(std::ptr::null_mut(), raw, |_, _| {}) };
1528            let borrowed = CompressedRef::<VideoPacketFormat>::new(guard).unwrap();
1529            let received = borrowed.to_owned();
1530            let debug = format!("{video:?}");
1531            for other in [format!("{borrowed:?}"), format!("{received:?}")] {
1532                assert_eq!(
1533                    debug.split_once(" {").unwrap().1,
1534                    other.split_once(" {").unwrap().1
1535                );
1536            }
1537            let scatter = ScatterFrame::<VideoPacketFormat>::new(
1538                h264_format(),
1539                vec![bytes[..44].to_vec(), bytes[44..].to_vec()],
1540            )
1541            .unwrap();
1542            let mut result = vec![
1543                debug,
1544                format!("{borrowed:?}"),
1545                format!("{received:?}"),
1546                format!("{:?}", video.envelope().unwrap()),
1547                format!("{scatter:?}"),
1548                format!("{:?}", ReceivedVideo::Compressed(received.clone())),
1549                format!(
1550                    "{:?}",
1551                    PacketItem::Video(ReceivedVideo::Compressed(received))
1552                ),
1553                format!("{:?}", SubmittedVideo::Contiguous(video.clone())),
1554                format!("{:?}", SubmittedVideo::Scatter(scatter.clone())),
1555                format!("{:?}", QueuedVideoFrame::Compressed(video.clone())),
1556                format!("{:?}", QueuedVideoFrame::Scatter(scatter.clone())),
1557                format!(
1558                    "{:?}",
1559                    ReclaimedVideo {
1560                        program: Some(SubmittedVideo::Contiguous(video.clone())),
1561                        preview: Some(SubmittedVideo::Scatter(scatter)),
1562                    }
1563                ),
1564            ];
1565            for codec in AudioCodec::ALL {
1566                let (samples, bytes) = match codec {
1567                    AudioCodec::Aac => (1024, aac_packet(48_000, 2, &vec![7; size])),
1568                    AudioCodec::Opus => (960, vec![7; size]),
1569                };
1570                let mut audio = CompressedFrame::<AudioPacketFormat>::new(
1571                    AudioPacketFormat::new(codec, 48_000, 2, samples).unwrap(),
1572                    bytes.clone(),
1573                )
1574                .unwrap();
1575                let raw = audio.raw();
1576                // SAFETY: audio owns the readable descriptor storage until
1577                // the synthetic non-owning receive guard is dropped.
1578                let guard = unsafe { Guard::with_test_free(std::ptr::null_mut(), raw, |_, _| {}) };
1579                let borrowed = CompressedRef::<AudioPacketFormat>::new(guard).unwrap();
1580                let received = borrowed.to_owned();
1581                let debug = format!("{audio:?}");
1582                for other in [format!("{borrowed:?}"), format!("{received:?}")] {
1583                    assert_eq!(
1584                        debug.split_once(" {").unwrap().1,
1585                        other.split_once(" {").unwrap().1
1586                    );
1587                }
1588                let scatter = ScatterFrame::<AudioPacketFormat>::new(
1589                    AudioPacketFormat::new(codec, 48_000, 2, samples).unwrap(),
1590                    vec![bytes[..44].to_vec(), bytes[44..].to_vec()],
1591                )
1592                .unwrap();
1593                result.extend([
1594                    debug,
1595                    format!("{borrowed:?}"),
1596                    format!("{received:?}"),
1597                    format!("{scatter:?}"),
1598                    format!("{:?}", ReceivedAudio::Compressed(received.clone())),
1599                    format!(
1600                        "{:?}",
1601                        PacketItem::Audio(ReceivedAudio::Compressed(received))
1602                    ),
1603                ]);
1604            }
1605            result
1606        }
1607
1608        crate::test_support::assert_bounded_debug(&summaries(1024), &summaries(1024 * 1024));
1609    }
1610
1611    fn aac(sample_rate: u32, channels: u32, samples: u32, packet: Vec<u8>) -> Result<()> {
1612        let format = AudioPacketFormat::new(AudioCodec::Aac, sample_rate, channels, samples)?;
1613        CompressedFrame::<AudioPacketFormat>::new(format, packet)
1614            .map(drop)
1615            .map_err(Rejected::into_error)
1616    }
1617
1618    fn opus(sample_rate: u32, channels: u32, samples: u32) -> Result<()> {
1619        let format = AudioPacketFormat::new(AudioCodec::Opus, sample_rate, channels, samples)?;
1620        CompressedFrame::<AudioPacketFormat>::new(format, vec![1; 8])
1621            .map(drop)
1622            .map_err(Rejected::into_error)
1623    }
1624
1625    /// The text of an invalid-frame error.
1626    fn reason<T: std::fmt::Debug>(result: Result<T>) -> crate::FrameDefect {
1627        match result {
1628            Err(Error::InvalidFrame(reason)) => reason,
1629            other => panic!("expected an invalid frame, got {other:?}"),
1630        }
1631    }
1632
1633    #[test]
1634    fn packed_and_scatter_admission_agree_for_every_codec_and_use() {
1635        fn check<F: PacketFormat>(format: F, bytes: &[u8], sendable: bool) {
1636            let packet = PacketSlice::new(bytes).unwrap();
1637            let header = format.header_bytes().max(1);
1638            let blocks = [bytes[..header].to_vec(), bytes[header..].to_vec()];
1639            for (purpose, accepted) in [(Use::Receive, true), (Use::Send, sendable)] {
1640                let contiguous = format.admit(PacketContent::Contiguous(packet), purpose);
1641                let scatter = format.admit(
1642                    PacketContent::Scatter {
1643                        first: &blocks[0],
1644                        total: packet.len(),
1645                        rest: &blocks[1..],
1646                    },
1647                    purpose,
1648                );
1649                assert_eq!(contiguous.is_ok(), accepted, "{format:?}");
1650                assert_eq!(
1651                    contiguous.map_err(|error| error.to_string()),
1652                    scatter.map_err(|error| error.to_string()),
1653                    "{format:?}"
1654                );
1655            }
1656        }
1657
1658        for codec in VideoCodec::ALL {
1659            let format = VideoPacketFormat::new(codec, 1920, 1080).unwrap();
1660            if let Some(envelope) = codec.envelope_codec() {
1661                for config in [&[2][..], &[]] {
1662                    let bytes =
1663                        PacketEnvelope::encode(envelope, 0, 0, true, &[1, 2], config).unwrap();
1664                    check(format, &bytes, !config.is_empty());
1665                }
1666            } else {
1667                check(format, &[80, 0, 0, 0, 42], true);
1668                check(format, &[100, 0, 0, 0, 42], false);
1669            }
1670        }
1671        for codec in AudioCodec::ALL {
1672            let (samples, wrong_samples, bytes) = match codec {
1673                AudioCodec::Aac => (1024, 960, aac_packet(48_000, 2, &[1, 2])),
1674                AudioCodec::Opus => (960, 1440, vec![1, 2]),
1675            };
1676            for (samples, sendable) in [(samples, true), (wrong_samples, false)] {
1677                let format = AudioPacketFormat::new(codec, 48_000, 2, samples).unwrap();
1678                check(format, &bytes, sendable);
1679            }
1680        }
1681    }
1682
1683    #[test]
1684    fn envelope_causes_agree_across_containers_and_directions() {
1685        use crate::advanced::{AudioPacketFormat, ScatterFrame, VideoPacketFormat};
1686        use crate::FrameDefect::*;
1687        let cases: &[(&str, usize, u32, Option<crate::FrameDefect>, bool)] = &[
1688            (
1689                "short header",
1690                usize::MAX,
1691                0,
1692                Some(PacketHeaderTruncated),
1693                false,
1694            ),
1695            (
1696                "invalid size",
1697                VERSION_OFFSET,
1698                43,
1699                Some(PacketHeaderSize),
1700                false,
1701            ),
1702            (
1703                "later header",
1704                VERSION_OFFSET,
1705                48,
1706                Some(PacketHeaderUnsupported),
1707                true,
1708            ),
1709            (
1710                "unknown flags",
1711                FLAGS_OFFSET,
1712                3,
1713                Some(PacketHeaderUnsupported),
1714                true,
1715            ),
1716            ("codec", CODEC_OFFSET, 0, Some(PacketCodecMismatch), false),
1717            ("empty", DATA_SIZE_OFFSET, 0, Some(EmptyCodecPayload), false),
1718            (
1719                "truncated",
1720                DATA_SIZE_OFFSET,
1721                9,
1722                Some(PacketTruncated),
1723                false,
1724            ),
1725            (
1726                "trailing",
1727                DATA_SIZE_OFFSET,
1728                7,
1729                Some(PacketLengthsMismatch),
1730                true,
1731            ),
1732        ];
1733        for audio in [false, true] {
1734            let codec = if audio {
1735                EnvelopeCodec::Aac
1736            } else {
1737                EnvelopeCodec::H264
1738            };
1739            for (label, offset, value, expected, receive_accepts) in cases {
1740                let mut bytes = PacketEnvelope::encode(
1741                    codec,
1742                    0,
1743                    0,
1744                    true,
1745                    &[1; 8],
1746                    if audio { &[0x11, 0x90] } else { &[1, 2] },
1747                )
1748                .unwrap();
1749                if *label == "later header" {
1750                    bytes.splice(ENVELOPE_HEADER_BYTES..ENVELOPE_HEADER_BYTES, [0; 4]);
1751                }
1752                if *offset == usize::MAX {
1753                    bytes.truncate(43);
1754                } else {
1755                    bytes[*offset..*offset + 4].copy_from_slice(&value.to_ne_bytes());
1756                }
1757                let send = if audio {
1758                    CompressedFrame::<AudioPacketFormat>::new(
1759                        AudioPacketFormat::new(AudioCodec::Aac, 48_000, 2, 1024).unwrap(),
1760                        bytes.clone(),
1761                    )
1762                    .map(drop)
1763                    .map_err(Rejected::into_error)
1764                } else {
1765                    CompressedFrame::<VideoPacketFormat>::new(h264_format(), bytes.clone())
1766                        .map(drop)
1767                        .map_err(Rejected::into_error)
1768                };
1769                assert_eq!(Some(reason(send)), *expected, "{label}, audio={audio}");
1770                if bytes.len() >= ENVELOPE_HEADER_BYTES {
1771                    let blocks = vec![
1772                        bytes[..ENVELOPE_HEADER_BYTES].to_vec(),
1773                        bytes[ENVELOPE_HEADER_BYTES..].to_vec(),
1774                    ];
1775                    let scatter = if audio {
1776                        ScatterFrame::<AudioPacketFormat>::new(
1777                            AudioPacketFormat::new(AudioCodec::Aac, 48_000, 2, 1024).unwrap(),
1778                            blocks,
1779                        )
1780                        .map(drop)
1781                        .map_err(Rejected::into_error)
1782                    } else {
1783                        ScatterFrame::<VideoPacketFormat>::new(h264_format(), blocks)
1784                            .map(drop)
1785                            .map_err(Rejected::into_error)
1786                    };
1787                    assert_eq!(
1788                        Some(reason(scatter)),
1789                        *expected,
1790                        "scatter {label}, audio={audio}"
1791                    );
1792                }
1793                // SAFETY: both descriptors refer to this live bytes allocation.
1794                let received = unsafe {
1795                    if audio {
1796                        let mut raw = AudioPacketFormat::new(AudioCodec::Aac, 48_000, 2, 1024)
1797                            .unwrap()
1798                            .descriptor(&FrameExtras::default());
1799                        raw.p_data = bytes.as_ptr().cast_mut();
1800                        raw.__bindgen_anon_1.data_size_in_bytes =
1801                            PacketLen::new(bytes.len()).unwrap().to_sdk();
1802                        copy_audio_packet(&raw).map(drop)
1803                    } else {
1804                        let mut raw = h264_format().raw();
1805                        raw.p_data = bytes.as_ptr().cast_mut();
1806                        raw.__bindgen_anon_1.data_size_in_bytes =
1807                            PacketLen::new(bytes.len()).unwrap().to_sdk();
1808                        copy_video_packet(&raw).map(drop)
1809                    }
1810                };
1811                if *receive_accepts {
1812                    assert!(
1813                        received.is_ok(),
1814                        "receive {label}, audio={audio}: {received:?}"
1815                    );
1816                } else {
1817                    assert_eq!(
1818                        Some(reason(received)),
1819                        *expected,
1820                        "receive {label}, audio={audio}"
1821                    );
1822                }
1823            }
1824        }
1825    }
1826
1827    #[cfg(target_pointer_width = "32")]
1828    #[test]
1829    fn envelope_length_overflow_is_independent_of_direction() {
1830        let mut bytes = h264_packet(false, &[]);
1831        bytes[DATA_SIZE_OFFSET..DATA_SIZE_OFFSET + 4].copy_from_slice(&u32::MAX.to_ne_bytes());
1832        for purpose in [Use::Send, Use::Receive] {
1833            assert_eq!(
1834                reason(EnvelopeHeader::read(&bytes).unwrap().validate(
1835                    EnvelopeCodec::H264,
1836                    bytes.len(),
1837                    purpose
1838                )),
1839                crate::FrameDefect::PacketLengthOverflow
1840            );
1841        }
1842    }
1843
1844    #[test]
1845    fn received_packet_and_uncompressed_headers_report_the_same_invalid_fields() {
1846        let valid = NDIlib_video_frame_v2_t {
1847            FourCC: VideoCodec::H264.outer(StreamTier::Program, false),
1848            xres: 16,
1849            yres: 16,
1850            frame_rate_N: 60,
1851            frame_rate_D: 1,
1852            frame_format_type: ScanType::Progressive.to_sdk(),
1853            ..Default::default()
1854        };
1855        let invalid = [
1856            NDIlib_video_frame_v2_t {
1857                frame_rate_N: 0,
1858                ..valid
1859            },
1860            NDIlib_video_frame_v2_t {
1861                frame_rate_N: -1,
1862                ..valid
1863            },
1864            NDIlib_video_frame_v2_t {
1865                frame_rate_D: 0,
1866                ..valid
1867            },
1868            NDIlib_video_frame_v2_t {
1869                frame_rate_D: -1,
1870                ..valid
1871            },
1872            NDIlib_video_frame_v2_t {
1873                picture_aspect_ratio: -1.0,
1874                ..valid
1875            },
1876            NDIlib_video_frame_v2_t {
1877                picture_aspect_ratio: f32::NAN,
1878                ..valid
1879            },
1880            NDIlib_video_frame_v2_t {
1881                picture_aspect_ratio: f32::INFINITY,
1882                ..valid
1883            },
1884            NDIlib_video_frame_v2_t {
1885                frame_format_type: u32::MAX,
1886                ..valid
1887            },
1888        ];
1889        for raw in invalid {
1890            let packet = reason(VideoPacketFormat::from_sdk(&raw).map(drop));
1891            let frame = reason(VideoHeader::from_sdk(&raw).map(drop));
1892            match (&packet, &frame) {
1893                (
1894                    crate::FrameDefect::Layout(crate::LayoutDefect::PictureAspectRatio(a)),
1895                    crate::FrameDefect::Layout(crate::LayoutDefect::PictureAspectRatio(b)),
1896                ) => assert_eq!(a.to_bits(), b.to_bits()),
1897                _ => assert_eq!(packet, frame),
1898            }
1899        }
1900        assert!(matches!(
1901            reason(VideoHeader::from_sdk(&invalid[7]).map(drop)),
1902            crate::FrameDefect::UnknownScanType { code: 0xFFFFFFFF }
1903        ));
1904        for ratio in [-1.0, f32::NAN, f32::INFINITY] {
1905            assert!(matches!(
1906                PictureAspectRatio::new(ratio),
1907                Err(Error::InvalidInput(crate::InputDefect::Layout(
1908                    crate::LayoutDefect::PictureAspectRatio(value)
1909                ))) if value.to_bits() == ratio.to_bits()
1910            ));
1911        }
1912    }
1913
1914    #[test]
1915    fn packed_header_parsing_preserves_extensions_and_checks_bounds() {
1916        let mut bytes =
1917            PacketEnvelope::encode(EnvelopeCodec::H264, 12, -4, true, &[1, 2], &[3]).unwrap();
1918        let p = PacketEnvelope::parse(&bytes).unwrap();
1919        assert_eq!(p.codec(), Some(EnvelopeCodec::H264));
1920        assert_eq!(p.fourcc(), FourCc::from(EnvelopeCodec::H264));
1921        assert_eq!(p.fourcc().raw().to_le_bytes(), *b"H264");
1922        assert_eq!(p.presentation_time(), 12);
1923        assert_eq!(p.decode_time(), -4);
1924        assert!(p.is_keyframe());
1925        assert_eq!(p.data(), &[1, 2]);
1926        assert_eq!(p.extra_data(), &[3]);
1927        bytes.splice(44..44, [9, 8]);
1928        bytes[..4].copy_from_slice(&46i32.to_ne_bytes());
1929        assert_eq!(
1930            PacketEnvelope::parse(&bytes).unwrap().header_extension(),
1931            &[9, 8]
1932        );
1933        assert!(validate_video_packet(h264_format(), &bytes, Use::Receive).is_ok());
1934        assert!(CompressedFrame::<VideoPacketFormat>::new(h264_format(), bytes.clone()).is_err());
1935        bytes[36..40].copy_from_slice(&u32::MAX.to_ne_bytes());
1936        assert!(PacketEnvelope::parse(&bytes).is_err());
1937
1938        // An unknown codec is kept, by its FourCC.
1939        let mut unknown = h264_packet(false, &[]);
1940        unknown[CODEC_OFFSET..CODEC_OFFSET + 4].copy_from_slice(b"AV01");
1941        let p = PacketEnvelope::parse(&unknown).unwrap();
1942        assert_eq!(p.codec(), None);
1943        assert_eq!(p.fourcc(), FourCc::from_raw(u32::from_ne_bytes(*b"AV01")));
1944        for codec in EnvelopeCodec::ALL {
1945            assert_eq!(EnvelopeCodec::try_from(FourCc::from(codec)).unwrap(), codec);
1946        }
1947        assert!(matches!(
1948            EnvelopeCodec::try_from(p.fourcc()),
1949            Err(Error::InvalidFrame(crate::FrameDefect::UnknownEnvelopeCodec { fourcc }))
1950                if fourcc == p.fourcc().raw()
1951        ));
1952    }
1953
1954    #[test]
1955    fn codec_outer_roundtrips_and_opus_is_not_an_envelope() {
1956        for codec in AudioCodec::ALL {
1957            for protected in [false, true] {
1958                assert_eq!(
1959                    AudioCodec::from_outer(codec.outer(protected)),
1960                    Some((codec, protected))
1961                );
1962            }
1963        }
1964        for codec in VideoCodec::ALL {
1965            for tier in [StreamTier::Program, StreamTier::Preview] {
1966                for protected in [false, true] {
1967                    assert_eq!(
1968                        VideoCodec::from_outer(codec.outer(tier, protected)),
1969                        Some((codec, tier, protected))
1970                    );
1971                    let format = VideoPacketFormat::new(codec, 16, 16)
1972                        .unwrap()
1973                        .with_tier(tier)
1974                        .with_protected(protected);
1975                    let bytes = match codec.envelope_codec() {
1976                        Some(code) => PacketEnvelope::encode(code, 0, 0, false, &[1], &[]).unwrap(),
1977                        None => vec![1, 2, 3, 4],
1978                    };
1979                    let mut frame =
1980                        CompressedFrame::<VideoPacketFormat>::new(format, bytes).unwrap();
1981                    let raw = frame.raw();
1982                    assert_eq!(raw.FourCC, codec.outer(tier, protected));
1983                    let copied = unsafe { copy_video_packet(&raw) }.unwrap();
1984                    assert_eq!(copied.format(), format);
1985                    assert_eq!(copied.format().codec(), codec);
1986                    assert_eq!(copied.format().tier(), tier);
1987                    assert_eq!(copied.format().is_protected(), protected);
1988                    assert_eq!(copied.data(), frame.data());
1989                }
1990            }
1991        }
1992        assert!(PacketEnvelope::parse(b"Opus").is_err());
1993    }
1994
1995    #[test]
1996    fn validated_envelopes_agree_for_owned_borrowed_and_received_packets() {
1997        use crate::capture::Guard;
1998
1999        for codec in VideoCodec::ALL {
2000            for tier in [StreamTier::Program, StreamTier::Preview] {
2001                for protected in [false, true] {
2002                    let format = VideoPacketFormat::new(codec, 16, 16)
2003                        .unwrap()
2004                        .with_tier(tier)
2005                        .with_protected(protected);
2006                    let bytes = codec.envelope_codec().map_or_else(
2007                        || vec![1, 2, 3, 4],
2008                        |codec| {
2009                            PacketEnvelope::encode(codec, 17, 13, true, &[1, 2], &[3, 4]).unwrap()
2010                        },
2011                    );
2012                    let mut frame =
2013                        CompressedFrame::<VideoPacketFormat>::new(format, bytes).unwrap();
2014                    if codec.envelope_codec().is_some() {
2015                        assert_eq!(frame.envelope().unwrap().reserved(), 0);
2016                        let raw = frame.raw();
2017                        // SAFETY: the initialized reserved field is inside
2018                        // this exclusively owned frame's validated envelope.
2019                        unsafe {
2020                            std::ptr::copy_nonoverlapping(
2021                                123u64.to_ne_bytes().as_ptr(),
2022                                raw.p_data.add(RESERVED_OFFSET),
2023                                8,
2024                            );
2025                        }
2026                        assert_eq!(frame.envelope().unwrap().reserved(), 123);
2027                    }
2028                    let raw = frame.raw();
2029                    // SAFETY: frame retains the descriptor's initialized
2030                    // bytes until the synthetic non-owning guard is dropped.
2031                    let guard =
2032                        unsafe { Guard::with_test_free(std::ptr::null_mut(), raw, |_, _| {}) };
2033                    let borrowed = CompressedRef::<VideoPacketFormat>::new(guard).unwrap();
2034                    let received = borrowed.to_owned();
2035                    let expected = codec
2036                        .envelope_codec()
2037                        .map(|_| PacketEnvelope::parse(frame.data()).unwrap());
2038                    assert_eq!(frame.envelope(), expected);
2039                    assert_eq!(borrowed.envelope(), expected);
2040                    assert_eq!(received.envelope(), expected);
2041                }
2042            }
2043        }
2044
2045        for codec in AudioCodec::ALL {
2046            for protected in [false, true] {
2047                let (samples, bytes) = match codec {
2048                    AudioCodec::Aac => (1024, testing::aac_packet(48_000, 2, &[1, 2])),
2049                    AudioCodec::Opus => (960, vec![1, 2]),
2050                };
2051                let mut frame = CompressedFrame::<AudioPacketFormat>::new(
2052                    AudioPacketFormat::new(codec, 48_000, 2, samples)
2053                        .unwrap()
2054                        .with_protected(protected),
2055                    bytes,
2056                )
2057                .unwrap();
2058                let raw = frame.raw();
2059                // SAFETY: frame retains all descriptor storage until the
2060                // synthetic non-owning guard is dropped.
2061                let guard = unsafe { Guard::with_test_free(std::ptr::null_mut(), raw, |_, _| {}) };
2062                let borrowed = CompressedRef::<AudioPacketFormat>::new(guard).unwrap();
2063                let received = borrowed.to_owned();
2064                assert_eq!(borrowed.format(), frame.format());
2065                assert_eq!(received.format(), borrowed.format());
2066                let sendable =
2067                    CompressedFrame::<AudioPacketFormat>::try_from(received.clone()).unwrap();
2068                assert_eq!(sendable.format(), borrowed.format());
2069                let expected = (codec == AudioCodec::Aac)
2070                    .then(|| PacketEnvelope::parse(frame.data()).unwrap());
2071                assert_eq!(frame.envelope(), expected);
2072                assert_eq!(borrowed.envelope(), expected);
2073                assert_eq!(received.envelope(), expected);
2074            }
2075        }
2076    }
2077
2078    #[test]
2079    fn audio_packet_formats_validate_quantities_and_preserve_protection() {
2080        fn value_traits<T: Copy + Eq + std::hash::Hash + Send + Sync>() {}
2081        value_traits::<AudioPacketFormat>();
2082        let max = i32::MAX as u32;
2083        let format = AudioPacketFormat::new(AudioCodec::Opus, max, max, max).unwrap();
2084        assert_eq!(
2085            (
2086                format.sample_rate(),
2087                format.num_channels(),
2088                format.num_samples()
2089            ),
2090            (max, max, max)
2091        );
2092        for (sample_rate, channels, samples) in [
2093            (0, 2, 960),
2094            (48_000, 0, 960),
2095            (48_000, 2, 0),
2096            (max + 1, 2, 960),
2097            (48_000, max + 1, 960),
2098            (48_000, 2, max + 1),
2099        ] {
2100            assert!(matches!(
2101                AudioPacketFormat::new(AudioCodec::Opus, sample_rate, channels, samples),
2102                Err(Error::InvalidInput(crate::InputDefect::Layout(_)))
2103            ));
2104        }
2105        let format = AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap();
2106        assert!(!format.is_protected());
2107        assert!(format.with_protected(true).is_protected());
2108        assert_eq!(format.with_protected(true).with_protected(false), format);
2109        let protected = format.with_protected(true);
2110        assert_eq!(
2111            AudioPacketFormat::from_sdk(&protected.descriptor(&FrameExtras::default())).unwrap(),
2112            protected
2113        );
2114    }
2115
2116    #[test]
2117    fn audio_packet_quantities_share_causes_for_api_and_sdk_input() {
2118        for (rate, channels, samples) in [(0, 2, 960), (48_000, 0, 960), (48_000, 2, 0)] {
2119            let api = AudioPacketFormat::new(AudioCodec::Opus, rate, channels, samples);
2120            let raw = NDIlib_audio_frame_v3_t {
2121                sample_rate: rate as i32,
2122                no_channels: channels as i32,
2123                no_samples: samples as i32,
2124                FourCC: AudioCodec::Opus.outer(false),
2125                ..Default::default()
2126            };
2127            let (
2128                Err(Error::InvalidInput(crate::InputDefect::Layout(api))),
2129                Err(Error::InvalidFrame(crate::FrameDefect::Layout(sdk))),
2130            ) = (api, AudioPacketFormat::from_sdk(&raw))
2131            else {
2132                panic!("expected paired layout causes")
2133            };
2134            assert_eq!(api, sdk);
2135            if rate == 0 {
2136                assert_eq!(api, crate::LayoutDefect::AudioRate(0.into()));
2137            }
2138        }
2139    }
2140
2141    /// The dimensions of a format the caller describes are input; those of a
2142    /// frame the SDK delivered belong to the frame.
2143    #[test]
2144    fn packet_format_dimensions_are_checked_on_both_sides_of_the_sdk() {
2145        let max = i32::MAX.unsigned_abs();
2146        let format = VideoPacketFormat::new(VideoCodec::H264, max, 1).unwrap();
2147        assert_eq!((format.width(), format.height()), (max, 1));
2148        for (width, height) in [(0, 1), (1, 0), (max + 1, 1), (1, u32::MAX)] {
2149            assert!(matches!(
2150                VideoPacketFormat::new(VideoCodec::H264, width, height),
2151                Err(Error::InvalidInput(reason)) if matches!(reason, crate::InputDefect::Layout(crate::LayoutDefect::CompressedVideoDimensions {..}))
2152            ));
2153        }
2154        let delivered = h264_format().raw();
2155        for (xres, yres) in [(0, 16), (16, -1), (i32::MIN, 16)] {
2156            let raw = NDIlib_video_frame_v2_t {
2157                xres,
2158                yres,
2159                ..delivered
2160            };
2161            assert!(matches!(
2162                VideoPacketFormat::from_sdk(&raw),
2163                Err(Error::InvalidFrame(_))
2164            ));
2165        }
2166        let raw = NDIlib_video_frame_v2_t {
2167            frame_rate_D: 0,
2168            ..delivered
2169        };
2170        assert!(matches!(
2171            VideoPacketFormat::from_sdk(&raw),
2172            Err(Error::InvalidFrame(_))
2173        ));
2174
2175        let rate = FrameRate::new(60_000, 1001).unwrap();
2176        let format = h264_format()
2177            .with_frame_rate(rate)
2178            .with_scan_type(ScanType::Interlaced);
2179        assert_eq!(h264_format().frame_rate(), FrameRate::new(60, 1).unwrap());
2180        assert_eq!(
2181            (format.frame_rate(), format.scan_type()),
2182            (rate, ScanType::Interlaced)
2183        );
2184        let raw = format.raw();
2185        assert_eq!((raw.frame_rate_N, raw.frame_rate_D), (60_000, 1001));
2186        assert_eq!(VideoPacketFormat::from_sdk(&raw).unwrap(), format);
2187    }
2188
2189    #[test]
2190    fn a_zero_aspect_ratio_means_square_pixels_and_is_kept_when_received() {
2191        let format = h264_format();
2192        assert_eq!(
2193            format.picture_aspect_ratio(),
2194            PictureAspectRatio::SQUARE_PIXELS
2195        );
2196        assert_eq!(
2197            format
2198                .with_picture_aspect_ratio(PictureAspectRatio::SQUARE_PIXELS)
2199                .picture_aspect_ratio(),
2200            PictureAspectRatio::SQUARE_PIXELS
2201        );
2202
2203        // A received frame whose descriptor leaves the ratio unset is kept
2204        // as it is.
2205        let mut frame =
2206            CompressedFrame::<VideoPacketFormat>::new(format, h264_packet(false, &[])).unwrap();
2207        let raw = frame.raw();
2208        assert_eq!(raw.picture_aspect_ratio, 0.0);
2209        let received = unsafe { copy_video_packet(&raw) }.unwrap();
2210        assert_eq!(
2211            received.format().picture_aspect_ratio(),
2212            PictureAspectRatio::SQUARE_PIXELS
2213        );
2214
2215        let wide = NDIlib_video_frame_v2_t {
2216            picture_aspect_ratio: 16.0 / 9.0,
2217            ..raw
2218        };
2219        let received = unsafe { copy_video_packet(&wide) }.unwrap();
2220        assert_eq!(
2221            received.format().picture_aspect_ratio(),
2222            PictureAspectRatio::new(16.0 / 9.0).unwrap()
2223        );
2224
2225        let negative = NDIlib_video_frame_v2_t {
2226            picture_aspect_ratio: -1.0,
2227            ..raw
2228        };
2229        assert!(matches!(
2230            unsafe { copy_video_packet(&negative) },
2231            Err(Error::InvalidFrame(_))
2232        ));
2233    }
2234
2235    #[test]
2236    fn rejected_constructors_return_their_input() {
2237        let rejected =
2238            CompressedFrame::<VideoPacketFormat>::new(h264_format(), vec![7; 20]).unwrap_err();
2239        assert_eq!(rejected.into_inner(), vec![7; 20]);
2240
2241        let format = AudioPacketFormat::new(AudioCodec::Opus, 44_100, 2, 960).unwrap();
2242        let rejected = CompressedFrame::<AudioPacketFormat>::new(format, vec![1, 2]).unwrap_err();
2243        assert!(matches!(
2244            rejected.error(),
2245            Error::InvalidFrame(crate::FrameDefect::OpusSampleRate)
2246        ));
2247        assert_eq!(rejected.into_inner(), [1, 2]);
2248
2249        let mut frame = CompressedFrame::<VideoPacketFormat>::new(
2250            h264_format().with_tier(StreamTier::Preview),
2251            h264_packet(false, &[]),
2252        )
2253        .unwrap();
2254        assert!(matches!(
2255            frame
2256                .set_metadata("nul\0inside")
2257                .map_err(Rejected::into_error),
2258            Err(Error::InvalidCString(_))
2259        ));
2260        assert_eq!(frame.format().tier(), StreamTier::Preview);
2261        assert_eq!(frame.metadata(), None);
2262        frame.set_metadata("<ok/>").unwrap();
2263        assert_eq!(frame.metadata(), Some("<ok/>"));
2264    }
2265
2266    #[test]
2267    fn frame_extras_retain_owned_metadata_storage_until_cleared() {
2268        fn check(extras: &mut FrameExtras) {
2269            let mut text = String::with_capacity(1024);
2270            text.push_str("<metadata label='é'/>");
2271            let (pointer, capacity) = (text.as_ptr(), text.capacity());
2272            let ((), allocations) =
2273                crate::test_alloc::allocation_count(|| extras.set_metadata(text).unwrap());
2274            assert_eq!(allocations, 0);
2275            assert_eq!(extras.metadata().unwrap().as_ptr(), pointer);
2276            assert_eq!(extras.retained_bytes(), capacity);
2277            assert_eq!(extras.to_sdk().2.cast::<u8>(), pointer);
2278
2279            assert!(extras.set_metadata("bad\0metadata").is_err());
2280            assert_eq!(extras.metadata(), Some("<metadata label='é'/>"));
2281            assert_eq!(extras.metadata().unwrap().as_ptr(), pointer);
2282            assert_eq!(extras.retained_bytes(), capacity);
2283            extras.clear_metadata();
2284            assert_eq!(extras.metadata(), None);
2285            assert_eq!(extras.retained_bytes(), 0);
2286            assert!(extras.to_sdk().2.is_null());
2287        }
2288
2289        check(&mut FrameExtras::default());
2290    }
2291
2292    #[test]
2293    fn received_metadata_preserves_presence_and_omits_unreadable_text() {
2294        // SAFETY: all non-null pointers below name live terminated byte strings.
2295        unsafe {
2296            let absent = FrameExtras::received(123, 456, std::ptr::null()).unwrap();
2297            assert_eq!(absent.metadata(), None);
2298            assert_eq!(absent.metadata_status(), crate::FrameMetadataStatus::Absent);
2299            assert!(absent.to_sdk().2.is_null());
2300            for text in [c"", c"<received/>"] {
2301                let extras = FrameExtras::received(123, 456, text.as_ptr()).unwrap();
2302                assert_eq!(extras.metadata(), Some(text.to_str().unwrap()));
2303                assert_eq!(extras.metadata_status(), crate::FrameMetadataStatus::Text);
2304                assert_eq!(extras.retained_bytes(), text.to_bytes_with_nul().len());
2305                assert_eq!(std::ffi::CStr::from_ptr(extras.to_sdk().2), text);
2306                assert_eq!(extras.timecode().ticks(), 123);
2307                assert_eq!(extras.timestamp().unwrap().ticks(), 456);
2308            }
2309            let unterminated = vec![b'x'; crate::frames::MAX_METADATA_BYTES];
2310            for (pointer, status) in [
2311                (c"\xff".as_ptr(), crate::FrameMetadataStatus::NotUtf8),
2312                (
2313                    unterminated.as_ptr().cast(),
2314                    crate::FrameMetadataStatus::Unterminated,
2315                ),
2316            ] {
2317                let (extras, allocations) = crate::test_alloc::allocation_count(|| {
2318                    FrameExtras::received(123, 456, pointer).unwrap()
2319                });
2320                assert_eq!(allocations, 0);
2321                assert_eq!(extras.metadata(), None);
2322                assert_eq!(extras.metadata_status(), status);
2323                assert!(extras.to_sdk().2.is_null());
2324            }
2325        }
2326    }
2327
2328    #[test]
2329    fn protected_aac_preserves_codec_high_bit() {
2330        let bytes = aac_packet(48_000, 2, &[1]);
2331        let mut frame = CompressedFrame::<AudioPacketFormat>::new(
2332            AudioPacketFormat::new(AudioCodec::Aac, 48_000, 2, 1024).unwrap(),
2333            bytes,
2334        )
2335        .unwrap();
2336        let mut raw = frame.raw();
2337        raw.FourCC = AudioCodec::Aac.outer(true);
2338        let copied = unsafe { copy_audio_packet(&raw) }.unwrap();
2339        assert_eq!(copied.format().codec(), AudioCodec::Aac);
2340        assert!(copied.format().is_protected());
2341        assert_eq!(
2342            (
2343                copied.format().sample_rate(),
2344                copied.format().num_channels(),
2345                copied.format().num_samples()
2346            ),
2347            (48_000, 2, 1024)
2348        );
2349        assert_eq!(copied.data(), frame.data());
2350    }
2351
2352    #[test]
2353    fn unknown_native_enum_bits_are_rejected_without_truncation() {
2354        for bits in [0x8000_0000, PROTECTED, u32::MAX] {
2355            let video = NDIlib_video_frame_v2_t {
2356                FourCC: bits,
2357                ..Default::default()
2358            };
2359            let audio = NDIlib_audio_frame_v3_t {
2360                FourCC: bits,
2361                ..Default::default()
2362            };
2363            assert!(unsafe { copy_video_packet(&video) }.is_err());
2364            assert!(unsafe { copy_audio_packet(&audio) }.is_err());
2365        }
2366        let mut video = h264_format().raw();
2367        video.frame_format_type = u32::MAX;
2368        assert!(unsafe { copy_video_packet(&video) }.is_err());
2369    }
2370
2371    /// Received audio whose parameters are not positive is an invalid frame,
2372    /// whatever its bytes.
2373    #[test]
2374    fn delivered_audio_parameters_are_validated_before_they_become_unsigned() {
2375        let mut frame = CompressedFrame::<AudioPacketFormat>::new(
2376            AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap(),
2377            vec![1; 8],
2378        )
2379        .unwrap();
2380        let raw = frame.raw();
2381        for (sample_rate, no_channels, no_samples) in
2382            [(0, 2, 960), (48_000, -2, 960), (48_000, 2, 0)]
2383        {
2384            let delivered = NDIlib_audio_frame_v3_t {
2385                sample_rate,
2386                no_channels,
2387                no_samples,
2388                ..raw
2389            };
2390            assert!(matches!(
2391                unsafe { copy_audio_packet(&delivered) },
2392                Err(Error::InvalidFrame(_))
2393            ));
2394        }
2395    }
2396
2397    #[test]
2398    fn receiving_keeps_unknown_flags_but_sending_rejects_them() {
2399        let mut bytes = h264_packet(false, &[]);
2400        bytes[FLAGS_OFFSET..FLAGS_OFFSET + 4].copy_from_slice(&2u32.to_ne_bytes());
2401        let format = h264_format();
2402        assert_eq!(PacketEnvelope::parse(&bytes).unwrap().flags(), 2);
2403        assert!(validate_video_packet(format, &bytes, Use::Receive).is_ok());
2404        assert!(validate_video_packet(format, &bytes, Use::Send).is_err());
2405    }
2406
2407    #[test]
2408    fn envelope_slices_keep_admitted_extents_after_native_header_writes() {
2409        let overwrite = |data: *mut u8| {
2410            // SAFETY: each caller passes the writable header from its own
2411            // live frame's descriptor, with a complete version-0 header.
2412            unsafe {
2413                data.add(VERSION_OFFSET).cast::<i32>().write_unaligned(-1);
2414                data.add(DATA_SIZE_OFFSET)
2415                    .cast::<u32>()
2416                    .write_unaligned(u32::MAX);
2417                data.add(EXTRA_DATA_SIZE_OFFSET)
2418                    .cast::<u32>()
2419                    .write_unaligned(u32::MAX);
2420                data.add(RESERVED_OFFSET).cast::<u64>().write_unaligned(42);
2421            }
2422        };
2423        let assert_envelope = |view: PacketEnvelope<'_>, codec, config: &[u8]| {
2424            assert_eq!(view.codec(), Some(codec));
2425            assert!(view.is_known_version());
2426            assert!(view.header_extension().is_empty());
2427            assert_eq!(view.data(), &[1, 2]);
2428            assert_eq!(view.extra_data(), config);
2429            assert!(view.trailing_bytes().is_empty());
2430            assert_eq!(view.reserved(), 42);
2431        };
2432
2433        for (codec, envelope) in [
2434            (VideoCodec::H264, EnvelopeCodec::H264),
2435            (VideoCodec::Hevc, EnvelopeCodec::Hevc),
2436        ] {
2437            let format = VideoPacketFormat::new(codec, 1920, 1080).unwrap();
2438            let bytes = PacketEnvelope::encode(envelope, 0, 0, true, &[1, 2], &[3]).unwrap();
2439            let mut frame = CompressedFrame::<VideoPacketFormat>::new(format, bytes).unwrap();
2440            overwrite(frame.raw().p_data);
2441            assert_envelope(frame.envelope().unwrap(), envelope, &[3]);
2442            let received = ReceivedPacket::<VideoPacketFormat>::from(frame);
2443            assert_envelope(received.envelope().unwrap(), envelope, &[3]);
2444        }
2445
2446        let mut frame = CompressedFrame::<AudioPacketFormat>::new(
2447            AudioPacketFormat::new(AudioCodec::Aac, 48_000, 2, 1024).unwrap(),
2448            aac_packet(48_000, 2, &[1, 2]),
2449        )
2450        .unwrap();
2451        overwrite(frame.raw().p_data);
2452        assert_envelope(frame.envelope().unwrap(), EnvelopeCodec::Aac, &[0x11, 0x90]);
2453        let received = ReceivedPacket::<AudioPacketFormat>::from(frame);
2454        assert_envelope(
2455            received.envelope().unwrap(),
2456            EnvelopeCodec::Aac,
2457            &[0x11, 0x90],
2458        );
2459    }
2460
2461    /// The SDK stamps the reserved field of every envelope it sends, in the
2462    /// sender's buffer, and delivers packets with the field set. Neither a
2463    /// frame that has been sent nor one that was received may be refused for
2464    /// it.
2465    #[test]
2466    fn the_reserved_field_never_decides_whether_a_packet_can_be_sent() {
2467        let format = h264_format();
2468        let stamp = |bytes: &mut [u8], value: u64| {
2469            bytes[RESERVED_OFFSET..RESERVED_OFFSET + 8].copy_from_slice(&value.to_ne_bytes());
2470        };
2471
2472        // As received: any value, on video and on audio.
2473        for value in [1, 1533, u64::MAX] {
2474            let mut video = h264_packet(true, &[2]);
2475            stamp(&mut video, value);
2476            assert_eq!(PacketEnvelope::parse(&video).unwrap().reserved(), value);
2477            let frame = CompressedFrame::<VideoPacketFormat>::new(format, video).unwrap();
2478            ReceivedPacket::<VideoPacketFormat>::from(frame.clone())
2479                .validate_for_send()
2480                .unwrap();
2481
2482            let mut audio = aac_packet(48_000, 2, &[1]);
2483            stamp(&mut audio, value);
2484            let frame = CompressedFrame::<AudioPacketFormat>::new(
2485                AudioPacketFormat::new(AudioCodec::Aac, 48_000, 2, 1024).unwrap(),
2486                audio,
2487            )
2488            .unwrap();
2489            ReceivedPacket::<AudioPacketFormat>::from(frame.clone())
2490                .validate_for_send()
2491                .unwrap();
2492        }
2493
2494        // As sent: the SDK writes through the pointer the descriptor lends.
2495        let mut frame =
2496            CompressedFrame::<VideoPacketFormat>::new(format, h264_packet(true, &[2])).unwrap();
2497        for value in 1..=2u64 {
2498            let raw = frame.raw();
2499            // SAFETY: the descriptor lends the frame's own bytes, which hold a
2500            // complete header, and the frame is borrowed exclusively.
2501            unsafe {
2502                raw.p_data
2503                    .add(RESERVED_OFFSET)
2504                    .cast::<u64>()
2505                    .write_unaligned(value)
2506            };
2507            assert_eq!(
2508                PacketEnvelope::parse(frame.data()).unwrap().reserved(),
2509                value
2510            );
2511            ReceivedPacket::<VideoPacketFormat>::from(frame.clone())
2512                .validate_for_send()
2513                .unwrap();
2514        }
2515    }
2516
2517    #[test]
2518    fn video_is_admitted_only_when_the_sdk_delivers_it() {
2519        let video = |format: VideoPacketFormat, bytes: Vec<u8>| {
2520            CompressedFrame::<VideoPacketFormat>::new(format, bytes)
2521                .map(drop)
2522                .map_err(Rejected::into_error)
2523        };
2524        // A SpeedHQ frame states its quality in its first byte.
2525        for codec in [
2526            VideoCodec::SpeedHq420,
2527            VideoCodec::SpeedHq422,
2528            VideoCodec::SpeedHq422Alpha,
2529        ] {
2530            for tier in [StreamTier::Program, StreamTier::Preview] {
2531                let format = VideoPacketFormat::new(codec, 1920, 1080)
2532                    .unwrap()
2533                    .with_tier(tier);
2534                for quality in [0, 1, 99] {
2535                    video(format, vec![quality, 0, 0, 0]).unwrap();
2536                }
2537                for quality in [100, 101, 255] {
2538                    assert!(matches!(
2539                        reason(video(format, vec![quality, 0, 0, 0])),
2540                        crate::FrameDefect::SpeedHqQuality
2541                    ));
2542                    // A received frame is kept whatever it holds.
2543                    assert!(
2544                        validate_video_packet(format, &[quality, 0, 0, 0], Use::Receive).is_ok()
2545                    );
2546                }
2547                assert!(matches!(
2548                    reason(video(format, vec![0; 3])),
2549                    crate::FrameDefect::SpeedHqTruncated
2550                ));
2551            }
2552        }
2553
2554        // The preview stream of an envelope codec fits in 640 by 640.
2555        let keyframe = |codec: VideoCodec| {
2556            PacketEnvelope::encode(codec.envelope_codec().unwrap(), 0, 0, true, &[1], &[2]).unwrap()
2557        };
2558        for codec in [
2559            VideoCodec::H264,
2560            VideoCodec::Hevc,
2561            VideoCodec::H264Alpha,
2562            VideoCodec::HevcAlpha,
2563        ] {
2564            let preview = |width, height| {
2565                let format = VideoPacketFormat::new(codec, width, height)
2566                    .unwrap()
2567                    .with_tier(StreamTier::Preview);
2568                video(format, keyframe(codec))
2569            };
2570            for (width, height) in [(640, 360), (360, 640), (640, 640), (1, 1)] {
2571                preview(width, height).unwrap();
2572            }
2573            for (width, height) in [(641, 360), (640, 641), (1280, 720), (2, 2000)] {
2574                assert!(matches!(
2575                    reason(preview(width, height)),
2576                    crate::FrameDefect::PreviewVideoDimensions
2577                ));
2578                let format = VideoPacketFormat::new(codec, width, height).unwrap();
2579                // The program stream has no such limit, and neither has a
2580                // frame that was received.
2581                video(format, keyframe(codec)).unwrap();
2582                let format = format.with_tier(StreamTier::Preview);
2583                assert!(validate_video_packet(format, &keyframe(codec), Use::Receive).is_ok());
2584            }
2585        }
2586        // SpeedHQ previews are not limited.
2587        let format = VideoPacketFormat::new(VideoCodec::SpeedHq422, 1920, 1080)
2588            .unwrap()
2589            .with_tier(StreamTier::Preview);
2590        video(format, vec![0; 4]).unwrap();
2591    }
2592
2593    #[test]
2594    fn an_aac_envelope_always_carries_the_keyframe_flag() {
2595        let config = aac_config(48_000, 2);
2596        for keyframe in [false, true] {
2597            let packet =
2598                PacketEnvelope::encode(EnvelopeCodec::Aac, 0, 0, keyframe, &[1], &config).unwrap();
2599            assert!(PacketEnvelope::parse(&packet).unwrap().is_keyframe());
2600            aac(48_000, 2, 1024, packet).unwrap();
2601        }
2602        // The flag stays the caller's choice for video.
2603        assert!(!PacketEnvelope::parse(&h264_packet(false, &[]))
2604            .unwrap()
2605            .is_keyframe());
2606
2607        // An AAC packet from elsewhere without the flag is kept when received
2608        // and refused when sent: the SDK would drop it without a word.
2609        let mut packet = aac_packet(48_000, 2, &[1]);
2610        packet[FLAGS_OFFSET..FLAGS_OFFSET + 4].copy_from_slice(&0u32.to_ne_bytes());
2611        let mut descriptor = AudioPacketFormat::new(AudioCodec::Aac, 48_000, 2, 1024)
2612            .unwrap()
2613            .descriptor(&FrameExtras::default());
2614        descriptor.p_data = packet.as_mut_ptr();
2615        descriptor.__bindgen_anon_1.data_size_in_bytes = i32::try_from(packet.len()).unwrap();
2616        // SAFETY: packet owns the readable payload without metadata.
2617        let received = unsafe { copy_audio_packet(&descriptor) }.unwrap();
2618        assert!(matches!(
2619            reason(received.validate_for_send()),
2620            crate::FrameDefect::AacKeyframeMissing
2621        ));
2622        assert!(matches!(
2623            reason(aac(48_000, 2, 1024, packet)),
2624            crate::FrameDefect::AacKeyframeMissing
2625        ));
2626    }
2627
2628    #[test]
2629    fn opus_is_admitted_only_at_the_rates_and_durations_the_sdk_delivers() {
2630        for rate in [8_000, 12_000, 16_000, 24_000, 48_000] {
2631            // 2.5, 5, 10, 20, 40 and 60 ms.
2632            for units in [1, 2, 4, 8, 16, 24] {
2633                opus(rate, 2, rate / 400 * units).unwrap();
2634            }
2635            // 7.5, 15, 30, 80 and 120 ms.
2636            for units in [3, 6, 12, 32, 48] {
2637                assert!(matches!(
2638                    reason(opus(rate, 2, rate / 400 * units)),
2639                    crate::FrameDefect::OpusDuration
2640                ));
2641            }
2642            assert!(matches!(
2643                reason(opus(rate, 2, rate / 400 + 1)),
2644                crate::FrameDefect::OpusDuration
2645            ));
2646        }
2647        for rate in [11_025, 22_050, 32_000, 44_100, 96_000] {
2648            assert!(matches!(
2649                reason(opus(rate, 2, rate / 50)),
2650                crate::FrameDefect::OpusSampleRate
2651            ));
2652        }
2653        for channels in [1, 2, 6, 255] {
2654            opus(48_000, channels, 960).unwrap();
2655        }
2656        assert!(matches!(
2657            opus(48_000, 0, 960),
2658            Err(Error::InvalidInput(crate::InputDefect::Layout(
2659                crate::LayoutDefect::AudioCount {
2660                    kind: crate::AudioCountKind::Channels,
2661                    ..
2662                }
2663            )))
2664        ));
2665    }
2666
2667    #[test]
2668    fn aac_is_admitted_only_with_a_configuration_that_matches_the_frame() {
2669        for rate in AAC_SAMPLE_RATES {
2670            aac(rate, 2, 1024, aac_packet(rate, 2, &[1])).unwrap();
2671        }
2672        for channels in AAC_CHANNELS {
2673            aac(48_000, channels, 1024, aac_packet(48_000, channels, &[1])).unwrap();
2674        }
2675
2676        for samples in [1, 512, 960, 2048] {
2677            let result = aac(48_000, 2, samples, aac_packet(48_000, 2, &[1]));
2678            assert!(matches!(reason(result), crate::FrameDefect::AacSampleCount));
2679        }
2680        assert!(matches!(
2681            reason(aac(50_000, 2, 1024, aac_packet(48_000, 2, &[1]))),
2682            crate::FrameDefect::AacSampleRate
2683        ));
2684        assert!(matches!(
2685            reason(aac(48_000, 7, 1024, aac_packet(48_000, 8, &[1]))),
2686            crate::FrameDefect::AacChannels
2687        ));
2688
2689        // A configuration for another rate or layout than the frame's.
2690        let result = aac(44_100, 2, 1024, aac_packet(48_000, 2, &[1]));
2691        assert!(matches!(
2692            reason(result),
2693            crate::FrameDefect::AacRateMismatch
2694        ));
2695        let result = aac(48_000, 1, 1024, aac_packet(48_000, 2, &[1]));
2696        assert!(matches!(
2697            reason(result),
2698            crate::FrameDefect::AacChannelsMismatch
2699        ));
2700
2701        // No configuration, and one too short to name a rate and a layout.
2702        for config in [&[][..], &[0x11][..]] {
2703            let packet =
2704                PacketEnvelope::encode(EnvelopeCodec::Aac, 0, 0, true, &[1], config).unwrap();
2705            assert!(matches!(
2706                reason(aac(48_000, 2, 1024, packet)),
2707                crate::FrameDefect::AacConfigurationMissing
2708            ));
2709        }
2710        // A longer configuration is read by its first two bytes.
2711        let mut config = aac_config(48_000, 2).to_vec();
2712        config.extend([0x56, 0xe5, 0x00]);
2713        let packet = PacketEnvelope::encode(EnvelopeCodec::Aac, 0, 0, true, &[1], &config).unwrap();
2714        aac(48_000, 2, 1024, packet).unwrap();
2715
2716        // Sample rates and layouts the configuration has no index for.
2717        let unindexed = |frequency_index: u16, channel_configuration: u16| {
2718            let config = ((2u16 << 11) | (frequency_index << 7) | (channel_configuration << 3))
2719                .to_be_bytes();
2720            let packet =
2721                PacketEnvelope::encode(EnvelopeCodec::Aac, 0, 0, true, &[1], &config).unwrap();
2722            reason(aac(48_000, 2, 1024, packet))
2723        };
2724        assert!(matches!(
2725            unindexed(15, 2),
2726            crate::FrameDefect::AacRateMismatch
2727        ));
2728        assert!(matches!(
2729            unindexed(3, 0),
2730            crate::FrameDefect::AacChannelsMismatch
2731        ));
2732        assert!(matches!(
2733            unindexed(3, 8),
2734            crate::FrameDefect::AacChannelsMismatch
2735        ));
2736    }
2737
2738    /// A frame built for sending carries no timestamp, and its descriptor
2739    /// says so; a received frame keeps the timecode and timestamp the SDK
2740    /// delivered.
2741    #[test]
2742    fn received_frames_keep_their_timecode_and_timestamp() {
2743        let mut video =
2744            CompressedFrame::<VideoPacketFormat>::new(h264_format(), h264_packet(false, &[]))
2745                .unwrap();
2746        video.set_timecode(Timecode::from_ticks(17));
2747        assert_eq!(video.timestamp(), None);
2748        let raw = video.raw();
2749        assert_eq!(raw.timecode, 17);
2750        assert_eq!(raw.timestamp, NDIlib_recv_timestamp_undefined);
2751        let delivered = NDIlib_video_frame_v2_t {
2752            timestamp: 4242,
2753            ..raw
2754        };
2755        let received = unsafe { copy_video_packet(&delivered) }.unwrap();
2756        assert_eq!(received.timecode(), Timecode::from_ticks(17));
2757        assert_eq!(received.timestamp(), ReceivedTimestamp::from_sdk(4242));
2758        // Relaying a received frame hands the SDK what it delivered.
2759        assert_eq!(
2760            CompressedFrame::<VideoPacketFormat>::try_from(received.clone())
2761                .unwrap()
2762                .raw()
2763                .timestamp,
2764            4242
2765        );
2766        let received = unsafe { copy_video_packet(&raw) }.unwrap();
2767        assert_eq!(received.timestamp(), None);
2768
2769        let mut audio = CompressedFrame::<AudioPacketFormat>::new(
2770            AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap(),
2771            vec![1; 8],
2772        )
2773        .unwrap();
2774        audio.set_timecode(Timecode::from_ticks(-5));
2775        assert_eq!(audio.timecode(), Timecode::from_ticks(-5));
2776        let delivered = NDIlib_audio_frame_v3_t {
2777            timestamp: 99,
2778            ..audio.raw()
2779        };
2780        let received = unsafe { copy_audio_packet(&delivered) }.unwrap();
2781        assert_eq!(received.timecode(), Timecode::from_ticks(-5));
2782        assert_eq!(received.timestamp(), ReceivedTimestamp::from_sdk(99));
2783    }
2784
2785    /// A clone owns its own copy of the bytes, so the SDK's writes to one
2786    /// never show in the other.
2787    #[test]
2788    fn a_cloned_frame_owns_a_copy_of_its_bytes() {
2789        let mut frame =
2790            CompressedFrame::<VideoPacketFormat>::new(h264_format(), h264_packet(true, &[2]))
2791                .unwrap();
2792        frame.set_metadata("<copy/>").unwrap();
2793        let mut copy = frame.clone();
2794        assert_eq!(copy.data(), frame.data());
2795        assert_ne!(copy.data().as_ptr(), frame.data().as_ptr());
2796        assert_eq!(copy.metadata(), Some("<copy/>"));
2797        let raw = copy.raw();
2798        // SAFETY: the descriptor lends the copy's own bytes, which hold a
2799        // complete header, and the copy is borrowed exclusively.
2800        unsafe { raw.p_data.add(RESERVED_OFFSET).write(7) };
2801        assert_eq!(copy.data()[RESERVED_OFFSET], 7);
2802        assert_eq!(frame.data()[RESERVED_OFFSET], 0);
2803
2804        let audio = CompressedFrame::<AudioPacketFormat>::new(
2805            AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960)
2806                .unwrap()
2807                .with_protected(true),
2808            vec![1; 8],
2809        )
2810        .unwrap();
2811        let copy = audio.clone();
2812        assert_eq!(
2813            (
2814                copy.data(),
2815                copy.format().is_protected(),
2816                copy.format().num_samples()
2817            ),
2818            (audio.data(), true, 960)
2819        );
2820    }
2821
2822    #[test]
2823    fn descriptors_keep_the_defaults_of_the_fields_they_do_not_set() {
2824        let video = h264_format().raw();
2825        assert_eq!(video.timecode, NDIlib_send_timecode_synthesize);
2826        assert!(video.p_data.is_null() && video.p_metadata.is_null());
2827        assert_eq!(video.timestamp, 0);
2828
2829        let mut frame = CompressedFrame::<AudioPacketFormat>::new(
2830            AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap(),
2831            vec![1; 8],
2832        )
2833        .unwrap();
2834        let audio = frame.raw();
2835        assert_eq!(audio.timecode, NDIlib_send_timecode_synthesize);
2836        assert_eq!(audio.FourCC, AudioCodec::Opus.outer(false));
2837        // A frame built for sending has no timestamp; the SDK ignores the
2838        // field when it sends.
2839        assert_eq!(audio.timestamp, NDIlib_recv_timestamp_undefined);
2840        assert!(audio.p_metadata.is_null());
2841    }
2842    #[test]
2843    fn all_compressed_metadata_setters_return_the_original_text() {
2844        macro_rules! check {
2845            ($frame:expr) => {{
2846                let mut frame = $frame;
2847                frame.set_metadata("previous").unwrap();
2848                for text in [
2849                    "<ok/>\0tail".to_owned(),
2850                    "x".repeat(crate::frames::MAX_METADATA_BYTES),
2851                ] {
2852                    let pointer = text.as_ptr();
2853                    let capacity = text.capacity();
2854                    let oversized = text.len() == crate::frames::MAX_METADATA_BYTES;
2855                    let (result, allocations) =
2856                        crate::test_alloc::allocation_count(|| frame.set_metadata(text));
2857                    assert_eq!(allocations, if oversized { 1 } else { 2 });
2858                    let (error, text) = result.unwrap_err().into_parts();
2859                    assert_eq!(text.as_ptr(), pointer);
2860                    assert_eq!(text.capacity(), capacity);
2861                    assert!(matches!(
2862                        error,
2863                        Error::InvalidFrame(_) | Error::InvalidCString(_)
2864                    ));
2865                    assert_eq!(frame.metadata(), Some("previous"));
2866                    assert_eq!(frame.metadata_status(), crate::FrameMetadataStatus::Text);
2867                }
2868            }};
2869        }
2870        check!(
2871            CompressedFrame::<VideoPacketFormat>::new(h264_format(), h264_packet(false, &[]))
2872                .unwrap()
2873        );
2874        check!(CompressedFrame::<AudioPacketFormat>::new(
2875            AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap(),
2876            vec![1, 2]
2877        )
2878        .unwrap());
2879        check!(ScatterFrame::<VideoPacketFormat>::new(
2880            h264_format(),
2881            vec![h264_packet(false, &[])]
2882        )
2883        .unwrap());
2884        check!(ScatterFrame::<AudioPacketFormat>::new(
2885            AudioPacketFormat::new(AudioCodec::Opus, 48_000, 2, 960).unwrap(),
2886            vec![vec![1, 2]]
2887        )
2888        .unwrap());
2889    }
2890}
2891
2892#[cfg(any(ndi_test_packet_payload, ndi_test_packet_payload_mutation))]
2893#[path = "../../tests/ui/internal/packet_payload.rs"]
2894mod privacy_fixture;