Skip to main content

grafton_ndi/
frames.rs

1//! Frame types for video, audio, and metadata.
2
3use std::{ffi::CStr, fmt, marker::PhantomData, mem::size_of, os::raw::c_char, slice};
4
5#[cfg(test)]
6use std::{ffi::CString, ptr, str};
7
8use crate::{
9    capture::{
10        AudioKind, FrameFree, FrameSyncAudioFree, FrameSyncVideoFree, Guard, RecvMetadataGuard,
11        SenderMetadataFree, VideoKind,
12    },
13    framesync::{AudioInputFormat, FrameSyncAudioRef, FrameSyncVideoRef},
14    media::SdkQuantity,
15    pixels::{AudioCopy, PackedStorage, PackedVideo, VideoCopy, VideoStorage},
16    sys::{self, bindings::*},
17    Error, FourCc, FrameRate, PictureAspectRatio, ReceivedTimestamp, Rejected, Result, Timecode,
18};
19
20#[cfg(feature = "advanced")]
21use crate::{advanced::AvSyncAudioRef, capture::AvSyncAudioFree};
22
23/// The uncompressed pixel formats NDI sends and receives.
24///
25/// Each converts to and from its [`FourCc`].
26/// The most common formats are BGRA/RGBA for full quality and UYVY for bandwidth-efficient streaming.
27///
28/// This enum is marked `#[non_exhaustive]` to allow future NDI SDK versions to add new formats
29/// without breaking existing code. Always use a wildcard pattern when matching.
30///
31/// # Examples
32///
33/// ```
34/// use grafton_ndi::PixelFormat;
35///
36/// // For maximum compatibility and quality
37/// let format = PixelFormat::Bgra;
38///
39/// // For bandwidth-efficient streaming
40/// let format = PixelFormat::Uyvy;
41///
42/// // When matching, always include a wildcard for forward compatibility
43/// match format {
44///     PixelFormat::Bgra | PixelFormat::Rgba => println!("Full quality RGB"),
45///     PixelFormat::Uyvy => println!("4:2:2 YUV"),
46///     _ => println!("Other format"),
47/// }
48/// ```
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50#[non_exhaustive]
51// Each discriminant is the format's SDK FourCC value.
52#[repr(u32)]
53pub enum PixelFormat {
54    /// YCbCr 4:2:2 format (16 bits per pixel) - bandwidth efficient.
55    Uyvy = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_UYVY,
56    /// YCbCr 4:2:2 with alpha channel (24 bits per pixel).
57    Uyva = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_UYVA,
58    /// 16-bit YCbCr 4:2:2 format.
59    P216 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_P216,
60    /// 16-bit YCbCr 4:2:2 with alpha.
61    Pa16 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_PA16,
62    /// Planar YCbCr 4:2:0 format (12 bits per pixel).
63    Yv12 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_YV12,
64    /// Planar YCbCr 4:2:0 format (12 bits per pixel).
65    I420 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_I420,
66    /// Semi-planar YCbCr 4:2:0 format (12 bits per pixel).
67    Nv12 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_NV12,
68    /// Blue-Green-Red-Alpha format (32 bits per pixel) - full quality.
69    Bgra = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_BGRA,
70    /// Blue-Green-Red with padding (32 bits per pixel).
71    Bgrx = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_BGRX,
72    /// Red-Green-Blue-Alpha format (32 bits per pixel) - full quality.
73    Rgba = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_RGBA,
74    /// Red-Green-Blue with padding (32 bits per pixel).
75    Rgbx = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_RGBX,
76    /// Full-resolution planar Y, U, V with 8-bit samples. Sending it needs
77    /// [`RuntimeFeature::Planar444Video`](crate::RuntimeFeature::Planar444Video).
78    Na48 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_NA48,
79    /// Full-resolution planar Y, U, V, alpha with 8-bit samples. Sending it
80    /// needs [`RuntimeFeature::Planar444Video`](crate::RuntimeFeature::Planar444Video).
81    Nb48 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_NB48,
82    /// Full-resolution planar Y, U, V with 16-bit samples. Sending it needs
83    /// [`RuntimeFeature::Planar444Video`](crate::RuntimeFeature::Planar444Video).
84    Na4g = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_NA4G,
85    /// Full-resolution planar Y, U, V, alpha with 16-bit samples. Sending it
86    /// needs [`RuntimeFeature::Planar444Video`](crate::RuntimeFeature::Planar444Video).
87    Nb4g = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_NB4G,
88}
89
90/// Plane structure used by buffer sizing and plane views.
91///
92/// This enum distinguishes between different memory layouts:
93/// - **Packed**: All pixel components are interleaved in a single buffer
94/// - **Planar420**: Y, U, V planes stored separately with 4:2:0 chroma subsampling
95/// - **SemiPlanar420**: Y plane followed by interleaved UV plane (NV12)
96/// - **PackedAlpha**: Packed 4:2:2 plane followed by an 8-bit alpha plane (UYVA)
97/// - **SemiPlanar422**: 16-bit Y plane followed by interleaved CbCr plane (P216)
98/// - **SemiPlanar422Alpha**: [`FormatCategory::SemiPlanar422`] followed by a
99///   16-bit alpha plane (PA16)
100/// - **Planar444**: Three full-resolution Y, U, V planes
101/// - **Planar444Alpha**: Four full-resolution Y, U, V, alpha planes
102///
103/// This enum is marked `#[non_exhaustive]` because the NDI SDK's video FourCC
104/// namespace is open and grows across releases; future formats may introduce
105/// additional memory-layout categories.
106#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
107#[non_exhaustive]
108pub enum FormatCategory {
109    /// Packed formats: simple stride * height buffer.
110    Packed,
111    /// Planar 4:2:0 with separate U and V planes (YV12, I420).
112    Planar420,
113    /// Semi-planar 4:2:0 with interleaved UV plane (NV12).
114    SemiPlanar420,
115    /// Packed UYVY plane followed by an 8-bit alpha plane whose stride is half
116    /// the line stride (UYVA).
117    PackedAlpha,
118    /// Semi-planar 4:2:2 with a 16-bit Y plane followed by an interleaved
119    /// 16-bit CbCr plane, both full height at the line stride (P216).
120    SemiPlanar422,
121    /// [`FormatCategory::SemiPlanar422`] followed by a 16-bit alpha plane at
122    /// the line stride (PA16).
123    SemiPlanar422Alpha,
124    /// Three full-resolution Y, U, V planes with equal byte strides.
125    Planar444,
126    /// Four full-resolution Y, U, V, alpha planes with equal byte strides.
127    Planar444Alpha,
128}
129
130/// Width of one component sample, independent of packed bytes per pixel.
131#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
132pub(crate) enum PixelSampleWidth {
133    Eight,
134    Sixteen,
135}
136impl PixelSampleWidth {
137    #[cfg(feature = "image-encoding")]
138    pub(crate) const fn bits(self) -> u32 {
139        match self {
140            Self::Eight => 8,
141            Self::Sixteen => 16,
142        }
143    }
144}
145
146/// Memory order of the two separate chroma planes.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
148enum ChromaOrder {
149    CbCr,
150    CrCb,
151}
152
153/// Compile-time pixel format properties.
154///
155/// Records first-plane bytes per pixel, plane category, alpha presence and
156/// sample width. See [`PixelFormat::buffer_len`] for storage size and
157/// [`PixelFormat::send_tail_room`] for the SDK's extra readable send bytes.
158///
159/// # Examples
160///
161/// ```
162/// use grafton_ndi::{PixelFormat, FormatCategory};
163///
164/// let info = PixelFormat::Bgra.info();
165/// assert_eq!(info.bytes_per_pixel(), 4);
166/// assert_eq!(info.category(), FormatCategory::Packed);
167///
168/// let info = PixelFormat::Nv12.info();
169/// assert_eq!(info.bytes_per_pixel(), 1);
170/// assert_eq!(info.category(), FormatCategory::SemiPlanar420);
171/// ```
172#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
173pub struct PixelFormatInfo {
174    /// Bytes per pixel for packed formats, or first-plane bytes per pixel for
175    /// planar and semi-planar formats.
176    bytes_per_pixel: u8,
177    /// Plane structure for buffer sizing and plane views.
178    category: FormatCategory,
179    has_alpha: bool,
180    sample_width: PixelSampleWidth,
181    chroma_order: ChromaOrder,
182}
183
184impl PixelFormatInfo {
185    /// Get bytes per pixel for packed formats, or first-plane bytes per pixel
186    /// for planar and semi-planar formats (the Y plane, or the UYVY plane of
187    /// UYVA).
188    #[must_use]
189    pub const fn bytes_per_pixel(&self) -> u8 {
190        self.bytes_per_pixel
191    }
192
193    /// Get the format category.
194    #[must_use]
195    pub const fn category(&self) -> FormatCategory {
196        self.category
197    }
198
199    /// Whether this format defines an alpha channel rather than padding.
200    #[cfg(feature = "image-encoding")]
201    pub(crate) const fn has_alpha(self) -> bool {
202        self.has_alpha
203    }
204
205    /// Precision of one component, independent of packed pixel width.
206    #[cfg(feature = "image-encoding")]
207    pub(crate) const fn sample_width(self) -> PixelSampleWidth {
208        self.sample_width
209    }
210
211    #[cfg(feature = "image-encoding")]
212    const fn chroma_order(self) -> ChromaOrder {
213        self.chroma_order
214    }
215
216    pub(crate) const fn plane_count(self) -> usize {
217        match self.category {
218            FormatCategory::Packed => 1,
219            FormatCategory::PackedAlpha
220            | FormatCategory::SemiPlanar420
221            | FormatCategory::SemiPlanar422 => 2,
222            FormatCategory::Planar420
223            | FormatCategory::SemiPlanar422Alpha
224            | FormatCategory::Planar444 => 3,
225            FormatCategory::Planar444Alpha => 4,
226        }
227    }
228
229    /// Returns true if this is a planar 4:2:0 format (YV12, I420, or NV12).
230    #[must_use]
231    pub const fn is_planar_420(&self) -> bool {
232        matches!(
233            self.category,
234            FormatCategory::Planar420 | FormatCategory::SemiPlanar420
235        )
236    }
237}
238
239crate::media::decoded_variants!(PixelFormat:
240    Uyvy, Uyva, P216, Pa16, Yv12, I420, Nv12, Bgra, Bgrx, Rgba, Rgbx, Na48,
241    Nb48, Na4g, Nb4g,
242);
243
244impl PixelFormat {
245    /// Packed storage bytes per pixel across all planes, rounded up for 4:2:0.
246    const fn packed_bytes_per_pixel_ceil(self) -> usize {
247        let info = self.info();
248        let first_plane = info.bytes_per_pixel() as usize;
249        match info.category() {
250            FormatCategory::PackedAlpha
251            | FormatCategory::Planar420
252            | FormatCategory::SemiPlanar420 => first_plane + first_plane.div_ceil(2),
253            FormatCategory::Packed
254            | FormatCategory::SemiPlanar422
255            | FormatCategory::SemiPlanar422Alpha
256            | FormatCategory::Planar444
257            | FormatCategory::Planar444Alpha => first_plane * info.plane_count(),
258        }
259    }
260
261    /// The complete readable allocation size for sending this layout.
262    ///
263    /// `line_stride_bytes` is `None` for tightly packed rows; explicit values
264    /// follow the [video stride rules](Self::buffer_len). The returned size includes every plane and
265    /// the extra readable bytes required by the format and scan type. It is
266    /// suitable for allocating external buffers used with
267    /// [`BorrowedVideoFrameBuilder::allow_send_from_padding_and_tail`].
268    /// Padding and tail bytes must be initialized before direct sending;
269    /// the visible picture still occupies [`Self::buffer_len`] bytes for a
270    /// packed layout. Owned frames initialize their own tail as needed.
271    ///
272    /// # Errors
273    ///
274    /// Returns [`Error::InvalidFrame`] for invalid dimensions, stride,
275    /// or excessive layout size.
276    pub fn send_buffer_len(
277        self,
278        width: u32,
279        height: u32,
280        line_stride_bytes: Option<usize>,
281        scan_type: ScanType,
282    ) -> Result<usize> {
283        let layout =
284            ValidatedVideoLayout::new_uncompressed(self, width, height, line_stride_bytes)?;
285        // The validated data and the maximum send room fit usize on every
286        // supported target; the bound is asserted beside ValidatedVideoLayout.
287        Ok(layout.data_len_bytes() + crate::pixels::send_room(&layout, scan_type))
288    }
289
290    /// Get compile-time format properties.
291    ///
292    /// Returns first-plane bytes per pixel, plane category, alpha presence and
293    /// sample width. See [`Self::buffer_len`] for storage size and
294    /// [`Self::send_tail_room`] for the SDK's extra readable send bytes.
295    ///
296    /// # Examples
297    ///
298    /// ```
299    /// use grafton_ndi::{PixelFormat, FormatCategory};
300    ///
301    /// // Get properties for BGRA (32 bpp packed)
302    /// let info = PixelFormat::Bgra.info();
303    /// assert_eq!(info.bytes_per_pixel(), 4);
304    /// assert_eq!(info.category(), FormatCategory::Packed);
305    ///
306    /// // Get properties for YV12 (planar 4:2:0)
307    /// let info = PixelFormat::Yv12.info();
308    /// assert_eq!(info.bytes_per_pixel(), 1);
309    /// assert_eq!(info.category(), FormatCategory::Planar420);
310    /// ```
311    #[must_use]
312    pub const fn info(self) -> PixelFormatInfo {
313        match self {
314            Self::Bgra | Self::Rgba => PixelFormatInfo {
315                chroma_order: ChromaOrder::CbCr,
316                has_alpha: true,
317                sample_width: PixelSampleWidth::Eight,
318                bytes_per_pixel: 4,
319                category: FormatCategory::Packed,
320            },
321            Self::Bgrx | Self::Rgbx => PixelFormatInfo {
322                chroma_order: ChromaOrder::CbCr,
323                has_alpha: false,
324                sample_width: PixelSampleWidth::Eight,
325                bytes_per_pixel: 4,
326                category: FormatCategory::Packed,
327            },
328            Self::Uyvy => PixelFormatInfo {
329                chroma_order: ChromaOrder::CbCr,
330                has_alpha: false,
331                sample_width: PixelSampleWidth::Eight,
332                bytes_per_pixel: 2,
333                category: FormatCategory::Packed,
334            },
335            Self::Uyva => PixelFormatInfo {
336                chroma_order: ChromaOrder::CbCr,
337                has_alpha: true,
338                sample_width: PixelSampleWidth::Eight,
339                bytes_per_pixel: 2,
340                category: FormatCategory::PackedAlpha,
341            },
342            Self::P216 => PixelFormatInfo {
343                chroma_order: ChromaOrder::CbCr,
344                has_alpha: false,
345                sample_width: PixelSampleWidth::Sixteen,
346                bytes_per_pixel: 2,
347                category: FormatCategory::SemiPlanar422,
348            },
349            Self::Pa16 => PixelFormatInfo {
350                chroma_order: ChromaOrder::CbCr,
351                has_alpha: true,
352                sample_width: PixelSampleWidth::Sixteen,
353                bytes_per_pixel: 2,
354                category: FormatCategory::SemiPlanar422Alpha,
355            },
356            Self::Yv12 => PixelFormatInfo {
357                chroma_order: ChromaOrder::CrCb,
358                has_alpha: false,
359                sample_width: PixelSampleWidth::Eight,
360                bytes_per_pixel: 1,
361                category: FormatCategory::Planar420,
362            },
363            Self::I420 => PixelFormatInfo {
364                chroma_order: ChromaOrder::CbCr,
365                has_alpha: false,
366                sample_width: PixelSampleWidth::Eight,
367                bytes_per_pixel: 1,
368                category: FormatCategory::Planar420,
369            },
370            Self::Nv12 => PixelFormatInfo {
371                chroma_order: ChromaOrder::CbCr,
372                has_alpha: false,
373                sample_width: PixelSampleWidth::Eight,
374                bytes_per_pixel: 1,
375                category: FormatCategory::SemiPlanar420,
376            },
377            Self::Na48 => PixelFormatInfo {
378                chroma_order: ChromaOrder::CbCr,
379                has_alpha: false,
380                sample_width: PixelSampleWidth::Eight,
381                bytes_per_pixel: 1,
382                category: FormatCategory::Planar444,
383            },
384            Self::Nb48 => PixelFormatInfo {
385                chroma_order: ChromaOrder::CbCr,
386                has_alpha: true,
387                sample_width: PixelSampleWidth::Eight,
388                bytes_per_pixel: 1,
389                category: FormatCategory::Planar444Alpha,
390            },
391            Self::Na4g => PixelFormatInfo {
392                chroma_order: ChromaOrder::CbCr,
393                has_alpha: false,
394                sample_width: PixelSampleWidth::Sixteen,
395                bytes_per_pixel: 2,
396                category: FormatCategory::Planar444,
397            },
398            Self::Nb4g => PixelFormatInfo {
399                chroma_order: ChromaOrder::CbCr,
400                has_alpha: true,
401                sample_width: PixelSampleWidth::Sixteen,
402                bytes_per_pixel: 2,
403                category: FormatCategory::Planar444Alpha,
404            },
405        }
406    }
407
408    /// The number of readable bytes the NDI SDK needs after the last pixel
409    /// of a frame of this format that it sends: 64 for [`Self::Uyvy`] and
410    /// [`Self::Uyva`], and zero for every other format. On 64-bit ARM Linux
411    /// it is zero for every format.
412    ///
413    /// The x86 builds of the SDK read UYVY and UYVA frames a fixed number of
414    /// bytes at a time, and for many frames the last read ends after the
415    /// frame, by up to 28 bytes. Whether it does depends on the frame's
416    /// width, height and scan type and on where its buffer lies in memory: a
417    /// progressive 1920x1080 frame is read exactly, the same frame interlaced
418    /// is not, and neither is a 720x480 frame or any frame whose width is not
419    /// a multiple of 16. The SDK documents no such requirement, and it
420    /// compresses what it reads there into the picture's last blocks. The
421    /// 64-bit ARM Linux build reads every frame exactly. The figures are
422    /// measured with the Linux runtimes 6.1.1, 6.3.2 and 6.4.0.2.
423    /// `tests/send_tail_room_sdk.rs` checks these room figures against the
424    /// native SDK for its listed packed, padded and planar video layouts,
425    /// and the exact extents of its strided audio layouts. Every build
426    /// but the 64-bit ARM Linux one takes the
427    /// x86 figure, the 32-bit x86 Linux build included.
428    ///
429    /// The crate keeps this room for the SDK, and fills it with zeros, so a
430    /// program needs the number only to avoid a copy or a reallocation:
431    ///
432    /// - A [`VideoFrame`] has the complete room for its layout and scan
433    ///   type. Construction, copying, pixel replacement and scan-type
434    ///   changes grow its allocation when necessary, so sending it needs
435    ///   no wrapper pixel copy or reallocation.
436    /// - [`Sender::send_video`](crate::Sender::send_video) sends a
437    ///   [`BorrowedVideoFrame`] through a packed,
438    ///   zero-tailed copy by default when this room is nonzero. Direct sending
439    ///   requires both sufficient room and explicit opt-in through
440    ///   [`BorrowedVideoFrameBuilder::allow_send_from_padding_and_tail`].
441    ///   [`BorrowedVideoFrame::sends_in_place`]
442    ///   tells which.
443    /// - Include any initialized trailing room in the slice passed to
444    ///   [`BorrowedVideoFrame::builder`],
445    ///   so the frame borrows those bytes along with its pixels.
446    ///
447    /// One kind of frame needs two rows more, twice the line stride: an
448    /// interlaced or single-field UYVY or UYVA frame whose height is not a
449    /// multiple of four, which the SDK reads as far as the row after next.
450    /// Owned frames keep these extra rows too. A borrowed frame is sent
451    /// from a copy unless its buffer has that room and direct sending was
452    /// explicitly enabled.
453    ///
454    /// # Examples
455    ///
456    /// A buffer the sender does not copy:
457    ///
458    /// ```
459    /// use grafton_ndi::{BorrowedVideoFrame, PixelFormat};
460    ///
461    /// let format = PixelFormat::Uyvy;
462    /// let buffer = vec![0u8; 720 * 480 * 2 + format.send_tail_room()];
463    /// let frame = BorrowedVideoFrame::builder(&buffer, 720, 480, format)
464    ///     .allow_send_from_padding_and_tail(true)
465    ///     .build()?;
466    /// assert!(frame.sends_in_place());
467    ///
468    /// assert_eq!(PixelFormat::Bgra.send_tail_room(), 0);
469    /// # Ok::<(), grafton_ndi::Error>(())
470    /// ```
471    #[must_use]
472    pub const fn send_tail_room(self) -> usize {
473        // Measured exact: the SDK for 64-bit ARM Linux.
474        if cfg!(all(target_os = "linux", target_arch = "aarch64")) {
475            return 0;
476        }
477        match self {
478            Self::Uyvy | Self::Uyva => 64,
479            Self::P216
480            | Self::Pa16
481            | Self::Yv12
482            | Self::I420
483            | Self::Nv12
484            | Self::Bgra
485            | Self::Bgrx
486            | Self::Rgba
487            | Self::Rgbx
488            | Self::Na48
489            | Self::Nb48
490            | Self::Na4g
491            | Self::Nb4g => 0,
492        }
493    }
494
495    /// Calculate line stride in bytes for a given width using checked
496    /// arithmetic.
497    ///
498    /// For packed formats, this returns the total bytes per row.
499    /// For planar and semi-planar formats, this returns the first-plane
500    /// stride, which is what the SDK expects in `line_stride_in_bytes`.
501    ///
502    /// # Examples
503    ///
504    /// ```
505    /// use grafton_ndi::PixelFormat;
506    ///
507    /// // BGRA: 4 bytes per pixel
508    /// assert_eq!(PixelFormat::Bgra.line_stride_bytes(1920)?, 7680);
509    ///
510    /// // UYVY: 2 bytes per pixel
511    /// assert_eq!(PixelFormat::Uyvy.line_stride_bytes(1920)?, 3840);
512    ///
513    /// // NV12: Y-plane has 1 byte per pixel
514    /// assert_eq!(PixelFormat::Nv12.line_stride_bytes(1920)?, 1920);
515    ///
516    /// // P216: Y-plane has 16 bits per pixel
517    /// assert_eq!(PixelFormat::P216.line_stride_bytes(1920)?, 3840);
518    /// # Ok::<(), grafton_ndi::Error>(())
519    /// ```
520    ///
521    /// # Errors
522    ///
523    /// Returns [`Error::InvalidFrame`] if the width is zero or odd, or if the
524    /// stride exceeds the maximum video frame size.
525    pub fn line_stride_bytes(self, width: u32) -> Result<usize> {
526        validate_video_width(width.into())?;
527        let stride = min_video_line_stride(self, width);
528        validate_video_data_len(stride)?;
529        // The byte cap fits usize and the SDK's signed stride field.
530        Ok(stride as usize)
531    }
532
533    /// Calculate the total buffer size needed for a frame with given dimensions
534    /// using checked arithmetic.
535    ///
536    /// `line_stride_bytes` is `None` for tightly packed rows, or the byte
537    /// distance between first-plane row starts. An explicit stride must be
538    /// positive, hold at least the active row (`width × bytes per pixel`),
539    /// and be even for YV12, I420 and UYVA. The complete layout must fit the
540    /// crate's maximum video frame size. The result includes all planes,
541    /// without SDK send tail room.
542    ///
543    /// # Examples
544    ///
545    /// ```
546    /// use grafton_ndi::PixelFormat;
547    ///
548    /// // BGRA 1920x1080: 1920 * 4 * 1080 = 8,294,400 bytes
549    /// assert_eq!(PixelFormat::Bgra.buffer_len(1920, 1080, None)?, 8_294_400);
550    ///
551    /// // NV12 1920x1080: Y (1920*1080) + UV (1920*540) = 3,110,400 bytes
552    /// assert_eq!(PixelFormat::Nv12.buffer_len(1920, 1080, None)?, 3_110_400);
553    ///
554    /// // Planar 4:2:0 needs an even stride; semi-planar NV12 permits an odd one.
555    /// assert!(PixelFormat::I420.buffer_len(1920, 1080, Some(1921)).is_err());
556    /// assert!(PixelFormat::Nv12.buffer_len(1920, 1080, Some(1921)).is_ok());
557    /// # Ok::<(), grafton_ndi::Error>(())
558    /// ```
559    ///
560    /// # Errors
561    ///
562    /// Returns [`Error::InvalidFrame`] for invalid dimensions, a stride that
563    /// is zero or shorter than the active row, an odd YV12/I420 or UYVA stride,
564    /// or a layout above the video byte cap. The
565    /// [`FrameDefect::Layout`](crate::FrameDefect::Layout) carries the cause:
566    /// [`VideoZeroStride`](crate::LayoutDefect::VideoZeroStride),
567    /// [`VideoShortStride`](crate::LayoutDefect::VideoShortStride),
568    /// [`VideoPlanar420`](crate::LayoutDefect::VideoPlanar420),
569    /// [`VideoUyvaStride`](crate::LayoutDefect::VideoUyvaStride), or the
570    /// corresponding dimension or byte-cap defect.
571    pub fn buffer_len(
572        self,
573        width: u32,
574        height: u32,
575        line_stride_bytes: Option<usize>,
576    ) -> Result<usize> {
577        let layout =
578            ValidatedVideoLayout::new_uncompressed(self, width, height, line_stride_bytes)?;
579        Ok(layout.data_len_bytes())
580    }
581
582    /// Whether sending this format needs the runtime to support it: the
583    /// planar 4:4:4 formats need [`RuntimeFeature::Planar444Video`].
584    ///
585    /// [`RuntimeFeature::Planar444Video`]: crate::RuntimeFeature::Planar444Video
586    pub(crate) fn require_sendable<T>(
587        self,
588        planar444: impl FnOnce() -> Result<T>,
589    ) -> Result<Option<T>> {
590        if matches!(
591            self.info().category(),
592            FormatCategory::Planar444 | FormatCategory::Planar444Alpha
593        ) {
594            return planar444().map(Some);
595        }
596        Ok(None)
597    }
598}
599
600/// Video scan type (progressive, interlaced, or field-based).
601///
602/// This enum describes how video frames are scanned/displayed.
603/// Most modern content uses Progressive, while legacy broadcast may use Interlaced or field-based formats.
604///
605/// This enum is marked `#[non_exhaustive]` to allow future NDI SDK versions to add new scan types
606/// without breaking existing code. Always use a wildcard pattern when matching.
607///
608/// # Examples
609///
610/// ```
611/// use grafton_ndi::ScanType;
612///
613/// let scan = ScanType::Progressive;
614///
615/// // When matching, always include a wildcard for forward compatibility
616/// match scan {
617///     ScanType::Progressive => println!("Progressive scan"),
618///     ScanType::Interlaced => println!("Interlaced"),
619///     _ => println!("Field-based or other"),
620/// }
621/// ```
622#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
623#[non_exhaustive]
624pub enum ScanType {
625    /// Progressive scan - full frames rendered sequentially.
626    Progressive,
627    /// Interlaced scan - alternating even/odd lines.
628    Interlaced,
629    /// Field 0 only (first field of interlaced content).
630    Field0,
631    /// Field 1 only (second field of interlaced content).
632    Field1,
633}
634
635crate::media::decoded_variants!(ScanType: Progressive, Interlaced, Field0, Field1);
636
637impl ScanType {
638    /// The SDK's frame format type for this scan type.
639    pub(crate) const fn to_sdk(self) -> NDIlib_frame_format_type_e {
640        match self {
641            Self::Progressive => NDIlib_frame_format_type_e_NDIlib_frame_format_type_progressive,
642            Self::Interlaced => NDIlib_frame_format_type_e_NDIlib_frame_format_type_interleaved,
643            Self::Field0 => NDIlib_frame_format_type_e_NDIlib_frame_format_type_field_0,
644            Self::Field1 => NDIlib_frame_format_type_e_NDIlib_frame_format_type_field_1,
645        }
646    }
647
648    /// The scan type an SDK frame format type names, if it names one.
649    pub(crate) fn from_sdk(value: NDIlib_frame_format_type_e) -> Option<Self> {
650        Self::ALL.into_iter().find(|scan| scan.to_sdk() == value)
651    }
652}
653
654/// Video header values independent of the storage's scan-dependent send room.
655#[derive(Debug, Clone, Copy)]
656pub(crate) struct VideoTiming {
657    frame_rate: FrameRate,
658    picture_aspect_ratio: PictureAspectRatio,
659    timecode: Timecode,
660}
661
662impl VideoTiming {
663    pub(crate) const fn with_scan_type(self, scan_type: ScanType) -> VideoHeader {
664        VideoHeader {
665            timing: self,
666            scan_type,
667        }
668    }
669}
670
671/// The complete header of a validated video frame besides its layout.
672#[derive(Debug, Clone, Copy)]
673pub(crate) struct VideoHeader {
674    pub(crate) timing: VideoTiming,
675    scan_type: ScanType,
676}
677
678impl VideoHeader {
679    pub(crate) const fn new(
680        frame_rate: FrameRate,
681        picture_aspect_ratio: PictureAspectRatio,
682        scan_type: ScanType,
683        timecode: Timecode,
684    ) -> Self {
685        VideoTiming {
686            frame_rate,
687            picture_aspect_ratio,
688            timecode,
689        }
690        .with_scan_type(scan_type)
691    }
692
693    pub(crate) const fn frame_rate(self) -> FrameRate {
694        self.timing.frame_rate
695    }
696    pub(crate) const fn picture_aspect_ratio(self) -> PictureAspectRatio {
697        self.timing.picture_aspect_ratio
698    }
699    pub(crate) const fn scan_type(self) -> ScanType {
700        self.scan_type
701    }
702    pub(crate) const fn timecode(self) -> Timecode {
703        self.timing.timecode
704    }
705    pub(crate) fn with_timecode(mut self, timecode: Timecode) -> Self {
706        self.timing.timecode = timecode;
707        self
708    }
709
710    /// Validate the header of a frame the SDK delivered.
711    pub(crate) fn from_sdk(raw: &NDIlib_video_frame_v2_t) -> Result<Self> {
712        let frame_rate = FrameRate::from_sdk(raw.frame_rate_N, raw.frame_rate_D)?;
713        let picture_aspect_ratio = PictureAspectRatio::from_sdk(raw.picture_aspect_ratio)?;
714        let scan_type = ScanType::from_sdk(raw.frame_format_type).ok_or({
715            Error::InvalidFrame(crate::FrameDefect::UnknownScanType {
716                code: raw.frame_format_type,
717            })
718        })?;
719        Ok(Self::new(
720            frame_rate,
721            picture_aspect_ratio,
722            scan_type,
723            Timecode::from_ticks(raw.timecode),
724        ))
725    }
726}
727
728/// The parts of a video frame that its shared accessors and owned copies
729/// read.
730///
731/// [`VideoFrame`], [`BorrowedVideoFrame`], internal
732/// validated video, and the borrowed [`VideoFrameRef`] and
733/// [`FrameSyncVideoRef`](crate::FrameSyncVideoRef) views lend their validated
734/// layout, header, pixels and metadata through it. [`video_accessors!`]
735/// generates their public accessors and `Debug`, so each is written and
736/// documented once. Each implementation takes every part from one value that
737/// was validated as a whole; the validated video implementation covers both
738/// receiver and FrameSync guards.
739///
740/// # Safety
741///
742/// The plane views read through [`pixels`](Self::pixels): it must point to
743/// storage that [`layout`](Self::layout) describes, with every active row
744/// initialized and unchanged while `self` is borrowed. Row padding need not
745/// be initialized. Metadata text must remain a bounded NUL-terminated UTF-8
746/// string for the borrow. [`Initialized::Storage`] and
747/// [`Initialized::PackedSendReady`] each guarantee full initialization.
748/// For `Storage`, the reported room after the last active pixel is also
749/// initialized and readable, including final-row padding. For `PackedSendReady`,
750/// the packed allocation includes the zeroed SDK send tail for the layout and
751/// scan type. In each case the pointer returned by `pixels()` must derive from a
752/// reference or allocation covering both the storage and that trailing room.
753/// Copying, views and descriptors are non-overridable helpers.
754pub(crate) unsafe trait VideoParts {
755    /// The validated layout of the frame's pixels; stable for the borrow.
756    fn layout(&self) -> &ValidatedVideoLayout;
757
758    /// The validated header.
759    fn header(&self) -> VideoHeader;
760
761    /// The start of the frame's pixel storage.
762    fn pixels(&self) -> *const u8;
763
764    /// The frame's one validated metadata observation.
765    fn frame_metadata(&self) -> FrameMetadataRef<'_>;
766
767    /// The timestamp carried by the received frame, when present.
768    fn sdk_timestamp(&self) -> Option<ReceivedTimestamp>;
769
770    /// Which bytes the storage's owner guarantees are initialized.
771    /// Capture guarantees only active pixels, never padding or trailing room.
772    fn initialized(&self) -> Initialized {
773        Initialized::ActiveRows
774    }
775}
776
777/// The initialized extent reported by a validated video storage owner.
778#[derive(Clone, Copy, Debug, PartialEq, Eq)]
779pub(crate) enum Initialized {
780    /// Only the active rows are known initialized.
781    ActiveRows,
782    /// All layout storage is initialized, including padding, and `room_after`
783    /// initialized bytes follow the last active pixel and are readable through
784    /// `VideoParts::pixels()`, whose provenance covers the storage and room.
785    /// The final row's padding is part of that room.
786    Storage { room_after: usize },
787    /// Tightly packed storage with the initialized SDK tail for its scan type.
788    PackedSendReady,
789}
790
791// SAFETY: a reference forwards every accessor and keeps its original owner
792// borrowed; it neither changes storage nor adds a new lifetime claim.
793unsafe impl<T: VideoParts + ?Sized> VideoParts for &T {
794    fn layout(&self) -> &ValidatedVideoLayout {
795        (**self).layout()
796    }
797    fn header(&self) -> VideoHeader {
798        (**self).header()
799    }
800    fn pixels(&self) -> *const u8 {
801        (**self).pixels()
802    }
803    fn frame_metadata(&self) -> FrameMetadataRef<'_> {
804        (**self).frame_metadata()
805    }
806    fn sdk_timestamp(&self) -> Option<ReceivedTimestamp> {
807        (**self).sdk_timestamp()
808    }
809    fn initialized(&self) -> Initialized {
810        (**self).initialized()
811    }
812}
813
814/// Shared operations whose blanket implementation prevents per-frame overrides.
815pub(crate) trait VideoPartsExt: VideoParts {
816    /// Describe this validated frame without imposing a send capability.
817    /// The pointer fields borrow the same storage as the frame's accessors.
818    fn video_descriptor(&self) -> NDIlib_video_frame_v2_t {
819        let frame = self;
820        let layout = frame.layout();
821        let header = frame.header();
822        let (frame_rate_n, frame_rate_d) = header.frame_rate().to_sdk();
823        NDIlib_video_frame_v2_t {
824            xres: layout.sdk_width(),
825            yres: layout.sdk_height(),
826            FourCC: FourCc::from(layout.pixel_format()).raw(),
827            frame_rate_N: frame_rate_n,
828            frame_rate_D: frame_rate_d,
829            picture_aspect_ratio: header.picture_aspect_ratio().to_sdk(),
830            frame_format_type: header.scan_type.to_sdk(),
831            timecode: header.timecode().ticks(),
832            p_data: frame.pixels().cast_mut(),
833            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
834                line_stride_in_bytes: layout.sdk_line_stride(),
835            },
836            p_metadata: frame.frame_metadata().as_ptr(),
837            timestamp: ReceivedTimestamp::to_sdk(frame.sdk_timestamp()),
838        }
839    }
840
841    /// Whether one complete SDK read fits the owner's initialized extent.
842    fn can_send_direct(&self) -> bool {
843        let send_room = |layout| crate::pixels::send_room(layout, self.header().scan_type());
844        match self.initialized() {
845            Initialized::PackedSendReady => true,
846            Initialized::Storage { room_after } => room_after >= send_room(self.layout()),
847            Initialized::ActiveRows => {
848                let layout = self.layout();
849                layout.payload_len_bytes() == layout.data_len_bytes() && send_room(layout) == 0
850            }
851        }
852    }
853
854    /// Keep the metadata's status beside its text for a lazy color read.
855    fn color_metadata(&self) -> crate::color_info::Metadata<'_> {
856        crate::color_info::Metadata::new(self.frame_metadata())
857    }
858
859    /// One plane, or `None` for an invalid index: the view behind every
860    /// generated `plane`.
861    #[inline]
862    fn plane_view(&self, index: usize) -> Option<VideoPlane<'_>> {
863        // SAFETY: the trait's contract: `pixels` points to storage `layout`
864        // describes, with every active row initialized and unchanged while
865        // `self`, which the view borrows, is borrowed.
866        unsafe { self.layout().view_plane(self.pixels(), index) }
867    }
868
869    /// Every plane in SDK memory order: the view behind every generated
870    /// `planes`.
871    #[inline]
872    fn plane_views(&self) -> VideoPlanes<'_> {
873        // SAFETY: as for `plane_view`.
874        unsafe { self.layout().view_planes(self.pixels()) }
875    }
876
877    /// The frame's planes identified by their component roles.
878    #[cfg(feature = "image-encoding")]
879    fn plane_roles(&self) -> PlaneRoles<'_> {
880        // SAFETY: as for `plane_view`.
881        unsafe { self.layout().plane_roles(self.pixels()) }
882    }
883
884    /// Every active byte in SDK plane order, or `None` when padding
885    /// separates rows or planes: the view behind a received frame's `data`.
886    #[inline]
887    fn active_data(&self) -> Option<&[u8]> {
888        // SAFETY: as for `plane_view`.
889        unsafe { self.layout().view_data(self.pixels()) }
890    }
891
892    /// Copy active pixels using a single snapshot of the source layout.
893    fn owned_copy(&self) -> VideoFrame {
894        let header = self.header();
895        let metadata = OwnedFrameMetadata::copied(self.frame_metadata());
896        let timestamp = self.sdk_timestamp();
897        let data = VideoStorage::copied(VideoCopy::new(self), header.scan_type());
898        VideoFrame {
899            data,
900            timing: header.timing,
901            metadata,
902            timestamp,
903        }
904    }
905
906    /// Copy pixels and metadata, reusing their allocations when sufficient.
907    /// The storage kernel preserves the previous layout/storage pairing on unwind.
908    fn copy_into_owned(&self, destination: &mut VideoFrame) {
909        let header = self.header();
910        let timestamp = self.sdk_timestamp();
911        destination.metadata.copy_from(self.frame_metadata());
912        destination
913            .data
914            .refill_from(VideoCopy::new(self), header.scan_type());
915        destination.timing = header.timing;
916        destination.timestamp = timestamp;
917    }
918}
919
920impl<T: VideoParts + ?Sized> VideoPartsExt for T {}
921
922/// A validated uncompressed video input for synchronous sending and owned copies.
923///
924/// Implemented by [`VideoFrame`], [`crate::BorrowedVideoFrame`],
925/// [`VideoFrameRef`] and [`FrameSyncVideoRef`]. This trait is sealed: applications
926/// cannot claim that unchecked storage is a valid frame. It exposes no SDK
927/// pointers or allocation ownership. Operations borrow their input and preserve
928/// its lifetime and thread restrictions; converting a captured frame is unnecessary.
929#[allow(private_bounds)]
930pub trait VideoSource: VideoParts {
931    /// Frame width in pixels.
932    fn width(&self) -> u32;
933
934    /// Frame height in pixels.
935    fn height(&self) -> u32;
936
937    /// Validated uncompressed pixel format.
938    fn pixel_format(&self) -> PixelFormat;
939
940    /// Frame rate, including its rational representation.
941    fn frame_rate(&self) -> FrameRate;
942
943    /// Display width divided by height; zero means square pixels.
944    fn picture_aspect_ratio(&self) -> PictureAspectRatio;
945
946    /// Progressive, interlaced, or field scanning.
947    fn scan_type(&self) -> ScanType;
948
949    /// Frame timecode, or the sender's synthesis sentinel.
950    fn timecode(&self) -> Timecode;
951
952    /// Source-dependent timestamp supplied by the SDK for a captured frame.
953    fn timestamp(&self) -> Option<ReceivedTimestamp>;
954
955    /// Distance in bytes between first-plane row starts.
956    fn line_stride_bytes(&self) -> usize;
957
958    /// UTF-8 frame metadata; an explicit empty string differs from no metadata.
959    /// Unreadable received text is withheld; inspect [`Self::metadata_status`].
960    fn metadata(&self) -> Option<&str>;
961
962    /// Whether per-frame metadata is absent, readable, or withheld as unreadable.
963    fn metadata_status(&self) -> FrameMetadataStatus;
964
965    /// Read the frame's `ndi_color_info` description without copying metadata.
966    ///
967    /// # Errors
968    ///
969    /// [`Error::InvalidFrame`] for malformed, truncated or conflicting color
970    /// metadata or withheld received text, with the same semantics as
971    /// [`VideoFrame::color_info`].
972    fn color_info(&self) -> Result<Option<crate::ColorInfo>>;
973
974    /// One plane's initialized active rows, excluding row padding.
975    fn plane(&self, index: usize) -> Option<VideoPlane<'_>>;
976
977    /// All initialized active planes in SDK order, without allocating.
978    fn planes(&self) -> VideoPlanes<'_>;
979
980    /// Contiguous active pixels, or `None` when row/plane padding separates them.
981    /// Padding and SDK trailing read room are never exposed through this slice.
982    fn data(&self) -> Option<&[u8]>;
983
984    /// Copy active pixels and readable metadata into a new, tightly packed
985    /// owned frame. Withheld metadata keeps its status without its text.
986    /// Allocates pixel storage and, when present, readable metadata storage.
987    fn to_owned(&self) -> VideoFrame;
988
989    /// Copy active pixels and metadata into an owned destination, preserving
990    /// the header and timestamp. Row padding is omitted. Pixel and metadata
991    /// allocations are reused when their capacities/layouts permit; this has
992    /// the same allocation behavior as a captured frame's `copy_into`. A copy
993    /// without metadata retains the destination's text allocation.
994    fn copy_into(&self, destination: &mut VideoFrame);
995
996    /// Whether synchronous sending can read this frame directly, without a
997    /// wrapper pixel copy. The query allocates nothing and makes no SDK call.
998    ///
999    /// Captured padding is never assumed initialized. Padded captures and
1000    /// formats requiring trailing SDK room therefore use reusable staging;
1001    /// owned frames and eligible packed captures send directly. An external
1002    /// [`crate::BorrowedVideoFrame`] retains its explicit padding/tail policy.
1003    fn sends_in_place(&self) -> bool;
1004
1005    /// Encode this frame using the image format and conversion options.
1006    #[cfg(feature = "image-encoding")]
1007    fn encode_image(&self, options: &crate::image_encoding::ImageOptions) -> Result<Vec<u8>>;
1008
1009    /// Encode into a writer, flushing it when encoding succeeds.
1010    #[cfg(feature = "image-encoding")]
1011    fn encode_image_to<W: std::io::Write>(
1012        &self,
1013        options: &crate::image_encoding::ImageOptions,
1014        out: W,
1015    ) -> Result<()>
1016    where
1017        Self: Sized;
1018
1019    /// Encode this frame as a base64 data URL.
1020    #[cfg(feature = "image-encoding")]
1021    fn encode_image_data_url(
1022        &self,
1023        options: &crate::image_encoding::ImageOptions,
1024    ) -> Result<String>;
1025}
1026
1027// One accessor list defines the inherent surface and the sealed trait impl.
1028// Only owned data needs an adapter: its infallible slice becomes Some(slice).
1029macro_rules! source_accessor_forward {
1030    (#[cfg($cfg:meta)] $($rest:tt)*) => {
1031        #[cfg($cfg)]
1032        $crate::frames::source_accessor_forward! { $($rest)* }
1033    };
1034    (#[$attr:meta] $($rest:tt)*) => {
1035        $crate::frames::source_accessor_forward! { $($rest)* }
1036    };
1037    ($frame:ty; $name:ident<$generic:ident: $bound:path>(&$this:ident $(, $arg:ident: $arg_ty:ty)*) $(-> $ret:ty)? where Self: $sized:path;) => {
1038        #[inline]
1039        fn $name<$generic: $bound>(&$this $(, $arg: $arg_ty)*) $(-> $ret)? where Self: $sized {
1040            <$frame>::$name($this $(, $arg)*)
1041        }
1042    };
1043    ($frame:ty; $name:ident(&$this:ident $(, $arg:ident: $arg_ty:ty)*) $(-> $ret:ty)?;) => {
1044        #[inline]
1045        fn $name(&$this $(, $arg: $arg_ty)*) $(-> $ret)? {
1046            <$frame>::$name($this $(, $arg)*)
1047        }
1048    };
1049    ($frame:ty; $name:ident(&$this:ident $(, $arg:ident: $arg_ty:ty)*) -> $ret:ty => ($map:ident, $trait_ret:ty);) => {
1050        #[inline]
1051        fn $name(&$this $(, $arg: $arg_ty)*) -> $trait_ret {
1052            $map(<$frame>::$name($this $(, $arg)*))
1053        }
1054    };
1055}
1056pub(crate) use source_accessor_forward;
1057
1058macro_rules! source_accessors {
1059    (
1060        $(#[$attr:meta])*
1061        impl[$($generics:tt)*] $frame:ty;
1062        source($source:path);
1063        methods {
1064            $(
1065                $(#[$($doc:tt)*])*
1066                fn $method:ident $(<$generic:ident: $bound:path>)? (&$this:ident $(, $arg:ident: $arg_ty:ty)* $(,)?) $(-> $ret:ty)? $(where Self: $sized:path)?
1067                $body:block $(=> ($map:ident, $trait_ret:ty))?
1068            )*
1069        }
1070        extra { $($extra:tt)* }
1071    ) => {
1072        $(#[$attr])*
1073        impl<$($generics)*> $frame {
1074            $(
1075                $(#[$($doc)*])*
1076                pub fn $method $(<$generic: $bound>)? (&$this $(, $arg: $arg_ty)*) $(-> $ret)? $(where Self: $sized)? $body
1077            )*
1078            $($extra)*
1079        }
1080        $(#[$attr])*
1081        impl<$($generics)*> $source for $frame {
1082            $(
1083                $crate::frames::source_accessor_forward! {
1084                    $(#[$($doc)*])*
1085                    $frame; $method $(<$generic: $bound>)? (&$this $(, $arg: $arg_ty)*) $(-> $ret)? $(where Self: $sized)? $(=> ($map, $trait_ret))?;
1086                }
1087            )*
1088        }
1089    };
1090}
1091pub(crate) use source_accessors;
1092
1093/// Generate a video frame type's shared public accessors and its `Debug`
1094/// from its [`VideoParts`], so that each accessor is written, and
1095/// documented, once. Every generated method delegates to the frame's
1096/// validated parts.
1097///
1098/// A frame type passes its `impl` header; its `Debug` name and the layout
1099/// field that sizes its pixel data; for the accessors whose meaning differs
1100/// between types, the type-specific paragraph of their docs; and in `images`
1101/// the code-block options and hidden lines that make a `frame` of its type
1102/// for the examples of `color_info` and the image encoders, with the
1103/// type-specific paragraph of the encoders' docs. Every frame has a timestamp
1104/// accessor; application-built frames return `None`. The data and owned-copy
1105/// bodies select packed storage versus a borrowed view without a second trait body.
1106macro_rules! video_accessors {
1107    (
1108        $(#[$attr:meta])*
1109        impl[$($generics:tt)*] $frame:ty;
1110        debug($name:expr, $data:literal = $data_len:ident);
1111        timecode { $(#[$timecode:meta])* }
1112        line_stride_bytes { $(#[$line_stride:meta])* }
1113        plane { $(#[$plane:meta])* }
1114        timestamp { $(#[$timestamp:meta])* }
1115        data($data_self:ident -> $data_ty:ty $(=> $data_map:ident)?) { $(#[$data_doc:meta])* } $data_body:block
1116        to_owned($owned_self:ident) { $(#[$owned_doc:meta])* } $owned_body:block
1117        copy_into { $(#[$copy_doc:meta])* }
1118        sends_in_place { $(#[$send_doc:meta])* }
1119        images($fence:literal, $example:literal) { $(#[$images:meta])* }
1120    ) => {
1121        $crate::frames::source_accessors! {
1122            $(#[$attr])*
1123            impl[$($generics)*] $frame;
1124            source($crate::frames::VideoSource);
1125            methods {
1126                /// Get the frame width in pixels.
1127                #[inline]
1128                fn width(&self) -> u32 {
1129                    $crate::frames::VideoParts::layout(self).width()
1130                }
1131
1132                /// Get the frame height in pixels.
1133                #[inline]
1134                fn height(&self) -> u32 {
1135                    $crate::frames::VideoParts::layout(self).height()
1136                }
1137
1138                /// Get the pixel format.
1139                ///
1140                /// It is a supported uncompressed format, validated when the
1141                /// frame was constructed.
1142                #[inline]
1143                fn pixel_format(&self) -> $crate::PixelFormat {
1144                    $crate::frames::VideoParts::layout(self).pixel_format()
1145                }
1146
1147                /// Get the frame rate.
1148                #[inline]
1149                fn frame_rate(&self) -> $crate::FrameRate {
1150                    $crate::frames::VideoParts::header(self).frame_rate()
1151                }
1152
1153                /// Get the picture aspect ratio, width over height as displayed; `0.0`
1154                /// means square pixels.
1155                #[inline]
1156                fn picture_aspect_ratio(&self) -> $crate::PictureAspectRatio {
1157                    $crate::frames::VideoParts::header(self).picture_aspect_ratio()
1158                }
1159
1160                /// Get the scan type: progressive, interlaced, or a single field.
1161                #[inline]
1162                fn scan_type(&self) -> $crate::ScanType {
1163                    $crate::frames::VideoParts::header(self).scan_type()
1164                }
1165
1166                /// Get the timecode.
1167                ///
1168                $(#[$timecode])*
1169                #[inline]
1170                fn timecode(&self) -> $crate::Timecode {
1171                    $crate::frames::VideoParts::header(self).timecode()
1172                }
1173
1174                /// Get the validated first-plane line stride in bytes: the
1175                /// distance between the starts of consecutive rows of the first
1176                /// plane.
1177                ///
1178                $(#[$line_stride])*
1179                #[inline]
1180                fn line_stride_bytes(&self) -> usize {
1181                    $crate::frames::VideoParts::layout(self).line_stride_bytes()
1182                }
1183
1184                /// Get frame metadata as UTF-8 text, if present.
1185                ///
1186                /// Empty metadata, `Some("")`, is distinct from none, `None`.
1187                /// Unreadable received text returns `None`; use
1188                /// [`Self::metadata_status`] to distinguish it from absent text.
1189                #[inline]
1190                fn metadata(&self) -> Option<&str> {
1191                    $crate::frames::VideoParts::frame_metadata(self).text()
1192                        .map($crate::frames::MetadataText::as_str)
1193                }
1194
1195                /// The metadata's presence or the reason unreadable received text
1196                /// was withheld. Querying the cached status allocates nothing.
1197                #[inline]
1198                fn metadata_status(&self) -> $crate::FrameMetadataStatus {
1199                    $crate::frames::VideoParts::frame_metadata(self).status()
1200                }
1201
1202                /// Read the color description in the frame's `ndi_color_info`
1203                /// metadata.
1204                ///
1205                /// Returns `Ok(None)` when the frame has no metadata or no such
1206                /// element, which means BT.709 SDR with unknown primaries. See
1207                /// [`ColorInfo`](crate::ColorInfo) for what the element holds and
1208                /// how the SDK treats it. Image encoding reads the same
1209                /// description, so a program can check a frame, for an HDR
1210                /// transfer for example, before it encodes it.
1211                ///
1212                /// # Errors
1213                ///
1214                /// [`Error::InvalidFrame`](crate::Error::InvalidFrame), naming the
1215                /// attribute and its value, when the element is malformed or
1216                /// truncated, gives a value outside the SDK's list, or appears more
1217                /// than once with different values. Also returned when received
1218                /// metadata was withheld as [`FrameMetadataStatus::NotUtf8`](crate::FrameMetadataStatus::NotUtf8)
1219                /// or [`FrameMetadataStatus::Unterminated`](crate::FrameMetadataStatus::Unterminated),
1220                /// including on an owned copy of that frame.
1221                ///
1222                /// # Example
1223                ///
1224                #[doc = concat!("```", $fence)]
1225                #[doc = $example]
1226                /// match frame.color_info()? {
1227                ///     Some(color) if color.is_hdr() => println!("HDR: {:?}", color.transfer()),
1228                ///     Some(color) => println!("SDR, matrix {:?}", color.matrix()),
1229                ///     None => println!("BT.709 SDR"),
1230                /// }
1231                /// # Ok::<(), Box<dyn std::error::Error>>(())
1232                /// ```
1233                fn color_info(&self) -> $crate::Result<Option<$crate::ColorInfo>> {
1234                    $crate::frames::VideoPartsExt::color_metadata(self).read()
1235                }
1236
1237                /// Get one plane in SDK memory order, or `None` for an invalid index.
1238                ///
1239                /// Plane order follows the pixel format, as for
1240                /// [`VideoPlane`](crate::VideoPlane), whose rows exclude any row
1241                /// padding.
1242                ///
1243                $(#[$plane])*
1244                #[inline]
1245                fn plane(&self, index: usize) -> Option<$crate::VideoPlane<'_>> {
1246                    $crate::frames::VideoPartsExt::plane_view(self, index)
1247                }
1248
1249                /// Iterate planes in SDK memory order without allocating or copying.
1250                #[inline]
1251                fn planes(&self) -> $crate::VideoPlanes<'_> {
1252                    $crate::frames::VideoPartsExt::plane_views(self)
1253                }
1254
1255                /// The source-dependent timestamp of the received frame.
1256                ///
1257                $(#[$timestamp])*
1258                #[inline]
1259                fn timestamp(&self) -> Option<$crate::ReceivedTimestamp> {
1260                    $crate::frames::VideoParts::sdk_timestamp(self)
1261                }
1262
1263                $(#[$data_doc])*
1264                fn data(&$data_self) -> $data_ty $data_body $(=> ($data_map, Option<&[u8]>))?
1265
1266                $(#[$owned_doc])*
1267                fn to_owned(&$owned_self) -> $crate::VideoFrame $owned_body
1268
1269                $(#[$copy_doc])*
1270                fn copy_into(&self, destination: &mut $crate::VideoFrame) {
1271                    $crate::frames::VideoPartsExt::copy_into_owned(self, destination);
1272                }
1273
1274                $(#[$send_doc])*
1275                #[must_use]
1276                fn sends_in_place(&self) -> bool {
1277                    $crate::frames::VideoPartsExt::can_send_direct(self)
1278                }
1279
1280                /// Encode the frame as an image, as `options` describe.
1281                ///
1282                /// Every uncompressed pixel format encodes, as PNG, JPEG or
1283                /// lossless or lossy WebP. By default, YUV uses limited range,
1284                /// repeated chroma and the matrix in readable `ndi_color_info`,
1285                /// or BT.709 when untagged. RGB-received frames already hold the
1286                /// SDK's BT.709 limited-range conversion, which ignores the tag;
1287                /// encoding cannot apply its matrix afterward. Tags still decide
1288                /// HDR refusal and the PNG `cICP` chunk. Receive YUV when the
1289                /// tagged matrix or original HDR code values matter. See
1290                /// [`ImageOptions`](crate::image_encoding::ImageOptions) for formats, color, HDR,
1291                /// bit depth, alpha, reduction, cost and memory.
1292                ///
1293                $(#[$images])*
1294                ///
1295                /// Encoding is CPU work, tens to hundreds of milliseconds for a
1296                /// 1080p frame: async code runs it on a blocking thread with an
1297                /// owned frame.
1298                ///
1299                /// # Errors
1300                ///
1301                /// Returns [`Error::InvalidInput`](crate::Error::InvalidInput)
1302                /// for unsuitable options, [`Error::InvalidFrame`](crate::Error::InvalidFrame)
1303                /// for frame or codec refusals, or [`Error::AllocationFailed`](crate::Error::AllocationFailed) for
1304                /// conversion scratch storage. The complete conditions are in the
1305                /// [ImageOptions error table](crate::image_encoding::ImageOptions#errors).
1306                ///
1307                /// # Example
1308                ///
1309                #[doc = concat!("```", $fence)]
1310                #[doc = $example]
1311                /// use grafton_ndi::{image_encoding::{Downscale, ImageFormat, ImageOptions, PngCompression}};
1312                ///
1313                /// let options = ImageOptions::new(ImageFormat::Png)
1314                ///     .png_compression(PngCompression::Fast)
1315                ///     .downscale(Downscale::Half);
1316                /// let png = frame.encode_image(&options)?;
1317                /// # Ok::<(), Box<dyn std::error::Error>>(())
1318                /// ```
1319                #[cfg(feature = "image-encoding")]
1320                fn encode_image(&self, options: &$crate::image_encoding::ImageOptions) -> $crate::Result<Vec<u8>> {
1321                    $crate::image_encoding::encode($crate::image_encoding::Source::new(self), options)
1322                }
1323
1324                /// Encode the frame as an image, as `options` describe, writing it
1325                /// into `out`.
1326                ///
1327                /// It encodes as [`encode_image`](Self::encode_image) does, into
1328                /// any writer, so a program that takes snapshots on a timer can
1329                /// reuse one output buffer. A file or socket should be wrapped in
1330                /// a [`BufWriter`](std::io::BufWriter): the codecs write in small
1331                /// pieces. Both WebP formats buffer their complete encoded image
1332                /// before writing it; PNG and JPEG write as they encode. Success
1333                /// means every byte was written and `out` was flushed.
1334                ///
1335                /// # Errors
1336                ///
1337                /// As for [`encode_image`](Self::encode_image), and
1338                /// [`Error::Io`](crate::Error::Io) when `out` fails. Every check
1339                /// of the options and the frame happens before anything is
1340                /// written; after a later error, `out` may hold part of an image,
1341                /// which the caller discards.
1342                ///
1343                /// # Example
1344                ///
1345                #[doc = concat!("```", $fence)]
1346                #[doc = $example]
1347                /// use grafton_ndi::{image_encoding::{ImageFormat, ImageOptions}};
1348                ///
1349                /// let options = ImageOptions::new(ImageFormat::Jpeg(85));
1350                /// let mut jpeg = Vec::new();
1351                /// for _ in 0..3 {
1352                ///     jpeg.clear();
1353                ///     frame.encode_image_to(&options, &mut jpeg)?;
1354                ///     // Publish `jpeg`.
1355                /// }
1356                /// # Ok::<(), Box<dyn std::error::Error>>(())
1357                /// ```
1358                #[cfg(feature = "image-encoding")]
1359                fn encode_image_to<W: ::std::io::Write>(
1360                    &self,
1361                    options: &$crate::image_encoding::ImageOptions,
1362                    out: W,
1363                ) -> $crate::Result<()> where Self: Sized {
1364                    let mut out = out;
1365                    $crate::image_encoding::encode_to($crate::image_encoding::Source::new(self), options, &mut out)
1366                }
1367
1368                /// Encode the frame as an image, as `options` describe, in a
1369                /// base64 data URL for HTML or JSON: `data:image/png;base64,`,
1370                /// `data:image/jpeg;base64,` or `data:image/webp;base64,` and the
1371                /// image.
1372                ///
1373                /// The string is allocated once, at its final length.
1374                ///
1375                /// # Errors
1376                ///
1377                /// As for [`encode_image`](Self::encode_image).
1378                ///
1379                /// # Example
1380                ///
1381                #[doc = concat!("```", $fence)]
1382                #[doc = $example]
1383                /// use grafton_ndi::{image_encoding::{Downscale, ImageFormat, ImageOptions}};
1384                ///
1385                /// let options = ImageOptions::new(ImageFormat::Jpeg(80)).downscale(Downscale::Quarter);
1386                /// let url = frame.encode_image_data_url(&options)?;
1387                /// println!("<img src=\"{url}\">");
1388                /// # Ok::<(), Box<dyn std::error::Error>>(())
1389                /// ```
1390                #[cfg(feature = "image-encoding")]
1391                fn encode_image_data_url(&self, options: &$crate::image_encoding::ImageOptions) -> $crate::Result<String> {
1392                    $crate::image_encoding::encode_data_url($crate::image_encoding::Source::new(self), options)
1393                }
1394
1395            }
1396            extra {}
1397        }
1398
1399        $(#[$attr])*
1400        impl<$($generics)*> ::std::fmt::Debug for $frame {
1401            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
1402                f.debug_struct($name)
1403                    .field("width", &self.width())
1404                    .field("height", &self.height())
1405                    .field("pixel_format", &self.pixel_format())
1406                    .field("frame_rate", &self.frame_rate())
1407                    .field("picture_aspect_ratio", &self.picture_aspect_ratio())
1408                    .field("scan_type", &self.scan_type())
1409                    .field("timecode", &self.timecode())
1410                    .field($data, &$crate::frames::VideoParts::layout(self).$data_len())
1411                    .field("line_stride_bytes", &self.line_stride_bytes())
1412                    .field("metadata", &self.metadata())
1413                    .field("timestamp", &self.timestamp())
1414                    .finish()
1415            }
1416        }
1417
1418    };
1419}
1420pub(crate) use video_accessors;
1421
1422/// An owned video frame with validated dimensions, format, stride, and buffer size.
1423///
1424/// Owned frames contain tightly packed active pixels: copies of borrowed or
1425/// received frames omit their row padding. Use [`Self::builder`] to create
1426/// one for sending. Cloning copies the pixels, readable metadata and metadata
1427/// status, including when received text was withheld.
1428///
1429/// The allocation that holds the pixels also holds the
1430/// [room](PixelFormat::send_tail_room) the SDK needs after a frame of this
1431/// layout and scan type, so an owned frame is sent in place. Construction,
1432/// copies, pixel replacement and scan-type changes preserve this invariant;
1433/// sending requires no pixel copy or allocation growth.
1434#[derive(Clone)]
1435pub struct VideoFrame {
1436    timing: VideoTiming,
1437    /// The layout, scan type, pixels and scan-dependent SDK room.
1438    data: VideoStorage,
1439    metadata: OwnedFrameMetadata,
1440    timestamp: Option<ReceivedTimestamp>,
1441}
1442
1443// SAFETY: VideoStorage owns the packed layout, initialized pixels and
1444// scan-dependent SDK tail. OwnedFrameMetadata owns bounded terminated text.
1445// Immutable borrows keep both allocations unchanged. VideoStorage::as_ptr
1446// derives from the owning Vec and covers its initialized storage and tail.
1447unsafe impl VideoParts for VideoFrame {
1448    #[inline]
1449    fn layout(&self) -> &ValidatedVideoLayout {
1450        self.data.layout()
1451    }
1452    #[inline]
1453    fn header(&self) -> VideoHeader {
1454        self.timing.with_scan_type(self.data.scan_type())
1455    }
1456    #[inline]
1457    fn pixels(&self) -> *const u8 {
1458        self.data.as_ptr()
1459    }
1460    #[inline]
1461    fn frame_metadata(&self) -> FrameMetadataRef<'_> {
1462        self.metadata.view()
1463    }
1464    #[inline]
1465    fn sdk_timestamp(&self) -> Option<ReceivedTimestamp> {
1466        self.timestamp
1467    }
1468
1469    fn initialized(&self) -> Initialized {
1470        Initialized::PackedSendReady
1471    }
1472}
1473
1474video_accessors! {
1475    impl[] VideoFrame;
1476    debug("VideoFrame", "data (bytes)" = data_len_bytes);
1477    timecode {
1478        /// A built frame starts with [`Timecode::SYNTHESIZE`]; a copy of a
1479        /// received frame keeps the timecode it arrived with.
1480    }
1481    line_stride_bytes {
1482        /// An owned frame's rows are tightly packed, so this is the packed
1483        /// stride.
1484    }
1485    plane {
1486        /// The rows of an owned frame have no padding.
1487    }
1488    timestamp {
1489        /// A frame has one only when it was copied from a received frame
1490        /// that carries one; frames built for sending have none.
1491    }
1492    data(self -> &[u8] => Some) {
1493        /// Get the frame data: every plane, tightly packed, in SDK plane order.
1494    } {
1495        self.data.as_slice()
1496    }
1497    to_owned(self) {
1498        /// Copy this frame, its readable metadata and its metadata status into
1499        /// independent owned storage.
1500        #[must_use]
1501    } {
1502        self.clone()
1503    }
1504    copy_into {
1505        /// Copy active pixels, header, timestamp and metadata into a reusable owned
1506        /// destination. Row padding is omitted; pixel and metadata capacity is reused.
1507        ///
1508        /// ```
1509        /// # use grafton_ndi::VideoFrame;
1510        /// let frame = VideoFrame::builder().resolution(2, 2).build()?;
1511        /// let mut spare = VideoFrame::builder().resolution(2, 2).build()?;
1512        /// frame.copy_into(&mut spare);
1513        /// assert_eq!(frame.data(), spare.data());
1514        /// # Ok::<(), grafton_ndi::Error>(())
1515        /// ```
1516    }
1517    sends_in_place {
1518        /// Whether synchronous sending reads this frame directly without a wrapper
1519        /// pixel copy. This cached-layout query allocates nothing and makes no SDK call.
1520        /// Captured padding is never assumed initialized; captures needing row padding
1521        /// or extra SDK tail room use reusable staging.
1522    }
1523    images("", "\
1524 # use grafton_ndi::{PixelFormat, VideoFrame};
1525 # let frame = VideoFrame::builder().resolution(64, 36).pixel_format(PixelFormat::Uyvy).build()?;") {}
1526}
1527
1528impl VideoFrame {
1529    /// Create a builder for a frame to send.
1530    ///
1531    /// Its defaults are 1920x1080 BGRA at 60/1 frames per second, square
1532    /// pixels (picture aspect ratio `0.0`), progressive scan, [`Timecode::SYNTHESIZE`], no
1533    /// metadata and zero-filled pixels.
1534    pub fn builder() -> VideoFrameBuilder {
1535        VideoFrameBuilder {
1536            width: 1920,
1537            height: 1080,
1538            pixel_format: PixelFormat::Bgra,
1539            frame_rate: crate::media::DEFAULT_VIDEO_FRAME_RATE,
1540            picture_aspect_ratio: PictureAspectRatio::SQUARE_PIXELS,
1541            scan_type: ScanType::Progressive,
1542            timecode: Timecode::SYNTHESIZE,
1543            metadata: None,
1544            data: None,
1545        }
1546    }
1547
1548    /// Backing allocations retained when a frame enters a bounded send queue.
1549    #[cfg(feature = "advanced")]
1550    pub(crate) fn retained_bytes(&self) -> usize {
1551        self.data
1552            .capacity()
1553            .saturating_add(self.metadata.retained_bytes())
1554    }
1555
1556    #[cfg(test)]
1557    pub(crate) fn as_test_raw(&self) -> NDIlib_video_frame_v2_t {
1558        self.video_descriptor()
1559    }
1560
1561    /// Set the timecode without reallocating the pixels.
1562    pub fn set_timecode(&mut self, timecode: Timecode) {
1563        self.timing.timecode = timecode;
1564    }
1565
1566    /// Set the scan type without changing the frame's validated layout.
1567    ///
1568    /// Grows the pixel allocation if this scan type needs more SDK tail
1569    /// room. Existing capacity is reused and never shrunk, so switching
1570    /// among scan types allocates at most once after construction.
1571    pub fn set_scan_type(&mut self, scan_type: ScanType) {
1572        self.data.set_scan_type(scan_type);
1573    }
1574
1575    /// Set the frame rate.
1576    pub fn set_frame_rate(&mut self, frame_rate: FrameRate) {
1577        self.timing.frame_rate = frame_rate;
1578    }
1579
1580    /// Set the picture aspect ratio, width over height as displayed; `0.0`
1581    /// means square pixels.
1582    ///
1583    /// The validated ratio is stored without further checks.
1584    pub fn set_picture_aspect_ratio(&mut self, ratio: PictureAspectRatio) {
1585        self.timing.picture_aspect_ratio = ratio;
1586    }
1587
1588    /// Recover the original pixel vector, retaining its allocation and capacity.
1589    ///
1590    /// The length covers pixels only; initialized SDK tail bytes remain in
1591    /// spare capacity and will be restored if the vector is built into a frame.
1592    pub fn into_data(self) -> Vec<u8> {
1593        self.data.into_vec()
1594    }
1595
1596    /// Replace pixels and recover the previous allocation for reuse.
1597    ///
1598    /// The incoming vector follows the allocation rules of [`Self::replace_data`].
1599    ///
1600    /// # Errors
1601    ///
1602    /// Returns `data` unchanged with [`Error::InvalidFrame`] when its length
1603    /// differs from the validated layout. The frame is unchanged.
1604    pub fn swap_data(&mut self, data: Vec<u8>) -> std::result::Result<Vec<u8>, Rejected<Vec<u8>>> {
1605        self.data.swap(data)
1606    }
1607
1608    /// Get mutable access to the frame data without changing the validated
1609    /// layout.
1610    pub fn data_mut(&mut self) -> &mut [u8] {
1611        self.data.as_mut_slice()
1612    }
1613
1614    /// The zero bytes that follow the pixels in the frame's allocation for
1615    /// the SDK to read, including any scan-dependent extra rows.
1616    #[cfg(test)]
1617    pub(crate) fn tail_room(&self) -> usize {
1618        self.data.room()
1619    }
1620
1621    /// Replace the owned frame data while preserving the validated layout.
1622    ///
1623    /// The frame keeps `data`'s allocation when its spare capacity holds the
1624    /// layout and scan type's [room](PixelFormat::send_tail_room), which is
1625    /// nothing for most formats, and otherwise grows it once, which may move
1626    /// the pixels.
1627    ///
1628    /// # Errors
1629    ///
1630    /// Returns `data`, unused, with [`Error::InvalidFrame`] if it is not
1631    /// exactly the validated layout size. The frame is unchanged.
1632    pub fn replace_data(&mut self, data: Vec<u8>) -> std::result::Result<(), Rejected<Vec<u8>>> {
1633        self.swap_data(data).map(drop)
1634    }
1635
1636    #[cfg(test)]
1637    pub(crate) fn metadata_cstr(&self) -> Option<&CStr> {
1638        self.metadata.view().text().map(MetadataText::as_cstr)
1639    }
1640
1641    /// Replace frame metadata. Use [`Self::clear_metadata`] to remove it.
1642    ///
1643    /// Valid replacement text sets [`FrameMetadataStatus::Text`], including
1644    /// an empty string. Invalid replacement text leaves the existing metadata
1645    /// and its status unchanged.
1646    ///
1647    /// # Errors
1648    ///
1649    /// Returns the unchanged text in [`Rejected`]. Its reason is
1650    /// [`Error::InvalidCString`] if `metadata` contains an interior NUL
1651    /// byte, or [`Error::InvalidFrame`] if the emitted C string would exceed
1652    /// the metadata size cap.
1653    /// The `NulError` retains only the prefix through the first NUL; use
1654    /// [`Rejected::into_inner`] for the whole original string.
1655    pub fn set_metadata(
1656        &mut self,
1657        metadata: impl Into<String>,
1658    ) -> std::result::Result<(), Rejected<String>> {
1659        self.metadata.set(metadata)
1660    }
1661
1662    /// Remove frame metadata, setting [`FrameMetadataStatus::Absent`] and
1663    /// retaining its allocation for later copies.
1664    pub fn clear_metadata(&mut self) {
1665        self.metadata.clear();
1666    }
1667
1668    /// # Safety
1669    /// `c_frame` must describe one live allocation covering its SDK plane
1670    /// layout, with every active row initialized and immutable through this
1671    /// copy, and null or SDK-readable metadata.
1672    #[cfg(test)]
1673    pub(crate) unsafe fn from_raw(c_frame: &NDIlib_video_frame_v2_t) -> Result<VideoFrame> {
1674        // SAFETY: forwarded to the caller; the borrow holds the descriptor.
1675        let frame = unsafe { ValidatedVideo::video_descriptor(c_frame)? };
1676        Ok(frame.owned_copy())
1677    }
1678}
1679
1680/// Builder for a [`VideoFrame`], reached through [`VideoFrame::builder`].
1681#[derive(Clone)]
1682pub struct VideoFrameBuilder {
1683    width: u32,
1684    height: u32,
1685    pixel_format: PixelFormat,
1686    frame_rate: FrameRate,
1687    picture_aspect_ratio: PictureAspectRatio,
1688    scan_type: ScanType,
1689    timecode: Timecode,
1690    metadata: Option<String>,
1691    data: Option<Vec<u8>>,
1692}
1693
1694impl fmt::Debug for VideoFrameBuilder {
1695    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1696        f.debug_struct("VideoFrameBuilder")
1697            .field("width", &self.width)
1698            .field("height", &self.height)
1699            .field("pixel_format", &self.pixel_format)
1700            .field("frame_rate", &self.frame_rate)
1701            .field("picture_aspect_ratio", &self.picture_aspect_ratio)
1702            .field("scan_type", &self.scan_type)
1703            .field("timecode", &self.timecode)
1704            .field("metadata", &self.metadata)
1705            .field("data (bytes)", &self.data.as_ref().map(Vec::len))
1706            .finish()
1707    }
1708}
1709
1710impl VideoFrameBuilder {
1711    /// Set the video resolution. Width must be positive and even; height must
1712    /// be positive (and even for 4:2:0 formats).
1713    #[must_use]
1714    pub fn resolution(mut self, width: u32, height: u32) -> Self {
1715        self.width = width;
1716        self.height = height;
1717        self
1718    }
1719
1720    /// Set the pixel format.
1721    #[must_use]
1722    pub fn pixel_format(mut self, pixel_format: PixelFormat) -> Self {
1723        self.pixel_format = pixel_format;
1724        self
1725    }
1726
1727    /// Set the frame rate.
1728    #[must_use]
1729    pub fn frame_rate(mut self, frame_rate: FrameRate) -> Self {
1730        self.frame_rate = frame_rate;
1731        self
1732    }
1733
1734    /// Set the picture aspect ratio, width over height as displayed; `0.0`
1735    /// means square pixels.
1736    #[must_use]
1737    pub fn picture_aspect_ratio(mut self, ratio: PictureAspectRatio) -> Self {
1738        self.picture_aspect_ratio = ratio;
1739        self
1740    }
1741
1742    /// Set the scan type (progressive, interlaced, etc.).
1743    #[must_use]
1744    pub fn scan_type(mut self, scan_type: ScanType) -> Self {
1745        self.scan_type = scan_type;
1746        self
1747    }
1748
1749    /// Set the timecode.
1750    #[must_use]
1751    pub fn timecode(mut self, timecode: Timecode) -> Self {
1752        self.timecode = timecode;
1753        self
1754    }
1755
1756    /// Set the metadata text.
1757    /// A refused build retains this text; recover it with
1758    /// [`Self::supplied_metadata`] or [`Self::take_metadata`] to repair it.
1759    /// An owned string retains its allocation when there is capacity for
1760    /// the trailing NUL; invalid metadata leaves a rejected builder unchanged.
1761    #[must_use]
1762    pub fn metadata<S: Into<String>>(mut self, metadata: S) -> Self {
1763        self.metadata = Some(metadata.into());
1764        self
1765    }
1766
1767    /// Supply owned pixels without an intermediate zero-filled allocation.
1768    ///
1769    /// `build` requires exactly the validated layout size. The frame keeps
1770    /// this allocation when its spare capacity holds the layout and scan
1771    /// type's [room](PixelFormat::send_tail_room), which is nothing for most
1772    /// formats, and otherwise grows it once, which may move the pixels. Use
1773    /// `data_mut` on the resulting frame for reuse.
1774    #[must_use]
1775    pub fn data(mut self, data: Vec<u8>) -> Self {
1776        self.data = Some(data);
1777        self
1778    }
1779
1780    /// The caller-supplied pixels, before any validation or transformation.
1781    pub fn supplied_data(&self) -> Option<&[u8]> {
1782        self.data.as_deref()
1783    }
1784
1785    /// Take supplied data while retaining the builder's other settings.
1786    ///
1787    /// This permits repairing a refused buffer and putting it back with
1788    /// [`Self::data`]. Until then, building uses the zero-filled default.
1789    pub fn take_data(&mut self) -> Option<Vec<u8>> {
1790        self.data.take()
1791    }
1792
1793    /// Recover the caller-supplied vector without building a frame.
1794    ///
1795    /// Its allocation, capacity and bytes are unchanged, including after a
1796    /// failed [`Self::build`]. Returns `None` for zero-filled default input.
1797    pub fn into_data(self) -> Option<Vec<u8>> {
1798        self.data
1799    }
1800
1801    /// Use zero-filled default data instead of a supplied buffer.
1802    ///
1803    /// Recover the buffer first with [`Self::take_data`] when it is needed again.
1804    #[must_use]
1805    pub fn clear_data(mut self) -> Self {
1806        self.data = None;
1807        self
1808    }
1809
1810    /// The supplied metadata before validation or termination.
1811    pub fn supplied_metadata(&self) -> Option<&str> {
1812        self.metadata.as_deref()
1813    }
1814
1815    /// Recover metadata while retaining the builder's other settings.
1816    /// Its allocation and text are unchanged after a refused build.
1817    pub fn take_metadata(&mut self) -> Option<String> {
1818        self.metadata.take()
1819    }
1820
1821    /// Remove metadata, for example to repair a rejected builder.
1822    #[must_use]
1823    pub fn clear_metadata(mut self) -> Self {
1824        self.metadata = None;
1825        self
1826    }
1827
1828    /// Build the video frame.
1829    ///
1830    /// Unset fields keep the defaults [`VideoFrame::builder`] lists. Building
1831    /// never loads or queries an NDI runtime: whether the runtime can send
1832    /// the pixel format is checked when the frame is sent.
1833    ///
1834    /// # Errors
1835    ///
1836    /// Returns the unchanged builder with [`Error::InvalidFrame`] if the
1837    /// resolution, pixel format, metadata size or supplied data
1838    /// length do not form a
1839    /// valid frame, and [`Error::InvalidCString`] for metadata containing a
1840    /// NUL byte.
1841    pub fn build(mut self) -> std::result::Result<VideoFrame, Rejected<Self>> {
1842        let layout = match PackedVideoLayout::new(self.pixel_format, self.width, self.height) {
1843            Ok(layout) => layout,
1844            Err(error) => return Err(Rejected::new(error, self)),
1845        };
1846        let (data, metadata) = match self.data.take() {
1847            Some(data) => match VideoStorage::adopt(layout, data, self.scan_type, || {
1848                CheckedMetadata::take_from(&mut self.metadata)
1849            }) {
1850                Ok(checked) => checked,
1851                Err(rejected) => {
1852                    let (error, data) = rejected.into_parts();
1853                    self.data = Some(data);
1854                    return Err(Rejected::new(error, self));
1855                }
1856            },
1857            None => {
1858                let metadata = match CheckedMetadata::take_from(&mut self.metadata) {
1859                    Ok(metadata) => metadata,
1860                    Err(error) => return Err(Rejected::new(error, self)),
1861                };
1862                (VideoStorage::zeroed(layout, self.scan_type), metadata)
1863            }
1864        };
1865
1866        Ok(VideoFrame {
1867            timing: VideoTiming {
1868                frame_rate: self.frame_rate,
1869                picture_aspect_ratio: self.picture_aspect_ratio,
1870                timecode: self.timecode,
1871            },
1872            data,
1873            metadata: metadata.into_owned(),
1874            timestamp: None,
1875        })
1876    }
1877}
1878
1879/// The parts of an audio frame that its shared accessors and owned copies
1880/// read.
1881///
1882/// [`AudioFrame`], [`BorrowedAudioFrame`], internal validated audio, and the
1883/// borrowed [`AudioFrameRef`] and [`FrameSyncAudioRef`](crate::FrameSyncAudioRef)
1884/// views lend their validated layout, timing, samples and metadata through it.
1885/// [`audio_accessors!`] generates their public accessors and `Debug`, so each
1886/// is written and documented once. Each implementation takes every part from
1887/// one value that was validated as a whole; the validated audio
1888/// implementation covers receiver and synchronizer guards.
1889///
1890/// # Safety
1891///
1892/// The channel views read through [`samples`](Self::samples): it must point
1893/// to `f32`-aligned storage that [`layout`](Self::layout) describes, with
1894/// every channel's samples initialized and unchanged while `self` is
1895/// borrowed. Padding between channels need not be initialized. Metadata text
1896/// must remain a bounded NUL-terminated UTF-8 string for the borrow.
1897/// Views, copying and descriptors are non-overridable helpers.
1898pub(crate) unsafe trait AudioParts {
1899    /// The validated layout of the frame's samples; stable for the borrow.
1900    fn layout(&self) -> &ValidatedAudioLayout;
1901
1902    /// The frame's timecode.
1903    fn audio_timecode(&self) -> Timecode;
1904
1905    /// The timestamp carried by the received frame, when present.
1906    fn sdk_timestamp(&self) -> Option<ReceivedTimestamp>;
1907
1908    /// The start of the frame's sample storage.
1909    fn samples(&self) -> *const f32;
1910
1911    /// The frame's one validated metadata observation.
1912    fn frame_metadata(&self) -> FrameMetadataRef<'_>;
1913}
1914
1915/// Shared audio operations whose blanket implementation prevents overrides.
1916pub(crate) trait AudioPartsExt: AudioParts {
1917    /// Borrow the original validated channel stride, samples and metadata.
1918    fn audio_descriptor(&self) -> NDIlib_audio_frame_v3_t {
1919        let layout = self.layout();
1920        NDIlib_audio_frame_v3_t {
1921            sample_rate: layout.sdk_sample_rate(),
1922            no_channels: layout.sdk_num_channels(),
1923            no_samples: layout.sdk_num_samples(),
1924            timecode: self.audio_timecode().ticks(),
1925            FourCC: layout.format().to_sdk(),
1926            p_data: self.samples().cast_mut().cast(),
1927            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
1928                channel_stride_in_bytes: layout.sdk_channel_stride(),
1929            },
1930            p_metadata: self.frame_metadata().as_ptr(),
1931            timestamp: ReceivedTimestamp::to_sdk(self.sdk_timestamp()),
1932        }
1933    }
1934
1935    /// One channel's samples, or `None` for an invalid channel: the view
1936    /// behind every generated `channel_data`.
1937    #[inline]
1938    fn channel_view(&self, channel: usize) -> Option<&[f32]> {
1939        // SAFETY: the trait's contract: `samples` points to aligned storage
1940        // `layout` describes, with every channel's samples initialized and
1941        // unchanged while `self`, which the slice borrows, is borrowed.
1942        unsafe { self.layout().channel(self.samples(), channel) }
1943    }
1944
1945    /// Every channel's samples, in order: the view behind every generated
1946    /// `channels`.
1947    #[inline]
1948    fn channel_views(&self) -> AudioChannels<'_> {
1949        // SAFETY: as for `channel_view`.
1950        unsafe { self.layout().channels(self.samples()) }
1951    }
1952
1953    /// Every sample, channels back to back, or `None` when padding separates
1954    /// channels: the view behind a received frame's `data`.
1955    #[inline]
1956    fn contiguous_samples(&self) -> Option<&[f32]> {
1957        // SAFETY: as for `channel_view`.
1958        unsafe { self.layout().view_samples(self.samples()) }
1959    }
1960
1961    /// Copy active samples using a single snapshot of the source layout.
1962    fn owned_copy(&self) -> AudioFrame {
1963        let timecode = self.audio_timecode();
1964        let timestamp = self.sdk_timestamp();
1965        let metadata = OwnedFrameMetadata::copied(self.frame_metadata());
1966        let data = PackedStorage::copied(AudioCopy::new(self), 0);
1967        AudioFrame {
1968            data,
1969            timecode,
1970            metadata,
1971            timestamp,
1972        }
1973    }
1974
1975    /// Copy samples and metadata, reusing their allocations when sufficient.
1976    /// The storage kernel preserves the previous layout/storage pairing on unwind.
1977    fn copy_into_owned(&self, destination: &mut AudioFrame) {
1978        let timecode = self.audio_timecode();
1979        let timestamp = self.sdk_timestamp();
1980        destination.metadata.copy_from(self.frame_metadata());
1981        destination.data.refill_from(AudioCopy::new(self), 0);
1982        destination.timecode = timecode;
1983        destination.timestamp = timestamp;
1984    }
1985}
1986
1987impl<T: AudioParts + ?Sized> AudioPartsExt for T {}
1988
1989/// A validated planar audio input for synchronous sending and conversion.
1990///
1991/// Implemented by [`AudioFrame`], [`BorrowedAudioFrame`], [`AudioFrameRef`] and
1992/// [`FrameSyncAudioRef`], and Advanced AV-sync audio references. Generic and
1993/// `dyn AudioSource` consumers can inspect
1994/// validated layouts and channel samples without allocating.
1995/// This sealed trait prevents unchecked sample pointers or channel layouts.
1996/// Native operations borrow the original samples and channel stride directly,
1997/// with no intermediate owned planar copy or wrapper allocation. The input's
1998/// lifetime and thread restrictions still apply.
1999#[allow(private_bounds)]
2000pub trait AudioSource: AudioParts {
2001    /// Sample rate in Hz.
2002    fn sample_rate(&self) -> u32;
2003
2004    /// Number of channels.
2005    fn num_channels(&self) -> u32;
2006
2007    /// Number of active samples per channel.
2008    fn num_samples(&self) -> u32;
2009
2010    /// Validated planar floating-point audio format.
2011    fn format(&self) -> AudioFormat;
2012
2013    /// Distance in bytes between consecutive channel starts.
2014    fn channel_stride_bytes(&self) -> usize;
2015
2016    /// Frame timecode, or the sender's synthesis sentinel.
2017    fn timecode(&self) -> Timecode;
2018
2019    /// Source-dependent timestamp supplied by the SDK for a captured frame.
2020    fn timestamp(&self) -> Option<ReceivedTimestamp>;
2021
2022    /// UTF-8 metadata; an explicit empty string differs from no metadata.
2023    /// Unreadable received text is withheld; inspect [`Self::metadata_status`].
2024    fn metadata(&self) -> Option<&str>;
2025
2026    /// Whether per-frame metadata is absent, readable, or withheld as unreadable.
2027    fn metadata_status(&self) -> FrameMetadataStatus;
2028
2029    /// One channel's initialized samples, excluding any inter-channel padding.
2030    fn channel_data(&self, channel: usize) -> Option<&[f32]>;
2031
2032    /// Iterate initialized channel samples without allocating or reading padding.
2033    fn channels(&self) -> AudioChannels<'_>;
2034
2035    /// Contiguous samples, or `None` when padding separates channels.
2036    fn data(&self) -> Option<&[f32]>;
2037
2038    /// Copy samples and readable metadata into a new owned, tightly packed
2039    /// planar frame. Withheld metadata keeps its status without its text.
2040    /// Allocates sample storage and, when present, readable metadata storage.
2041    fn to_owned(&self) -> AudioFrame;
2042
2043    /// Copy into an owned destination, reusing sample and metadata allocations
2044    /// when their capacities permit. Padding is omitted. Absent source metadata
2045    /// clears the destination text while retaining its allocation.
2046    fn copy_into(&self, destination: &mut AudioFrame);
2047}
2048
2049/// Generate an audio frame type's shared public accessors and its `Debug`
2050/// from its [`AudioParts`], so that each accessor is written, and
2051/// documented, once. Every generated method delegates to the frame's
2052/// validated parts.
2053///
2054/// A frame type passes its `impl` header, its `Debug` name and, for the
2055/// accessors whose meaning differs between types, the type-specific
2056/// paragraph of their docs.
2057macro_rules! audio_accessors {
2058    (
2059        $(#[$attr:meta])*
2060        impl[$($generics:tt)*] $frame:ty;
2061        debug($name:expr, $data:literal = $data_len:ident);
2062        timecode { $(#[$timecode:meta])* }
2063        timestamp { $(#[$timestamp:meta])* }
2064        channel_stride_bytes { $(#[$channel_stride:meta])* }
2065        channel_data { $(#[$channel_data:meta])* }
2066        data($data_self:ident -> $data_ty:ty $(=> $data_map:ident)?) { $(#[$data_doc:meta])* } $data_body:block
2067        to_owned($owned_self:ident) { $(#[$owned_doc:meta])* } $owned_body:block
2068        copy_into { $(#[$copy_doc:meta])* }
2069    ) => {
2070        source_accessors! {
2071            $(#[$attr])*
2072            impl[$($generics)*] $frame;
2073            source(AudioSource);
2074            methods {
2075                /// Get the sample rate in Hz.
2076                #[inline]
2077                fn sample_rate(&self) -> u32 {
2078                    AudioParts::layout(self).sample_rate()
2079                }
2080
2081                /// Get the number of audio channels.
2082                #[inline]
2083                fn num_channels(&self) -> u32 {
2084                    AudioParts::layout(self).num_channels()
2085                }
2086
2087                /// Get the number of samples per channel.
2088                #[inline]
2089                fn num_samples(&self) -> u32 {
2090                    AudioParts::layout(self).num_samples()
2091                }
2092
2093                /// Get the timecode.
2094                ///
2095                $(#[$timecode])*
2096                #[inline]
2097                fn timecode(&self) -> Timecode {
2098                    AudioParts::audio_timecode(self)
2099                }
2100
2101                /// The source-dependent timestamp of the received frame.
2102                ///
2103                $(#[$timestamp])*
2104                #[inline]
2105                fn timestamp(&self) -> Option<ReceivedTimestamp> {
2106                    AudioParts::sdk_timestamp(self)
2107                }
2108
2109                /// Get the audio format.
2110                ///
2111                /// It is a supported format, validated when the frame was
2112                /// constructed.
2113                #[inline]
2114                fn format(&self) -> AudioFormat {
2115                    AudioParts::layout(self).format()
2116                }
2117
2118                /// Get the distance between the starts of consecutive channels in
2119                /// bytes.
2120                ///
2121                $(#[$channel_stride])*
2122                #[inline]
2123                fn channel_stride_bytes(&self) -> usize {
2124                    AudioParts::layout(self).channel_stride_bytes()
2125                }
2126
2127                /// Get frame metadata as UTF-8 text, if present.
2128                ///
2129                /// Empty metadata, `Some("")`, is distinct from none, `None`.
2130                /// Unreadable received text returns `None`; use
2131                /// [`Self::metadata_status`] to distinguish it from absent text.
2132                #[inline]
2133                fn metadata(&self) -> Option<&str> {
2134                    AudioParts::frame_metadata(self).text().map(MetadataText::as_str)
2135                }
2136
2137                /// The metadata's presence or the reason unreadable received text
2138                /// was withheld. Querying the cached status allocates nothing.
2139                #[inline]
2140                fn metadata_status(&self) -> crate::FrameMetadataStatus {
2141                    AudioParts::frame_metadata(self).status()
2142                }
2143
2144                /// Get one channel's samples, or `None` for an invalid channel.
2145                ///
2146                /// The slice borrows the frame's samples without copying and
2147                /// excludes any padding between channels.
2148                ///
2149                $(#[$channel_data])*
2150                #[inline]
2151                fn channel_data(&self, channel: usize) -> Option<&[f32]> {
2152                    AudioPartsExt::channel_view(self, channel)
2153                }
2154
2155                /// Iterate over the channels' samples, in channel order, without
2156                /// copying or reading padding between channels.
2157                #[inline]
2158                fn channels(&self) -> AudioChannels<'_> {
2159                    AudioPartsExt::channel_views(self)
2160                }
2161
2162                    $(#[$data_doc])*
2163                    fn data(&$data_self) -> $data_ty $data_body $(=> ($data_map, Option<&[f32]>))?
2164                    $(#[$owned_doc])*
2165                    fn to_owned(&$owned_self) -> AudioFrame $owned_body
2166                    $(#[$copy_doc])*
2167                    fn copy_into(&self, destination: &mut AudioFrame) {
2168                        AudioPartsExt::copy_into_owned(self, destination);
2169                    }
2170
2171            }
2172            extra {}
2173        }
2174        $(#[$attr])*
2175        impl<$($generics)*> ::std::fmt::Debug for $frame {
2176            fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result {
2177                f.debug_struct($name)
2178                    .field("sample_rate", &self.sample_rate())
2179                    .field("num_channels", &self.num_channels())
2180                    .field("num_samples", &self.num_samples())
2181                    .field("timecode", &self.timecode())
2182                    .field("format", &self.format())
2183                    .field($data, &AudioParts::layout(self).$data_len())
2184                    .field("channel_stride_bytes", &self.channel_stride_bytes())
2185                    .field("metadata", &self.metadata())
2186                    .field("timestamp", &self.timestamp())
2187                    .finish()
2188            }
2189        }
2190
2191    };
2192}
2193
2194mod borrowed;
2195pub use borrowed::{
2196    BorrowedAudioFrame, BorrowedAudioFrameBuilder, BorrowedVideoFrame, BorrowedVideoFrameBuilder,
2197};
2198
2199/// Owned, tightly packed planar floating-point audio with a validated layout.
2200///
2201/// Channel samples are contiguous, with channels stored one after another.
2202/// Conversion from borrowed SDK audio omits inter-channel padding. Cloning
2203/// copies the samples, readable metadata and metadata status, including when
2204/// received text was withheld.
2205#[derive(Clone)]
2206pub struct AudioFrame {
2207    timecode: Timecode,
2208    data: PackedStorage<PackedAudioLayout>,
2209    metadata: OwnedFrameMetadata,
2210    timestamp: Option<ReceivedTimestamp>,
2211}
2212
2213// SAFETY: PackedStorage privately pairs its layout with initialized samples;
2214// OwnedFrameMetadata owns bounded terminated text. Both stay unchanged for the
2215// borrow, and the default descriptor addresses only those live allocations.
2216unsafe impl AudioParts for AudioFrame {
2217    #[inline]
2218    fn layout(&self) -> &ValidatedAudioLayout {
2219        self.data.layout().as_layout()
2220    }
2221    #[inline]
2222    fn audio_timecode(&self) -> Timecode {
2223        self.timecode
2224    }
2225    #[inline]
2226    fn sdk_timestamp(&self) -> Option<ReceivedTimestamp> {
2227        self.timestamp
2228    }
2229    #[inline]
2230    fn samples(&self) -> *const f32 {
2231        self.data.as_ptr()
2232    }
2233    #[inline]
2234    fn frame_metadata(&self) -> FrameMetadataRef<'_> {
2235        self.metadata.view()
2236    }
2237}
2238
2239audio_accessors! {
2240    impl[] AudioFrame;
2241    debug("AudioFrame", "data (samples)" = sample_count);
2242    timecode {
2243        /// A built frame starts with [`Timecode::SYNTHESIZE`]; a copy of a
2244        /// received frame keeps the timecode it arrived with.
2245    }
2246    timestamp {
2247        /// A frame has one only when it was copied from a received frame
2248        /// that carries one; frames built for sending have none.
2249    }
2250    channel_stride_bytes {
2251        /// It is one channel's samples, since an owned frame has no padding.
2252    }
2253    channel_data {
2254        /// Samples for this channel are contiguous in the packed planar data.
2255    }
2256    data(self -> &[f32] => Some) {
2257        /// Get tightly packed planar audio as 32-bit floats.
2258        /// Each channel's samples are contiguous; channels follow one another.
2259    } {
2260        self.data.as_slice()
2261    }
2262    to_owned(self) {
2263        /// Copy this frame, its readable metadata and its metadata status into
2264        /// independent owned storage.
2265        #[must_use]
2266    } {
2267        self.clone()
2268    }
2269    copy_into {
2270        /// Copy samples, header, timestamp and metadata into a reusable owned frame.
2271        /// Existing sample and metadata capacity is reused when it is sufficient.
2272    }
2273
2274}
2275
2276impl AudioFrame {
2277    /// Copy validated interleaved floating-point samples into packed planar audio.
2278    ///
2279    /// This conversion needs no NDI runtime and allocates only the output
2280    /// samples. It preserves the input's timecode; metadata is absent and the
2281    /// received timestamp is `None`. Use [`Self::set_metadata`] to attach metadata.
2282    pub fn from_interleaved(source: &crate::audio_conversion::InterleavedAudioF32<'_>) -> Self {
2283        let mut frame = Self::from_validated_silence(source.layout(), source.timecode());
2284        let channels = frame.layout().no_channels();
2285        let samples = frame.layout().no_samples();
2286        // The input's validated shape proves it contains exactly `samples`
2287        // groups of `channels` initialized interleaved values.
2288        for (channel, output) in frame
2289            .data
2290            .as_mut_slice()
2291            .chunks_exact_mut(samples)
2292            .enumerate()
2293        {
2294            for (destination, &sample) in output
2295                .iter_mut()
2296                .zip(source.data()[channel..].iter().step_by(channels))
2297            {
2298                *destination = sample;
2299            }
2300        }
2301        frame
2302    }
2303
2304    /// Allocate silent packed samples for a shape that is already validated.
2305    /// Metadata and receive timestamp keep the ordinary outbound defaults.
2306    pub(crate) fn from_validated_silence(layout: ValidatedAudioLayout, timecode: Timecode) -> Self {
2307        let layout = layout.packed();
2308        Self {
2309            timecode,
2310            data: PackedStorage::zeroed(layout, 0),
2311            metadata: OwnedFrameMetadata::default(),
2312            timestamp: None,
2313        }
2314    }
2315
2316    /// Create a builder for a frame to send.
2317    ///
2318    /// Its defaults are 48 kHz stereo FLTP with 1024 samples per channel,
2319    /// planar input, [`Timecode::SYNTHESIZE`], no metadata and silent
2320    /// samples.
2321    pub fn builder() -> AudioFrameBuilder {
2322        AudioFrameBuilder {
2323            sample_rate: 48_000,
2324            num_channels: 2,
2325            num_samples: 1024,
2326            timecode: Timecode::SYNTHESIZE,
2327            data: None,
2328            metadata: None,
2329        }
2330    }
2331
2332    #[cfg(test)]
2333    /// # Safety
2334    /// `raw` must reference live SDK sample and metadata allocations with
2335    /// initialized active samples through this ownership copy.
2336    pub(crate) unsafe fn from_raw(raw: NDIlib_audio_frame_v3_t) -> Result<AudioFrame> {
2337        // SAFETY: forwarded to the caller; the borrow holds the descriptor.
2338        let frame = unsafe { ValidatedAudio::audio_descriptor(&raw)? };
2339        Ok(frame.owned_copy())
2340    }
2341
2342    /// Set the timecode without reallocating the samples.
2343    pub fn set_timecode(&mut self, timecode: Timecode) {
2344        self.timecode = timecode;
2345    }
2346
2347    /// Recover tightly packed planar samples, retaining their allocation and capacity.
2348    pub fn into_data(self) -> Vec<f32> {
2349        self.data.into_vec()
2350    }
2351
2352    /// Replace samples and return the previous vector for allocation reuse.
2353    ///
2354    /// # Errors
2355    ///
2356    /// Returns `data` unchanged with [`Error::InvalidFrame`] unless it has
2357    /// exactly the validated sample count. The frame is unchanged.
2358    pub fn swap_data(
2359        &mut self,
2360        data: Vec<f32>,
2361    ) -> std::result::Result<Vec<f32>, Rejected<Vec<f32>>> {
2362        self.data.swap(data, 0)
2363    }
2364
2365    /// Get mutable audio sample data without changing the validated layout.
2366    pub fn data_mut(&mut self) -> &mut [f32] {
2367        self.data.as_mut_slice()
2368    }
2369
2370    /// Replace the owned audio data while preserving the validated layout.
2371    ///
2372    /// # Errors
2373    ///
2374    /// Returns `data`, unused, with [`Error::InvalidFrame`] if it is not
2375    /// exactly the validated sample count. The frame is unchanged.
2376    pub fn replace_data(&mut self, data: Vec<f32>) -> std::result::Result<(), Rejected<Vec<f32>>> {
2377        self.swap_data(data).map(drop)
2378    }
2379
2380    /// Replace frame metadata. Use [`Self::clear_metadata`] to remove it.
2381    ///
2382    /// Valid replacement text sets [`FrameMetadataStatus::Text`], including
2383    /// an empty string. Invalid replacement text leaves the existing metadata
2384    /// and its status unchanged.
2385    ///
2386    /// # Errors
2387    ///
2388    /// Returns the unchanged text in [`Rejected`]. Its reason is
2389    /// [`Error::InvalidCString`] if `metadata` contains an interior NUL
2390    /// byte, or [`Error::InvalidFrame`] if the emitted C string would exceed
2391    /// the metadata size cap.
2392    /// The `NulError` retains only the prefix through the first NUL; use
2393    /// [`Rejected::into_inner`] for the whole original string.
2394    pub fn set_metadata(
2395        &mut self,
2396        metadata: impl Into<String>,
2397    ) -> std::result::Result<(), Rejected<String>> {
2398        self.metadata.set(metadata)
2399    }
2400
2401    /// Remove frame metadata, setting [`FrameMetadataStatus::Absent`] and
2402    /// retaining its allocation for later copies.
2403    pub fn clear_metadata(&mut self) {
2404        self.metadata.clear();
2405    }
2406
2407    /// Get mutable samples for one channel without allocating.
2408    pub fn channel_data_mut(&mut self, channel: usize) -> Option<&mut [f32]> {
2409        let range = self.layout().channel_range(channel)?;
2410        Some(&mut self.data.as_mut_slice()[range])
2411    }
2412}
2413
2414/// Builder for an [`AudioFrame`], reached through [`AudioFrame::builder`].
2415#[derive(Clone)]
2416pub struct AudioFrameBuilder {
2417    sample_rate: u32,
2418    num_channels: u32,
2419    num_samples: u32,
2420    timecode: Timecode,
2421    data: Option<Vec<f32>>,
2422    metadata: Option<String>,
2423}
2424
2425impl fmt::Debug for AudioFrameBuilder {
2426    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2427        f.debug_struct("AudioFrameBuilder")
2428            .field("sample_rate", &self.sample_rate)
2429            .field("num_channels", &self.num_channels)
2430            .field("num_samples", &self.num_samples)
2431            .field("timecode", &self.timecode)
2432            .field("metadata", &self.metadata)
2433            .field("data (samples)", &self.data.as_ref().map(Vec::len))
2434            .finish()
2435    }
2436}
2437
2438impl AudioFrameBuilder {
2439    /// Set the sample rate in Hz.
2440    #[must_use]
2441    pub fn sample_rate(mut self, sample_rate: u32) -> Self {
2442        self.sample_rate = sample_rate;
2443        self
2444    }
2445
2446    /// Set the number of audio channels.
2447    #[must_use]
2448    pub fn num_channels(mut self, num_channels: u32) -> Self {
2449        self.num_channels = num_channels;
2450        self
2451    }
2452
2453    /// Set the number of samples per channel.
2454    #[must_use]
2455    pub fn num_samples(mut self, num_samples: u32) -> Self {
2456        self.num_samples = num_samples;
2457        self
2458    }
2459
2460    /// Set the timecode.
2461    #[must_use]
2462    pub fn timecode(mut self, timecode: Timecode) -> Self {
2463        self.timecode = timecode;
2464        self
2465    }
2466
2467    /// Set packed planar 32-bit samples, with every sample of channel 0 first,
2468    /// then every sample of channel 1, and so on.
2469    ///
2470    /// The length must equal `num_channels * num_samples`. For interleaved
2471    /// input, use [`AudioFrame::from_interleaved`].
2472    #[must_use]
2473    pub fn data(mut self, data: Vec<f32>) -> Self {
2474        self.data = Some(data);
2475        self
2476    }
2477
2478    /// Set the metadata text.
2479    /// A refused build retains this text; recover it with
2480    /// [`Self::supplied_metadata`] or [`Self::take_metadata`] to repair it.
2481    /// An owned string retains its allocation when there is capacity for
2482    /// the trailing NUL; invalid metadata leaves a rejected builder unchanged.
2483    #[must_use]
2484    pub fn metadata<S: Into<String>>(mut self, metadata: S) -> Self {
2485        self.metadata = Some(metadata.into());
2486        self
2487    }
2488
2489    /// The caller-supplied packed planar samples.
2490    pub fn supplied_data(&self) -> Option<&[f32]> {
2491        self.data.as_deref()
2492    }
2493
2494    /// Take supplied data while retaining the builder's other settings.
2495    ///
2496    /// This permits repairing a refused buffer and putting it back with
2497    /// [`Self::data`]. Until then, building uses the zero-filled default.
2498    pub fn take_data(&mut self) -> Option<Vec<f32>> {
2499        self.data.take()
2500    }
2501
2502    /// Recover the original supplied samples, retaining allocation and capacity.
2503    ///
2504    /// A rejected builder retains untouched samples. Returns `None` for default
2505    /// silent input.
2506    pub fn into_data(self) -> Option<Vec<f32>> {
2507        self.data
2508    }
2509
2510    /// Use zero-filled default data instead of a supplied buffer.
2511    ///
2512    /// Recover the buffer first with [`Self::take_data`] when it is needed again.
2513    #[must_use]
2514    pub fn clear_data(mut self) -> Self {
2515        self.data = None;
2516        self
2517    }
2518
2519    /// The supplied metadata before validation or termination.
2520    pub fn supplied_metadata(&self) -> Option<&str> {
2521        self.metadata.as_deref()
2522    }
2523
2524    /// Recover metadata while retaining the builder's other settings.
2525    /// Its allocation and text are unchanged after a refused build.
2526    pub fn take_metadata(&mut self) -> Option<String> {
2527        self.metadata.take()
2528    }
2529
2530    /// Remove metadata, for example to repair a rejected builder.
2531    #[must_use]
2532    pub fn clear_metadata(mut self) -> Self {
2533        self.metadata = None;
2534        self
2535    }
2536
2537    /// Build the audio frame.
2538    ///
2539    /// Unset fields keep the defaults [`AudioFrame::builder`] lists. The frame
2540    /// stores packed planar data with channels `num_samples * 4` bytes apart.
2541    ///
2542    /// # Errors
2543    ///
2544    /// Returns the unchanged builder with [`Error::InvalidFrame`] if the sample
2545    /// rate, channel or sample count, metadata size or supplied data length
2546    /// do not form a valid
2547    /// frame, and [`Error::InvalidCString`] for metadata containing a NUL
2548    /// byte.
2549    pub fn build(mut self) -> std::result::Result<AudioFrame, Rejected<Self>> {
2550        let layout = match validate_outbound_audio_layout(
2551            self.sample_rate,
2552            self.num_channels,
2553            self.num_samples,
2554            AudioFormat::Fltp,
2555        ) {
2556            Ok(layout) => layout,
2557            Err(error) => return Err(Rejected::new(error, self)),
2558        };
2559        let (data, metadata) = match self.data.take() {
2560            Some(data) => match PackedStorage::adopt(layout, data, 0, || {
2561                CheckedMetadata::take_from(&mut self.metadata)
2562            }) {
2563                Ok(checked) => checked,
2564                Err(rejected) => {
2565                    let (error, data) = rejected.into_parts();
2566                    self.data = Some(data);
2567                    return Err(Rejected::new(error, self));
2568                }
2569            },
2570            None => {
2571                let metadata = match CheckedMetadata::take_from(&mut self.metadata) {
2572                    Ok(metadata) => metadata,
2573                    Err(error) => return Err(Rejected::new(error, self)),
2574                };
2575                (PackedStorage::zeroed(layout, 0), metadata)
2576            }
2577        };
2578
2579        Ok(AudioFrame {
2580            timecode: self.timecode,
2581            data,
2582            metadata: metadata.into_owned(),
2583            timestamp: None,
2584        })
2585    }
2586}
2587
2588/// Audio format identifiers (FourCC codes).
2589///
2590/// Currently NDI primarily uses `FLTP` (32-bit floating point planar format).
2591///
2592/// This enum is marked `#[non_exhaustive]` to allow future NDI SDK versions to add new audio formats
2593/// without breaking existing code. Always use a wildcard pattern when matching.
2594///
2595/// # Examples
2596///
2597/// ```
2598/// use grafton_ndi::AudioFormat;
2599///
2600/// let format = AudioFormat::Fltp;
2601///
2602/// // When matching, always include a wildcard for forward compatibility
2603/// match format {
2604///     AudioFormat::Fltp => println!("32-bit float planar"),
2605///     _ => println!("Other format"),
2606/// }
2607/// ```
2608#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2609#[non_exhaustive]
2610pub enum AudioFormat {
2611    /// 32-bit floating point planar audio (FLTP).
2612    Fltp,
2613}
2614
2615crate::media::decoded_variants!(AudioFormat: Fltp);
2616
2617impl AudioFormat {
2618    /// The SDK's FourCC for this format.
2619    pub(crate) const fn to_sdk(self) -> NDIlib_FourCC_audio_type_e {
2620        match self {
2621            Self::Fltp => NDIlib_FourCC_audio_type_e_NDIlib_FourCC_audio_type_FLTP,
2622        }
2623    }
2624}
2625
2626const DCI_8K_WIDTH: u32 = 8192;
2627const DCI_8K_HEIGHT: u32 = 4320;
2628
2629const fn widest_pixel_bytes() -> usize {
2630    let mut widest = 0;
2631    let mut index = 0;
2632    while index < PixelFormat::ALL.len() {
2633        let bytes = PixelFormat::ALL[index].packed_bytes_per_pixel_ceil();
2634        if bytes > widest {
2635            widest = bytes;
2636        }
2637        index += 1;
2638    }
2639    widest
2640}
2641
2642// Revisit the frame and allocator limits when a wider format is introduced.
2643const_assert!(widest_pixel_bytes() == PixelFormat::Nb4g.packed_bytes_per_pixel_ceil());
2644
2645/// Maximum extent in bytes of an uncompressed video frame, excluding SDK send tail room.
2646///
2647/// Sized to admit a tightly packed DCI 8K frame in every supported
2648/// [pixel format](PixelFormat), including 16-bit planar NB4G.
2649pub const MAX_VIDEO_BYTES: usize =
2650    DCI_8K_WIDTH as usize * DCI_8K_HEIGHT as usize * widest_pixel_bytes();
2651
2652/// Maximum allowed size for audio frame data (64 MiB).
2653/// Comfortably above typical NDI audio frames while preventing unbounded allocations.
2654pub(crate) const MAX_AUDIO_BYTES: usize = 64 * 1024 * 1024;
2655
2656/// Maximum allowed size for SDK metadata C strings (4 MiB), including the
2657/// trailing NUL terminator.
2658pub(crate) const MAX_METADATA_BYTES: usize = 4 * 1024 * 1024;
2659
2660/// Owned UTF-8 metadata text and its timecode.
2661///
2662/// NDI expects XML when sending; callers are responsible for XML syntax. Text
2663/// cannot contain NUL bytes and is limited to 4 MiB including the SDK terminator.
2664///
2665/// # Examples
2666///
2667/// ```
2668/// use grafton_ndi::{MetadataFrame, Timecode};
2669///
2670/// let frame = MetadataFrame::new("<tally on_program=\"true\"/>")?
2671///     .with_timecode(Timecode::from_ticks(0));
2672/// assert_eq!(frame.data(), "<tally on_program=\"true\"/>");
2673/// assert_eq!(frame.timecode().ticks(), 0);
2674/// # Ok::<(), grafton_ndi::Error>(())
2675/// ```
2676#[derive(Clone, PartialEq, Eq, Hash)]
2677pub struct MetadataFrame {
2678    data: TerminatedText,
2679    timecode: Timecode,
2680}
2681
2682impl fmt::Debug for MetadataFrame {
2683    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2684        f.debug_struct("MetadataFrame")
2685            .field("data", &self.data())
2686            .field("data (bytes)", &self.as_bytes().len())
2687            .field("timecode", &self.timecode())
2688            .finish()
2689    }
2690}
2691
2692impl MetadataFrame {
2693    /// Create a metadata frame from UTF-8 text, with
2694    /// [`Timecode::SYNTHESIZE`].
2695    /// An owned string retains its allocation when there is capacity for
2696    /// the trailing NUL, and otherwise grows once.
2697    ///
2698    /// # Errors
2699    ///
2700    /// Returns the unchanged text in [`Rejected`]. Its reason is
2701    /// [`Error::InvalidCString`] if `data` contains an interior NUL byte
2702    /// or [`Error::InvalidFrame`] if the SDK metadata length would exceed the
2703    /// crate's metadata size limit.
2704    /// The `NulError` retains only the prefix through the first NUL; use
2705    /// [`Rejected::into_inner`] for the whole original string.
2706    pub fn new(data: impl Into<String>) -> std::result::Result<Self, Rejected<String>> {
2707        Ok(MetadataFrame {
2708            data: TerminatedText::new(data)?,
2709            timecode: Timecode::SYNTHESIZE,
2710        })
2711    }
2712
2713    /// Return this frame with `timecode`.
2714    #[must_use]
2715    pub fn with_timecode(mut self, timecode: Timecode) -> Self {
2716        self.timecode = timecode;
2717        self
2718    }
2719
2720    /// Get the metadata text.
2721    pub fn data(&self) -> &str {
2722        self.data.as_str()
2723    }
2724
2725    /// Get the UTF-8 payload bytes, excluding the trailing NUL.
2726    pub fn as_bytes(&self) -> &[u8] {
2727        self.data().as_bytes()
2728    }
2729
2730    /// Copy this frame into an independently owned metadata frame.
2731    #[must_use]
2732    pub fn to_owned(&self) -> Self {
2733        self.clone()
2734    }
2735
2736    /// Copy text and timecode into an existing frame. Reuses its text
2737    /// allocation when its capacity holds the text and trailing NUL.
2738    pub fn copy_into(&self, destination: &mut Self) {
2739        copy_metadata_into(self, destination);
2740    }
2741
2742    /// Consume the frame and return the owned metadata text.
2743    pub fn into_data(self) -> String {
2744        self.data.into_string()
2745    }
2746
2747    /// Get the timecode.
2748    ///
2749    /// A new frame starts with [`Timecode::SYNTHESIZE`]; a received frame
2750    /// keeps the timecode it arrived with.
2751    pub fn timecode(&self) -> Timecode {
2752        self.timecode
2753    }
2754
2755    /// Replace the metadata text.
2756    ///
2757    /// # Errors
2758    ///
2759    /// Returns the unchanged text in [`Rejected`]. Its reason is
2760    /// [`Error::InvalidCString`] if `data` contains an interior NUL byte
2761    /// or [`Error::InvalidFrame`] if the SDK metadata length would exceed the
2762    /// crate's metadata size limit. The frame is unchanged.
2763    /// The `NulError` retains only the prefix through the first NUL; use
2764    /// [`Rejected::into_inner`] for the whole original string.
2765    pub fn set_data(
2766        &mut self,
2767        data: impl Into<String>,
2768    ) -> std::result::Result<(), Rejected<String>> {
2769        self.data = TerminatedText::new(data)?;
2770        Ok(())
2771    }
2772
2773    /// Set the timecode.
2774    pub fn set_timecode(&mut self, timecode: Timecode) {
2775        self.timecode = timecode;
2776    }
2777
2778    /// Create from raw NDI metadata frame (copies the data)
2779    ///
2780    /// # Safety
2781    ///
2782    /// `raw` must be an SDK-populated metadata frame whose `p_data` pointer is
2783    /// valid for `raw.length` bytes when `length > 0`. For zero length with a
2784    /// non-null pointer, it must be readable through its first NUL terminator
2785    /// or the crate's metadata cap, as required by `validate_frame_metadata`.
2786    #[cfg(test)]
2787    pub(crate) unsafe fn from_raw(raw: &NDIlib_metadata_frame_t) -> Result<Self> {
2788        // SAFETY: forwarded to the caller.
2789        let text = unsafe { validate_metadata_layout(raw)? };
2790        Ok(Self::copied(text, Timecode::from_ticks(raw.timecode)))
2791    }
2792
2793    /// Copy validated metadata text into an owned frame. `None`, the empty
2794    /// null frame, carries no text; it is empty metadata.
2795    pub(crate) fn copied(text: Option<MetadataText<'_>>, timecode: Timecode) -> Self {
2796        let data = TerminatedText::copied(text.unwrap_or(MetadataText::EMPTY));
2797        Self { data, timecode }
2798    }
2799}
2800
2801/// The private, validated text boundary used by [`MetadataSource`].
2802///
2803/// # Safety
2804///
2805/// Returned text must be bounded NUL-terminated UTF-8, live and unchanged for
2806/// the borrow, including its terminator, within the metadata size cap.
2807/// Descriptor construction is a non-overridable helper.
2808pub(crate) unsafe trait MetadataParts {
2809    fn metadata_text_for_send(&self) -> Option<MetadataText<'_>>;
2810    fn metadata_timecode(&self) -> Timecode;
2811}
2812
2813/// Shared descriptor construction whose blanket implementation prevents overrides.
2814pub(crate) trait MetadataPartsExt: MetadataParts {
2815    /// Canonicalize empty metadata to a non-null empty C string. The SDK
2816    /// reads/copies the text during the call, and the source remains borrowed
2817    /// until it returns. MetadataText retains the SDK length bound.
2818    fn metadata_raw(&self) -> NDIlib_metadata_frame_t {
2819        let text = self.metadata_text_for_send();
2820        NDIlib_metadata_frame_t {
2821            length: text.unwrap_or(MetadataText::EMPTY).sdk_len(),
2822            timecode: self.metadata_timecode().ticks(),
2823            p_data: text.unwrap_or(MetadataText::EMPTY).as_ptr().cast_mut(),
2824        }
2825    }
2826}
2827
2828impl<T: MetadataParts + ?Sized> MetadataPartsExt for T {}
2829
2830/// A validated metadata input for sending, connection metadata and recording.
2831///
2832/// Implemented by [`MetadataFrame`] and [`MetadataFrameRef`]. Both can be sent
2833/// directly, including through `&dyn MetadataSource`, without a wrapper string
2834/// allocation or copy in synchronous sends. For connection registrations, the
2835/// receiver or router retains its own copy; senders use the SDK's documented
2836/// copy. A captured input may be released as soon as the operation returns.
2837/// Async recording copies the text immediately into its deferred command. The
2838/// source's timecode is preserved in every operation.
2839///
2840/// This trait is sealed: applications cannot supply unchecked native pointers.
2841#[allow(private_bounds)]
2842pub trait MetadataSource: MetadataParts {
2843    /// The UTF-8 text without its trailing NUL. Empty metadata returns `""`.
2844    fn data(&self) -> &str;
2845
2846    /// The payload bytes, excluding the trailing NUL.
2847    fn as_bytes(&self) -> &[u8];
2848
2849    /// The source timecode, including [`Timecode::SYNTHESIZE`] when requested.
2850    fn timecode(&self) -> Timecode;
2851
2852    /// Copy the text and timecode into an independently owned frame.
2853    fn to_owned(&self) -> MetadataFrame;
2854
2855    /// Copy into an existing frame, reusing its text allocation when its
2856    /// capacity holds the text and trailing NUL, even when the length changes.
2857    fn copy_into(&self, destination: &mut MetadataFrame);
2858}
2859
2860macro_rules! metadata_source {
2861    (impl[$($generics:tt)*] $frame:ty) => {
2862        impl<$($generics)*> MetadataSource for $frame {
2863            source_accessor_forward! { $frame; data(&self) -> &str; }
2864            source_accessor_forward! { $frame; as_bytes(&self) -> &[u8]; }
2865            source_accessor_forward! { $frame; timecode(&self) -> Timecode; }
2866            source_accessor_forward! { $frame; to_owned(&self) -> MetadataFrame; }
2867            source_accessor_forward! { $frame; copy_into(&self, destination: &mut MetadataFrame); }
2868        }
2869    };
2870}
2871
2872fn copy_metadata_into(source: &(impl MetadataParts + ?Sized), destination: &mut MetadataFrame) {
2873    let text = source
2874        .metadata_text_for_send()
2875        .unwrap_or(MetadataText::EMPTY);
2876    let MetadataFrame { data, timecode } = destination;
2877    data.copy_text(text);
2878    *timecode = source.metadata_timecode();
2879}
2880
2881// SAFETY: TerminatedText owns bounded UTF-8 and its sole terminal NUL. The
2882// accessors lend exactly that live initialized string, whose allocation and
2883// contents stay unchanged for the borrow.
2884unsafe impl MetadataParts for MetadataFrame {
2885    fn metadata_text_for_send(&self) -> Option<MetadataText<'_>> {
2886        Some(self.data.text())
2887    }
2888
2889    fn metadata_timecode(&self) -> Timecode {
2890        self.timecode
2891    }
2892}
2893
2894metadata_source!(impl[] MetadataFrame);
2895
2896/// The state of optional per-frame metadata on decoded or compressed video/audio.
2897///
2898/// Unreadable metadata does not discard otherwise valid media. Its text is
2899/// withheld from [`VideoSource::metadata`] and [`AudioSource::metadata`], from
2900/// forwarding descriptors, and from owned copies. Owned copies and clones
2901/// preserve the status without retaining unreadable text. Video color queries
2902/// and default image encoding refuse withheld metadata, including on a copy.
2903/// Replacing metadata with valid text sets [`Self::Text`]; explicitly clearing
2904/// it sets [`Self::Absent`].
2905#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2906#[non_exhaustive]
2907pub enum FrameMetadataStatus {
2908    /// No per-frame metadata pointer was supplied.
2909    Absent,
2910    /// Valid UTF-8 text, including an explicitly empty string.
2911    Text,
2912    /// A terminated string contained bytes that are not UTF-8.
2913    NotUtf8,
2914    /// No NUL terminator appeared within the 4 MiB metadata cap.
2915    Unterminated,
2916}
2917
2918mod layout;
2919mod received;
2920pub(crate) use layout::*;
2921pub use layout::{AudioChannels, VideoPlane, VideoPlanes, VideoRows};
2922pub(crate) use received::*;
2923
2924mod metadata;
2925use metadata::CheckedMetadata;
2926pub(crate) use metadata::FrameMetadataState;
2927#[cfg(test)]
2928pub(crate) use metadata::{validate_frame_metadata, MetadataWithheld};
2929pub(crate) use metadata::{
2930    validate_metadata_layout, validate_sender_metadata, FrameMetadataRef, MetadataText,
2931    OwnedFrameMetadata, TerminatedText,
2932};
2933
2934// ============================================================================
2935// Frame layout validation helpers
2936// ============================================================================
2937
2938/// A frame together with the capability proof obtained for that frame.
2939/// Geometry stays with its storage; no other frame can consume its proof.
2940pub(crate) struct Sendable<F> {
2941    frame: F,
2942    _planar444: Option<sys::Planar444Video>,
2943}
2944
2945impl<F> std::ops::Deref for Sendable<F> {
2946    type Target = F;
2947    fn deref(&self) -> &F {
2948        &self.frame
2949    }
2950}
2951
2952impl<F: VideoParts> Sendable<F> {
2953    /// The send-capability check every uncompressed video send makes before
2954    /// reaching the SDK.
2955    fn checked(frame: F, ndi: &crate::Ndi) -> std::result::Result<Self, (Error, F)> {
2956        match frame
2957            .layout()
2958            .pixel_format()
2959            .require_sendable(|| ndi.table::<sys::Planar444Video>().copied())
2960        {
2961            Ok(planar444) => Ok(Self {
2962                frame,
2963                _planar444: planar444,
2964            }),
2965            Err(error) => Err((error, frame)),
2966        }
2967    }
2968
2969    pub(crate) fn new(frame: F, ndi: &crate::Ndi) -> std::result::Result<Self, Rejected<F>> {
2970        Self::checked(frame, ndi).map_err(|(error, frame)| Rejected::new(error, frame))
2971    }
2972
2973    pub(crate) fn frame(&self) -> &F {
2974        &self.frame
2975    }
2976    pub(crate) fn into_frame(self) -> F {
2977        self.frame
2978    }
2979
2980    /// Copies preserve the pixel format that the capability authorizes.
2981    pub(crate) fn copied(self, reusable: Option<VideoFrame>) -> Sendable<VideoFrame> {
2982        let frame = match reusable {
2983            Some(mut frame) => {
2984                self.frame.copy_into_owned(&mut frame);
2985                frame
2986            }
2987            None => self.frame.owned_copy(),
2988        };
2989        Sendable {
2990            frame,
2991            _planar444: self._planar444,
2992        }
2993    }
2994
2995    pub(crate) fn packed<'a>(
2996        &'a self,
2997        pixels: &'a mut Option<VideoStorage>,
2998    ) -> Sendable<PackedVideo<'a>> {
2999        Sendable {
3000            frame: crate::pixels::stage_video(&self.frame, pixels),
3001            _planar444: self._planar444,
3002        }
3003    }
3004
3005    #[cfg(test)]
3006    pub(crate) fn for_test(frame: F) -> Self {
3007        let planar444 = frame
3008            .layout()
3009            .pixel_format()
3010            .require_sendable(|| {
3011                sys::with_test_evidence("6.4.0.2", |evidence| {
3012                    sys::Planar444Video::check(evidence).copied()
3013                })
3014            })
3015            .unwrap();
3016        Self {
3017            frame,
3018            _planar444: planar444,
3019        }
3020    }
3021}
3022
3023impl<'a, F: VideoParts + ?Sized> Sendable<&'a F> {
3024    /// Borrowed gates return their typed refusal without allocating recovery storage.
3025    pub(crate) fn borrowed(frame: &'a F, ndi: &crate::Ndi) -> Result<Self> {
3026        Self::checked(frame, ndi).map_err(|(error, _)| error)
3027    }
3028}
3029
3030// ============================================================================
3031// Zero-copy borrowed receive frames
3032// ============================================================================
3033
3034/// A zero-copy video frame captured from a [`Receiver`](crate::Receiver).
3035///
3036/// Borrows its receiver and frees the SDK buffer when dropped. It can be moved
3037/// or shared with scoped worker threads (`Send + Sync`). Converting with
3038/// `to_owned` copies the active pixels into an owned frame. No pixels are
3039/// copied by capture itself. `data()` returns `None` when padding separates
3040/// active rows or planes; trailing padding after a single active row does not
3041/// prevent a contiguous view. Use `planes()` and each plane's rows for padded layouts.
3042/// See [`crate::FrameSyncVideoRef`] for clock-driven capture.
3043pub struct VideoFrameRef<'rx> {
3044    inner: ValidatedVideo<Guard<'rx, VideoKind>>,
3045}
3046
3047macro_rules! borrowed_video_accessors {
3048    ($name:ident, $strategy:ty) => {
3049        impl<'a> $name<'a> {
3050            pub(crate) fn new(guard: Guard<'a, $strategy>) -> Result<Self> {
3051                Ok(Self { inner: ValidatedVideo::validate(guard)? })
3052            }
3053
3054        }
3055
3056        // SAFETY: the private core retains the validated native loan, and this
3057        // concrete wrapper delegates every part to that same immutable core.
3058        unsafe impl VideoParts for $name<'_> {
3059            fn layout(&self) -> &ValidatedVideoLayout { VideoParts::layout(&self.inner) }
3060            fn header(&self) -> VideoHeader { VideoParts::header(&self.inner) }
3061            fn pixels(&self) -> *const u8 { VideoParts::pixels(&self.inner) }
3062            fn frame_metadata(&self) -> FrameMetadataRef<'_> { VideoParts::frame_metadata(&self.inner) }
3063            fn sdk_timestamp(&self) -> Option<ReceivedTimestamp> { VideoParts::sdk_timestamp(&self.inner) }
3064        }
3065        video_accessors! {
3066            impl['a] $name<'a>;
3067            debug(<$strategy as FrameFree>::REF_DEBUG_NAME, "active data (bytes)" = payload_len_bytes);
3068            timecode {}
3069            line_stride_bytes {
3070                /// It is the SDK's stride, which can include row padding, cached and
3071                /// validated when the frame was captured.
3072            }
3073            plane {}
3074            timestamp {
3075                /// It is `None` when the SDK does not know it.
3076            }
3077            data(self -> Option<&[u8]>) {
3078                /// Borrow all active pixels when contiguous, in SDK plane order.
3079                ///
3080                /// Returns `None` if padding separates active rows or planes. Use
3081                /// [`Self::planes`] / [`Self::plane`] for zero-copy padded access, or
3082                /// [`Self::to_owned`] for a tightly packed owned buffer. A single packed
3083                /// row can be borrowed even when its stride includes trailing padding.
3084            } {
3085        self.inner.active_data()
3086    }
3087            to_owned(self) {
3088                /// Copy this borrowed frame into an owned `VideoFrame`.
3089                ///
3090                /// Copies only active rows into one tightly packed pixel allocation and
3091                /// copies metadata separately. The owned stride can be smaller than the
3092                /// SDK stride. Preserves format, timing, aspect ratio, and scan type.
3093                /// Withheld metadata keeps its status without retaining its text.
3094                /// [`Self::copy_into`] makes the same copy into an existing frame,
3095                /// reusing its allocations.
3096                ///
3097                /// The copy cannot fail: capture validated everything it relies on, and
3098                /// the packed layout of a valid frame is valid.
3099            } {
3100        self.inner.owned_copy()
3101    }
3102            copy_into {
3103                /// Copy this borrowed frame into `destination`, reusing its allocations.
3104                ///
3105                /// `destination` ends up exactly as [`Self::to_owned`] would have
3106                /// returned it, whatever it held before: tightly packed active rows,
3107                /// format, dimensions, frame rate, aspect ratio, scan type, timecode,
3108                /// timestamp and metadata.
3109                ///
3110                /// Its pixel buffer is reused when its capacity holds the packed frame
3111                /// and its scan-dependent [room](PixelFormat::send_tail_room), and otherwise
3112                /// replaced by one allocation of exactly that size. Its
3113                /// metadata string is reused when its capacity holds the new text and
3114                /// its terminator; otherwise it grows once. With sufficient pixel and
3115                /// metadata capacity, subsequent copies allocate nothing, including
3116                /// when sources alternate between absent and present metadata. A
3117                /// copy without metadata retains the destination's text allocation.
3118                ///
3119                /// The copy makes no SDK call. It runs wherever this reference may be
3120                /// used: a receiver frame can be copied on a scoped worker thread, while a
3121                /// synchronizer frame stays on its capture thread. The destination is an
3122                /// ordinary owned frame either way.
3123            }
3124            sends_in_place {
3125                /// Whether synchronous sending reads this frame directly without a wrapper
3126                /// pixel copy. This cached-layout query allocates nothing and makes no SDK call.
3127                /// Captured padding is never assumed initialized; captures needing row padding
3128                /// or extra SDK tail room use reusable staging.
3129            }
3130            images("no_run", "\
3131 # use grafton_ndi::{Finder, FinderOptions, Ndi, Receiver, ReceiverOptions};
3132 # use std::time::Duration;
3133 # let ndi = Ndi::new()?;
3134 # let finder = Finder::new(&ndi, &FinderOptions::default())?;
3135 # finder.watch().wait_for_change(Duration::from_secs(1))?;
3136 # let Some(source) = finder.current_sources()?.into_iter().next() else { return Ok(()) };
3137 # let receiver = Receiver::new(&ndi, &ReceiverOptions::new(source))?;
3138 # let Some(frame) = receiver.capture_video_ref(Duration::from_secs(5))? else { return Ok(()) };") {
3139                /// It encodes directly from the borrowed SDK pixels, without first
3140                /// copying the frame into an owned [`VideoFrame`].
3141            }
3142        }
3143    };
3144}
3145borrowed_video_accessors!(VideoFrameRef, VideoKind);
3146borrowed_video_accessors!(FrameSyncVideoRef, FrameSyncVideoFree);
3147
3148/// A zero-copy audio frame captured from a [`Receiver`](crate::Receiver).
3149///
3150/// Borrows its receiver and frees the SDK buffer when dropped. It can be moved
3151/// or shared with scoped worker threads (`Send + Sync`). Converting with
3152/// `to_owned` copies the active samples into an owned frame. No samples are
3153/// copied by capture itself. For padded channels, `data()` returns `None`; use
3154/// `channel_data()` or `channels()` to read initialized samples. Every captured
3155/// audio frame has at least one channel and one sample per channel.
3156/// See [`crate::FrameSyncAudioRef`] for clock-driven capture.
3157pub struct AudioFrameRef<'rx> {
3158    inner: ValidatedAudio<Guard<'rx, AudioKind>>,
3159}
3160
3161macro_rules! borrowed_audio_accessors {
3162    (new $name:ident, $strategy:ty) => {
3163        impl<'a> $name<'a> {
3164            pub(crate) fn new(guard: Guard<'a, $strategy>) -> Result<Self> {
3165                Ok(Self { inner: ValidatedAudio::validate(guard)? })
3166            }
3167        }
3168        borrowed_audio_accessors!($name, $strategy);
3169    };
3170    ($name:ident, $strategy:ty) => {
3171        // SAFETY: all parts borrow the one validated descriptor retained by
3172        // this wrapper's private core, with no change to storage or freeing.
3173        unsafe impl AudioParts for $name<'_> {
3174            fn layout(&self) -> &ValidatedAudioLayout {
3175                AudioParts::layout(&self.inner)
3176            }
3177            fn audio_timecode(&self) -> Timecode {
3178                AudioParts::audio_timecode(&self.inner)
3179            }
3180            fn sdk_timestamp(&self) -> Option<ReceivedTimestamp> {
3181                AudioParts::sdk_timestamp(&self.inner)
3182            }
3183            fn samples(&self) -> *const f32 {
3184                AudioParts::samples(&self.inner)
3185            }
3186            fn frame_metadata(&self) -> FrameMetadataRef<'_> {
3187                AudioParts::frame_metadata(&self.inner)
3188            }
3189        }
3190        audio_accessors! {
3191                impl['a] $name<'a>;
3192                debug(<$strategy as FrameFree>::REF_DEBUG_NAME, "active data (samples)" = active_sample_count);
3193                timecode {
3194                    /// FrameSync output without a source timecode carries
3195                    /// [`Timecode::SYNTHESIZE`].
3196                }
3197                timestamp {
3198                    /// It is `None` when the SDK does not know it. FrameSync and
3199                    /// AV-sync audio also treat their zero marker as unknown; that
3200                    /// marker alone does not identify synthesized silence.
3201                }
3202                channel_stride_bytes {
3203                    /// It includes any padding between channels.
3204                }
3205                channel_data {}
3206                data(self -> Option<&[f32]>) {
3207                    /// Get a zero-copy slice when channels are tightly packed.
3208                    ///
3209                    /// Returns `None` for multi-channel buffers with padding between channels.
3210                    /// Use [`channel_data`](Self::channel_data) or [`channels`](Self::channels)
3211                    /// for those buffers.
3212                } {
3213            self.inner.contiguous_samples()
3214        }
3215                to_owned(self) {
3216                    /// Copy this borrowed frame into an owned `AudioFrame`.
3217                    ///
3218                    /// Copies channel samples into tightly packed planar storage and copies
3219                    /// metadata, allowing the frame to outlive the SDK buffer. Padding is omitted.
3220                    /// Allocates one sample buffer, and one metadata string when present.
3221                    /// Withheld metadata keeps its status without retaining its text.
3222                    /// [`Self::copy_into`] makes the same copy into an existing frame,
3223                    /// reusing its allocations.
3224                    ///
3225                    /// The copy cannot fail: capture validated everything it relies on.
3226                } {
3227            self.inner.owned_copy()
3228        }
3229                copy_into {
3230                    /// Copy this borrowed frame into `destination`, reusing its allocations.
3231                    ///
3232                    /// `destination` ends up exactly as [`Self::to_owned`] would have
3233                    /// returned it, whatever it held before: the channels' samples packed
3234                    /// back to back without inter-channel padding, format, sample rate,
3235                    /// channel and sample counts, timecode, timestamp and metadata.
3236                    ///
3237                    /// Its sample buffer is reused when its capacity holds the packed
3238                    /// samples, and otherwise replaced by one allocation of exactly that
3239                    /// size. Its metadata string is reused when its capacity holds the new
3240                    /// text and its terminator; otherwise it grows once. With sufficient
3241                    /// sample and metadata capacity, subsequent copies allocate nothing,
3242                    /// including when sources alternate between absent and present
3243                    /// metadata. A copy without text retains its allocation.
3244                    ///
3245                    /// The copy makes no SDK call. It runs wherever this reference may be
3246                    /// used: a receiver frame can be copied on a scoped worker thread, while a
3247                    /// synchronizer frame stays on its capture thread. The destination is an
3248                    /// ordinary owned frame either way.
3249                }
3250
3251            }
3252    };
3253}
3254borrowed_audio_accessors!(new AudioFrameRef, AudioKind);
3255borrowed_audio_accessors!(new FrameSyncAudioRef, FrameSyncAudioFree);
3256#[cfg(feature = "advanced")]
3257borrowed_audio_accessors!(AvSyncAudioRef, AvSyncAudioFree);
3258
3259#[cfg(all(feature = "advanced", any(test, ndi_has_advanced_av_sync)))]
3260impl<'a> AvSyncAudioRef<'a> {
3261    pub(crate) fn from_validated(frame: ValidatedAudio<Guard<'a, AvSyncAudioFree>>) -> Self {
3262        Self { inner: frame }
3263    }
3264}
3265
3266/// A zero-copy borrowed metadata frame.
3267///
3268/// This type wraps an RAII guard that owns the NDI frame buffer lifetime,
3269/// exposing a safe, zero-copy view of the metadata string. The frame is automatically
3270/// freed when dropped through its receiver or sender's matching metadata release.
3271///
3272/// **Key characteristics:**
3273/// - Zero allocations: References NDI SDK buffers directly
3274/// - Zero copies: No string duplication
3275/// - RAII lifetime: Exactly one free per frame, enforced at compile time
3276/// - `Send + Sync`: Captured metadata can be processed on a scoped worker thread
3277///
3278/// # Examples
3279///
3280/// ```no_run
3281/// # use grafton_ndi::{Ndi, ReceiverOptions, Receiver, Source, SourceAddress};
3282/// # use std::time::Duration;
3283/// # fn main() -> Result<(), grafton_ndi::Error> {
3284/// # let ndi = Ndi::new()?;
3285/// # let source = Source::new("Test").unwrap();
3286/// # let options = ReceiverOptions::new(source);
3287/// # let receiver = Receiver::new(&ndi, &options)?;
3288/// // Zero-copy capture
3289/// if let Some(frame) = receiver.capture_metadata_ref(Duration::from_millis(1000))? {
3290///     println!("Metadata: {}", frame.data());
3291///
3292///     // Frame is freed here when `frame` goes out of scope
3293/// }
3294/// # Ok(())
3295/// # }
3296/// ```
3297pub struct MetadataFrameRef<'rx> {
3298    /// The captured frame and its text, validated once when it was captured;
3299    /// `data()` and `as_bytes()` read the cached length. The empty null frame
3300    /// has no text.
3301    frame: MetadataLoan<'rx>,
3302}
3303
3304impl<'rx> MetadataFrameRef<'rx> {
3305    /// Create a borrowed metadata frame from an RAII guard.
3306    pub(crate) fn new(guard: RecvMetadataGuard<'rx>) -> Result<Self> {
3307        Ok(Self {
3308            frame: MetadataLoan::receiver(guard)?,
3309        })
3310    }
3311
3312    /// Validate a sender's bounded C-string result while retaining its capture gate.
3313    pub(crate) fn from_sender(
3314        guard: Guard<'rx, SenderMetadataFree>,
3315        lease: crate::sender::SenderMetadataLease<'rx>,
3316    ) -> Result<Self> {
3317        Ok(Self {
3318            frame: MetadataLoan::sender(guard, lease)?,
3319        })
3320    }
3321
3322    /// Get the timecode.
3323    pub fn timecode(&self) -> Timecode {
3324        Timecode::from_ticks(self.frame.descriptor().timecode)
3325    }
3326
3327    /// Get a zero-copy view of the metadata text.
3328    ///
3329    /// This returns a reference directly into the NDI SDK's buffer.
3330    /// No allocation or string copying is performed.
3331    pub fn data(&self) -> &str {
3332        self.frame.metadata().map_or("", MetadataText::as_str)
3333    }
3334
3335    /// Get a zero-copy view of the metadata UTF-8 payload bytes, excluding the
3336    /// SDK trailing NUL terminator.
3337    pub fn as_bytes(&self) -> &[u8] {
3338        self.data().as_bytes()
3339    }
3340
3341    /// Convert this borrowed frame to an owned `MetadataFrame`.
3342    ///
3343    /// This performs a string copy, allowing the frame to outlive
3344    /// the NDI buffer and be sent across threads.
3345    pub fn to_owned(&self) -> MetadataFrame {
3346        MetadataFrame::copied(self.frame.metadata(), self.timecode())
3347    }
3348
3349    /// Copy text and timecode into an existing owned frame. Reuses its text
3350    /// allocation when its capacity holds the text and trailing NUL.
3351    pub fn copy_into(&self, destination: &mut MetadataFrame) {
3352        copy_metadata_into(self, destination);
3353    }
3354}
3355
3356impl<'rx> fmt::Debug for MetadataFrameRef<'rx> {
3357    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3358        f.debug_struct("MetadataFrameRef")
3359            .field("data", &self.data())
3360            .field("data (bytes)", &self.as_bytes().len())
3361            .field("timecode", &self.timecode())
3362            .finish()
3363    }
3364}
3365
3366// SAFETY: The validated metadata frame and its Guard retain the SDK's bounded
3367// initialized terminated UTF-8 until matching release. The default descriptor
3368// borrows only that text, which remains unchanged for the reference's borrow.
3369unsafe impl MetadataParts for MetadataFrameRef<'_> {
3370    fn metadata_text_for_send(&self) -> Option<MetadataText<'_>> {
3371        self.frame.metadata()
3372    }
3373
3374    fn metadata_timecode(&self) -> Timecode {
3375        self.timecode()
3376    }
3377}
3378
3379metadata_source!(impl['a] MetadataFrameRef<'a>);
3380
3381#[cfg(test)]
3382#[path = "frames/accessor_tests.rs"]
3383mod accessor_tests;
3384
3385#[cfg(test)]
3386#[path = "frames/audio_validation_tests.rs"]
3387mod audio_validation_tests;
3388
3389#[cfg(test)]
3390mod tests {
3391    use super::*;
3392
3393    /// The layout part of [`validate_video_frame`].
3394    fn validate_video_layout(raw: &NDIlib_video_frame_v2_t) -> Result<ValidatedVideoLayout> {
3395        validate_video_frame(raw).map(|(layout, _)| layout)
3396    }
3397
3398    #[test]
3399    fn planar_444_layout_matches_independent_plane_math_and_bounds() {
3400        for (format, fourcc, bytes, count) in [
3401            (PixelFormat::Na48, b"NA48", 1usize, 3usize),
3402            (PixelFormat::Nb48, b"NB48", 1, 4),
3403            (PixelFormat::Na4g, b"NA4G", 2, 3),
3404            (PixelFormat::Nb4g, b"NB4G", 2, 4),
3405        ] {
3406            assert_eq!(FourCc::from(format).raw().to_le_bytes(), *fourcc);
3407            for width in [2u32, 4, 1920, 3840, 16_384] {
3408                for height in [1u32, 3, 1080, 2160, 16_384] {
3409                    for padding in [0, 2, 64] {
3410                        let active = width as usize * bytes;
3411                        let stride = active + padding;
3412                        let expected = stride as u128 * height as u128 * count as u128;
3413                        let layout = ValidatedVideoLayout::new_uncompressed(
3414                            format,
3415                            width,
3416                            height,
3417                            Some(stride),
3418                        );
3419                        assert_eq!(layout.is_ok(), expected <= MAX_VIDEO_BYTES as u128);
3420                        if let Ok(layout) = layout {
3421                            assert_eq!(layout.plane_count(), count);
3422                            assert_eq!(layout.data_len_bytes() as u128, expected);
3423                            assert_eq!(
3424                                layout.payload_len_bytes(),
3425                                active * height as usize * count
3426                            );
3427                            for (i, plane) in layout.planes().iter().enumerate() {
3428                                assert_eq!(plane.offset(), i * stride * height as usize);
3429                                assert_eq!(plane.row_stride(), stride);
3430                                assert_eq!(plane.active_row_bytes(), active);
3431                                assert_eq!(plane.row_count(), height as usize);
3432                            }
3433                        }
3434                    }
3435                }
3436            }
3437            assert!(ValidatedVideoLayout::new_uncompressed(format, 3, 3, None).is_err());
3438            assert!(ValidatedVideoLayout::new_uncompressed(format, 4, 3, Some(1)).is_err());
3439            assert!(calculate_buffer_len_checked(format, usize::MAX, 2).is_err());
3440            // Building needs no runtime; sending checks the runtime.
3441            let frame = VideoFrame::builder()
3442                .resolution(4, 3)
3443                .pixel_format(format)
3444                .build()
3445                .unwrap();
3446            assert_eq!(frame.planes().len(), count);
3447            assert!(frame.planes().all(|plane| plane.row_count() == 3));
3448        }
3449    }
3450
3451    /// The packed layout of every valid layout, padded or not, is the one
3452    /// validation gives the same format and dimensions without padding, so
3453    /// an owned copy, which packs, cannot meet a layout validation refuses.
3454    #[test]
3455    fn every_valid_layout_packs_into_the_validated_packed_layout() {
3456        for format in PixelFormat::ALL {
3457            let bytes = format.info().bytes_per_pixel() as usize;
3458            let mut packed_layouts = 0;
3459            for (width, height) in [
3460                (2u32, 1u32),
3461                (2, 2),
3462                (642, 4),
3463                (1920, 1080),
3464                (3840, 2160),
3465                (16_384, 8_192),
3466            ] {
3467                for padding in [0, 2, 64, 4096] {
3468                    let stride = width as usize * bytes + padding;
3469                    let Ok(layout) =
3470                        ValidatedVideoLayout::new_uncompressed(format, width, height, Some(stride))
3471                    else {
3472                        continue;
3473                    };
3474                    let expected =
3475                        ValidatedVideoLayout::new_uncompressed(format, width, height, None)
3476                            .unwrap();
3477                    let packed = layout.packed();
3478                    assert_eq!(format!("{:?}", packed.as_layout()), format!("{expected:?}"));
3479                    assert_eq!(
3480                        packed.as_layout().data_len_bytes(),
3481                        layout.payload_len_bytes()
3482                    );
3483                    packed_layouts += 1;
3484                }
3485            }
3486            assert!(packed_layouts > 0, "{format:?}");
3487        }
3488    }
3489
3490    /// A frame's `data` and each plane's follow one contiguity rule: active
3491    /// rows are one span when no padding separates the rows of a plane or
3492    /// the planes, and a single row may have padding after it. Audio is one
3493    /// span with one channel or with channels back to back.
3494    #[test]
3495    fn frames_planes_and_audio_share_one_contiguity_rule() {
3496        let rows_adjacent = |plane: &VideoPlaneLayout| {
3497            plane.row_count() == 1 || plane.row_stride() == plane.active_row_bytes()
3498        };
3499        let storage = vec![7u8; 4096];
3500        for format in PixelFormat::ALL {
3501            let bytes = format.info().bytes_per_pixel() as usize;
3502            for (height, padding) in [(1u32, 0usize), (1, 8), (2, 0), (2, 8), (4, 2), (4, 64)] {
3503                let Ok(layout) = ValidatedVideoLayout::new_uncompressed(
3504                    format,
3505                    4,
3506                    height,
3507                    Some(4 * bytes + padding),
3508                ) else {
3509                    continue;
3510                };
3511                let planes = layout.planes();
3512                let (last, before) = planes.split_last().unwrap();
3513                let contiguous = before
3514                    .iter()
3515                    .all(|plane| plane.row_stride() == plane.active_row_bytes())
3516                    && rows_adjacent(last);
3517                // SAFETY: the storage is initialized and covers every layout
3518                // here, and nothing writes it while the views live.
3519                let data = unsafe { layout.view_data(storage.as_ptr()) };
3520                assert_eq!(
3521                    data.map(<[u8]>::len),
3522                    contiguous.then_some(layout.payload_len_bytes()),
3523                    "{format:?} height {height} padding {padding}"
3524                );
3525                for (index, plane) in planes.iter().enumerate() {
3526                    // SAFETY: as above.
3527                    let view = unsafe { layout.view_plane(storage.as_ptr(), index) }.unwrap();
3528                    assert_eq!(
3529                        view.data().map(<[u8]>::len),
3530                        rows_adjacent(plane)
3531                            .then_some(plane.row_count() * plane.active_row_bytes())
3532                    );
3533                }
3534            }
3535        }
3536
3537        let samples = [0.5f32; 24];
3538        for (channels, stride, contiguous) in [(1, 8, true), (3, 5, true), (3, 8, false)] {
3539            let raw = NDIlib_audio_frame_v3_t {
3540                sample_rate: 48_000,
3541                no_channels: channels,
3542                no_samples: 5,
3543                FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
3544                p_data: samples.as_ptr().cast_mut().cast(),
3545                __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
3546                    channel_stride_in_bytes: stride * 4,
3547                },
3548                timecode: 0,
3549                timestamp: 0,
3550                p_metadata: ptr::null(),
3551            };
3552            let layout = validate_audio_layout(&raw).unwrap();
3553            // SAFETY: the samples are initialized, aligned and cover the
3554            // layout, and nothing writes them while the view lives.
3555            let view = unsafe { layout.view_samples(samples.as_ptr()) };
3556            assert_eq!(
3557                view.map(<[f32]>::len),
3558                contiguous.then_some(layout.sample_count())
3559            );
3560        }
3561    }
3562
3563    #[test]
3564    fn planar_444_rows_copy_without_padding_through_every_owned_path() {
3565        use crate::capture::FrameSyncVideoFree;
3566        use std::mem::MaybeUninit;
3567        for (format, bytes, count) in [
3568            (PixelFormat::Na48, 1usize, 3usize),
3569            (PixelFormat::Nb48, 1, 4),
3570            (PixelFormat::Na4g, 2, 3),
3571            (PixelFormat::Nb4g, 2, 4),
3572        ] {
3573            let active = 4 * bytes;
3574            let stride = active + 4;
3575            let mut storage = vec![MaybeUninit::<u8>::uninit(); stride * 3 * count];
3576            let mut expected = Vec::new();
3577            for plane in 0..count {
3578                for row in 0..3 {
3579                    for column in 0..active {
3580                        let value = (plane * 40 + row * 10 + column) as u8;
3581                        storage[plane * stride * 3 + row * stride + column].write(value);
3582                        expected.push(value);
3583                    }
3584                }
3585            }
3586            let raw = NDIlib_video_frame_v2_t {
3587                xres: 4,
3588                yres: 3,
3589                FourCC: FourCc::from(format).raw(),
3590                frame_rate_N: 60,
3591                frame_rate_D: 1,
3592                frame_format_type: ScanType::Progressive.to_sdk(),
3593                p_data: storage.as_mut_ptr().cast(),
3594                __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
3595                    line_stride_in_bytes: stride as i32,
3596                },
3597                ..Default::default()
3598            };
3599            // Only initialized active bytes may be read; padding stays uninitialized.
3600            let frame = unsafe {
3601                FrameSyncVideoRef::new(Guard::<FrameSyncVideoFree>::with_test_free(
3602                    ptr::null_mut(),
3603                    raw,
3604                    |_, _| {},
3605                ))
3606            }
3607            .unwrap();
3608            assert_eq!(frame.planes().len(), count);
3609            assert_eq!(
3610                frame
3611                    .planes()
3612                    .flat_map(|p| p.rows())
3613                    .flatten()
3614                    .copied()
3615                    .collect::<Vec<_>>(),
3616                expected
3617            );
3618            assert!(frame.plane(count).is_none());
3619            let captured = frame.to_owned();
3620            let copied = unsafe { VideoFrame::from_raw(&raw) }.unwrap();
3621            let built = VideoFrame::builder()
3622                .resolution(4, 3)
3623                .pixel_format(format)
3624                .data(expected.clone())
3625                .build()
3626                .unwrap();
3627            for owned in [captured, copied, built] {
3628                assert_eq!(owned.data(), expected);
3629                // The owned frame's planes are the same views, without padding.
3630                assert_eq!(
3631                    owned
3632                        .planes()
3633                        .flat_map(|p| p.rows())
3634                        .flatten()
3635                        .copied()
3636                        .collect::<Vec<_>>(),
3637                    expected
3638                );
3639                let recopy = owned.clone();
3640                assert_eq!(recopy.data(), expected);
3641            }
3642        }
3643    }
3644
3645    #[test]
3646    fn planar_444_formats_are_sendable_only_where_the_runtime_supports_them() {
3647        let Some(ndi) = crate::test_support::ndi() else {
3648            return;
3649        };
3650        let supported = ndi
3651            .require_feature(crate::capabilities::RuntimeFeature::Planar444Video)
3652            .is_ok();
3653        for format in PixelFormat::ALL {
3654            let planar_444 = matches!(
3655                format,
3656                PixelFormat::Na48 | PixelFormat::Nb48 | PixelFormat::Na4g | PixelFormat::Nb4g
3657            );
3658            let result = format.require_sendable(|| ndi.table::<sys::Planar444Video>().copied());
3659            if planar_444 && !supported {
3660                assert!(
3661                    matches!(
3662                        result,
3663                        Err(Error::UnsupportedCapability {
3664                            capability: crate::Capability::Runtime(
3665                                crate::capabilities::RuntimeFeature::Planar444Video
3666                            ),
3667                            ..
3668                        })
3669                    ),
3670                    "{format:?}: {result:?}"
3671                );
3672            } else {
3673                assert!(result.is_ok(), "{format:?}: {result:?}");
3674            }
3675        }
3676    }
3677
3678    /// Interleaved input is transposed into exact per-channel planes.
3679    #[test]
3680    fn interleaved_audio_builds_exact_planar_output() {
3681        // Sample counts that are not multiples of the channel count or each other.
3682        for (channels, samples) in [
3683            (1, 1),
3684            (1, 7),
3685            (2, 1),
3686            (2, 5),
3687            (2, 13),
3688            (3, 7),
3689            (3, 1),
3690            (5, 11),
3691            (8, 3),
3692        ] {
3693            // Value encodes (channel, sample) so any misplacement is visible.
3694            let value = |ch: usize, s: usize| (ch * 1000 + s) as f32;
3695            let mut interleaved = Vec::with_capacity(channels * samples);
3696            for s in 0..samples {
3697                for ch in 0..channels {
3698                    interleaved.push(value(ch, s));
3699                }
3700            }
3701            let input = crate::audio_conversion::InterleavedAudioF32::new(
3702                48_000,
3703                channels as u32,
3704                &interleaved,
3705            )
3706            .unwrap()
3707            .with_timecode(Timecode::from_ticks(123));
3708            let (frame, allocations) =
3709                crate::test_alloc::allocation_count(|| AudioFrame::from_interleaved(&input));
3710            assert_eq!(allocations, 1);
3711            assert_eq!(frame.channel_stride_bytes(), samples * size_of::<f32>());
3712            assert_eq!(frame.timecode(), input.timecode());
3713            assert_eq!(frame.timestamp(), None);
3714            assert_eq!(frame.metadata(), None);
3715            let expected: Vec<f32> = (0..channels)
3716                .flat_map(|ch| (0..samples).map(move |s| value(ch, s)))
3717                .collect();
3718            assert_eq!(frame.data(), expected, "{channels}ch x {samples}");
3719            // The channel iterator and per-channel access agree with the data.
3720            assert_eq!(frame.channels().len(), channels);
3721            for (ch, samples) in frame.channels().enumerate() {
3722                assert_eq!(Some(samples), frame.channel_data(ch));
3723                assert_eq!(samples, &expected[ch * samples.len()..][..samples.len()]);
3724            }
3725        }
3726        // The input validates divisibility before a conversion is possible.
3727        assert!(crate::audio_conversion::InterleavedAudioF32::new(48_000, 3, &[0.0; 11]).is_err());
3728    }
3729
3730    /// Every audio path reports a bad sample rate with the same message.
3731    #[test]
3732    fn audio_descriptors_use_the_validated_format() {
3733        let frame = AudioFrame::builder()
3734            .num_channels(2)
3735            .num_samples(3)
3736            .build()
3737            .unwrap();
3738        assert_eq!(
3739            frame.audio_descriptor().FourCC,
3740            FourCc::from(frame.format()).raw()
3741        );
3742        let samples = [0.0; 6];
3743        let frame = BorrowedAudioFrame::builder(&samples, 48_000, 2, 3)
3744            .build()
3745            .unwrap();
3746        assert_eq!(
3747            frame.audio_descriptor().FourCC,
3748            FourCc::from(frame.format()).raw()
3749        );
3750    }
3751
3752    #[test]
3753    fn audio_sample_rate_check_is_shared_with_one_message() {
3754        let message = |result: Result<()>| match result {
3755            Err(Error::InvalidFrame(msg)) => msg,
3756            other => panic!("expected InvalidFrame, got {other:?}"),
3757        };
3758        for rate in [0u32, 1 << 31, u32::MAX] {
3759            let expected = crate::FrameDefect::Layout(crate::LayoutDefect::AudioRate(rate.into()));
3760            assert_eq!(
3761                message(
3762                    validate_audio_sample_rate(rate.into())
3763                        .map(|_| ())
3764                        .map_err(Into::into)
3765                ),
3766                expected
3767            );
3768            assert_eq!(
3769                message(validate_outbound_audio_layout(rate, 2, 8, AudioFormat::Fltp).map(|_| ())),
3770                expected
3771            );
3772            assert_eq!(
3773                match crate::framesync::FrameSyncAudioRequest::capture_at(rate, 2, 8).unwrap_err() {
3774                    Error::InvalidInput(crate::InputDefect::Layout(cause)) => cause,
3775                    other => panic!("expected InvalidInput(Layout), got {other:?}"),
3776                },
3777                crate::LayoutDefect::AudioRate(rate.into())
3778            );
3779            assert_eq!(
3780                message(
3781                    crate::audio_conversion::InterleavedAudioF32::new(rate, 2, &[0.0; 2])
3782                        .map(|_| ())
3783                ),
3784                expected
3785            );
3786        }
3787        // Rates the SDK reports go through the same check.
3788        for rate in [0, -48_000, i32::MIN] {
3789            let mut sample = 0.0f32;
3790            let raw = NDIlib_audio_frame_v3_t {
3791                sample_rate: rate,
3792                no_channels: 1,
3793                no_samples: 1,
3794                FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
3795                p_data: (&mut sample as *mut f32).cast(),
3796                __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
3797                    channel_stride_in_bytes: 4,
3798                },
3799                ..Default::default()
3800            };
3801            assert_eq!(
3802                message(validate_audio_layout(&raw).map(|_| ())),
3803                crate::FrameDefect::Layout(crate::LayoutDefect::AudioRate(rate.into()))
3804            );
3805        }
3806        assert_eq!(validate_audio_sample_rate(1).unwrap().get(), 1);
3807        assert_eq!(
3808            validate_audio_sample_rate(i32::MAX.into()).unwrap().get(),
3809            i32::MAX.unsigned_abs()
3810        );
3811    }
3812
3813    /// The extent helper gives packed and strided audio the same sample count
3814    /// and size cap.
3815    #[test]
3816    fn audio_extent_is_shared_by_packed_and_strided_layouts() {
3817        let quantity = |value: usize| SdkQuantity::new(value as i64).unwrap();
3818        let extent = |channels, samples, stride| {
3819            checked_audio_extent(quantity(channels), quantity(samples), stride)
3820        };
3821        let packed =
3822            ValidatedAudioLayout::new_uncompressed(AudioFormat::Fltp, 48_000, 3, 5, None).unwrap();
3823        assert_eq!(packed.sample_count(), 15);
3824        assert_eq!(extent(3, 5, 5).unwrap(), 15);
3825        // Padding between channels counts, trailing padding does not.
3826        assert_eq!(extent(3, 5, 8).unwrap(), 2 * 8 + 5);
3827        let limit = MAX_AUDIO_BYTES / 4;
3828        assert_eq!(extent(1, limit, limit as u64).unwrap(), limit);
3829        assert!(extent(1, limit + 1, (limit + 1) as u64).is_err());
3830        assert!(extent(2, limit, limit as u64).is_err());
3831        assert!(extent(2, 1, limit as u64).is_err());
3832        assert!(extent(2, 1, usize::MAX as u64).is_err());
3833    }
3834
3835    #[test]
3836    fn borrowed_audio_stride_matches_sdk_layout_without_reading_padding() {
3837        let samples = [0.0, 1.0, 2.0, f32::NAN, 3.0, 4.0, 5.0];
3838        let (frame, allocations) = crate::test_alloc::allocation_count(|| {
3839            BorrowedAudioFrame::builder(&samples, 48_000, 2, 3)
3840                .channel_stride_bytes(16)
3841                .build()
3842                .unwrap()
3843        });
3844        assert_eq!(allocations, 0);
3845        let raw = frame.audio_descriptor();
3846        assert_eq!(*frame.layout(), validate_audio_layout(&raw).unwrap());
3847        assert_eq!(frame.channel_data(0), Some(&samples[..3]));
3848        assert_eq!(frame.channel_data(1), Some(&samples[4..]));
3849        assert_eq!(frame.layout().sample_count(), samples.len());
3850        // A received zero stride is invalid; only caller input's None means
3851        // packed. Sharing scalar checks must not change this distinction.
3852        let zero_stride = NDIlib_audio_frame_v3_t {
3853            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
3854                channel_stride_in_bytes: 0,
3855            },
3856            ..raw
3857        };
3858        assert!(validate_audio_layout(&zero_stride).is_err());
3859    }
3860
3861    #[test]
3862    fn validated_audio_channel_ranges_match_a_wide_oracle_near_the_storage_limit() {
3863        let limit = MAX_AUDIO_BYTES / size_of::<f32>();
3864        let mut checked = 0;
3865        for channels in [1u32, 2, 3, 4, 16, 64] {
3866            let edge = limit / channels as usize;
3867            for samples in [
3868                1,
3869                2,
3870                edge.saturating_sub(1),
3871                edge,
3872                edge + 1,
3873                limit,
3874                limit + 1,
3875            ] {
3876                let minimum = samples * size_of::<f32>();
3877                for stride in [
3878                    4,
3879                    minimum.saturating_sub(4),
3880                    minimum,
3881                    minimum + 4,
3882                    (limit / 2) * 4,
3883                    limit * 4,
3884                    usize::MAX - 3,
3885                ] {
3886                    let Ok(layout) = ValidatedAudioLayout::new_uncompressed(
3887                        AudioFormat::Fltp,
3888                        48_000,
3889                        channels,
3890                        samples as u32,
3891                        Some(stride),
3892                    ) else {
3893                        continue;
3894                    };
3895                    for layout in [layout, *layout.packed().as_layout()] {
3896                        checked += 1;
3897                        for channel in 0..channels as usize {
3898                            let start = channel as i128 * layout.channel_stride_samples() as i128;
3899                            let end = start + samples as i128;
3900                            let actual = layout.channel_range(channel).unwrap();
3901                            assert_eq!((actual.start as i128, actual.end as i128), (start, end));
3902                            assert!(end <= layout.sample_count() as i128);
3903                        }
3904                        assert_eq!(layout.channel_range(channels as usize), None);
3905                        assert_eq!(layout.channel_range(usize::MAX), None);
3906                    }
3907                }
3908            }
3909        }
3910        assert!(checked > 0);
3911    }
3912
3913    #[test]
3914    fn packed_audio_layout_matches_wide_oracle_and_owned_validation() {
3915        fn check(channels: u32, samples: u32) {
3916            let bytes = i128::from(channels) * i128::from(samples) * 4;
3917            let stride = i128::from(samples) * 4;
3918            let valid = channels > 0
3919                && samples > 0
3920                && stride <= i128::from(i32::MAX)
3921                && bytes <= MAX_AUDIO_BYTES as i128;
3922            let packed = ValidatedAudioLayout::new_uncompressed(
3923                AudioFormat::Fltp,
3924                48_000,
3925                channels,
3926                samples,
3927                None,
3928            );
3929            let owned =
3930                validate_outbound_audio_layout(48_000, channels, samples, AudioFormat::Fltp);
3931            let request = crate::FrameSyncAudioRequest::capture_at(48_000, channels, samples);
3932            assert_eq!(
3933                packed.is_ok(),
3934                valid,
3935                "channels={channels}, samples={samples}"
3936            );
3937            assert_eq!(owned.is_ok(), valid);
3938            assert_eq!(request.is_ok(), valid);
3939            if let (Ok(packed), Ok(owned)) = (packed, owned) {
3940                let owned = owned.as_layout();
3941                assert_eq!(packed.sample_count() as i128 * 4, bytes);
3942                assert_eq!(owned.channel_stride_bytes() as i128, stride);
3943                assert_eq!(packed.no_channels(), owned.no_channels());
3944                assert_eq!(packed.no_samples(), owned.no_samples());
3945                assert_eq!(packed.sample_count(), owned.sample_count());
3946            }
3947        }
3948        let values = [
3949            0,
3950            1,
3951            2,
3952            3,
3953            16,
3954            1024,
3955            8_388_608,
3956            8_388_609,
3957            16_777_216,
3958            16_777_217,
3959            i32::MAX.unsigned_abs() / 4,
3960            i32::MAX.unsigned_abs() / 4 + 1,
3961            1_073_741_825,
3962            i32::MAX.unsigned_abs(),
3963            1 << 31,
3964            u32::MAX,
3965        ];
3966        for channels in values {
3967            for samples in values {
3968                check(channels, samples);
3969            }
3970        }
3971        // Deterministic property coverage around the payload boundary, plus the
3972        // full unsigned input range. No sample buffers are allocated.
3973        let mut seed = 102u64;
3974        for _ in 0..4096 {
3975            seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1);
3976            let channels = (seed >> 32) as u32;
3977            check(channels, seed as u32);
3978            let channels = ((seed >> 32) % 4096 + 1) as u32;
3979            let boundary = (MAX_AUDIO_BYTES / 4) as u32 / channels;
3980            for samples in [boundary - 1, boundary, boundary + 1] {
3981                check(channels, samples);
3982            }
3983        }
3984        // Packed strides on either side of the signed boundary exceed the byte cap.
3985        let at_stride_limit = ValidatedAudioLayout::new_uncompressed(
3986            AudioFormat::Fltp,
3987            48_000,
3988            1,
3989            i32::MAX.unsigned_abs() / 4,
3990            None,
3991        );
3992        assert!(at_stride_limit
3993            .err()
3994            .unwrap()
3995            .to_string()
3996            .contains("maximum size"));
3997        let over_stride_limit = ValidatedAudioLayout::new_uncompressed(
3998            AudioFormat::Fltp,
3999            48_000,
4000            1,
4001            i32::MAX.unsigned_abs() / 4 + 1,
4002            None,
4003        );
4004        assert!(matches!(
4005            over_stride_limit,
4006            Err(Error::InvalidFrame(crate::FrameDefect::Layout(crate::LayoutDefect::AudioBytes(bytes))))
4007                if bytes.get() == (i32::MAX as u64 / 4 + 1) * 4
4008        ));
4009    }
4010
4011    #[test]
4012    fn video_padding_all_formats_expose_and_copy_only_initialized_rows() {
4013        use crate::capture::{FrameSyncVideoFree, Guard};
4014        // Independently specified active plane dimensions for 4x4 images.
4015        let cases: &[(PixelFormat, &[(usize, usize)])] = &[
4016            (PixelFormat::Bgra, &[(16, 4)]),
4017            (PixelFormat::Bgrx, &[(16, 4)]),
4018            (PixelFormat::Rgba, &[(16, 4)]),
4019            (PixelFormat::Rgbx, &[(16, 4)]),
4020            (PixelFormat::Uyvy, &[(8, 4)]),
4021            (PixelFormat::Uyva, &[(8, 4), (4, 4)]),
4022            (PixelFormat::P216, &[(8, 4), (8, 4)]),
4023            (PixelFormat::Pa16, &[(8, 4), (8, 4), (8, 4)]),
4024            (PixelFormat::Yv12, &[(4, 4), (2, 2), (2, 2)]),
4025            (PixelFormat::I420, &[(4, 4), (2, 2), (2, 2)]),
4026            (PixelFormat::Nv12, &[(4, 4), (4, 2)]),
4027        ];
4028        // One padded layout per format keeps interpretation bounded. The
4029        // native and Memcheck runs retain the complete layout matrix.
4030        let paddings: &[usize] = if cfg!(miri) { &[4] } else { &[0, 4, 8] };
4031        for &(format, dimensions) in cases {
4032            for &padding in paddings {
4033                let stride = dimensions[0].0 + padding;
4034                let mut storage = Box::<[u8]>::new_uninit_slice(512);
4035                let mut expected = Vec::new();
4036                let mut offsets = Vec::new();
4037                let mut offset = 0;
4038                for (i, &(active, rows)) in dimensions.iter().enumerate() {
4039                    let plane_stride = stride * active / dimensions[0].0;
4040                    offsets.push(offset);
4041                    for row in 0..rows {
4042                        for byte in 0..active {
4043                            let value = (i * 71 + row * 17 + byte) as u8;
4044                            storage[offset + row * plane_stride + byte].write(value);
4045                            expected.push(value);
4046                        }
4047                    }
4048                    offset += plane_stride * rows;
4049                }
4050                let metadata = CString::new("<video-padding/>").unwrap();
4051                let raw = NDIlib_video_frame_v2_t {
4052                    xres: 4,
4053                    yres: 4,
4054                    FourCC: FourCc::from(format).raw(),
4055                    frame_rate_N: 30000,
4056                    frame_rate_D: 1001,
4057                    picture_aspect_ratio: 1.25,
4058                    frame_format_type: ScanType::Interlaced.to_sdk(),
4059                    timecode: 12345,
4060                    timestamp: 67890,
4061                    p_data: storage.as_mut_ptr().cast(),
4062                    p_metadata: metadata.as_ptr(),
4063                    __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
4064                        line_stride_in_bytes: stride as i32,
4065                    },
4066                };
4067                // Null FrameSync guards skip SDK calls; storage and metadata
4068                // live until both independent guards and their views are gone.
4069                let make = || unsafe {
4070                    FrameSyncVideoRef::new(Guard::<FrameSyncVideoFree>::with_test_free(
4071                        ptr::null_mut(),
4072                        raw,
4073                        |_, _| {},
4074                    ))
4075                    .unwrap()
4076                };
4077                let (frame, allocations) = crate::test_alloc::allocation_count(make);
4078                assert_eq!(allocations, 0);
4079                let second = make();
4080                let ((), allocations) = crate::test_alloc::allocation_count(|| {
4081                    assert_eq!(frame.planes().len(), dimensions.len());
4082                    assert!(frame.plane(dimensions.len()).is_none());
4083                    assert_eq!(frame.data().is_some(), padding == 0);
4084                    if let Some(data) = frame.data() {
4085                        assert_eq!(data, expected);
4086                    }
4087                    let mut position = 0;
4088                    for (i, plane) in frame.planes().enumerate() {
4089                        let (active, rows) = dimensions[i];
4090                        assert_eq!(plane.row_count(), rows);
4091                        assert_eq!(plane.active_row_bytes(), active);
4092                        assert_eq!(plane.row_stride_bytes(), stride * active / dimensions[0].0);
4093                        assert_eq!(plane.data().is_some(), padding == 0);
4094                        assert!(plane.row(rows).is_none());
4095                        let mut iterator = plane.rows();
4096                        assert_eq!(iterator.len(), rows);
4097                        assert_eq!(iterator.next_back(), plane.row(rows - 1));
4098                        assert_eq!(iterator.len(), rows - 1);
4099                        for (row_index, row) in plane.rows().enumerate() {
4100                            assert_eq!(row.as_ptr(), unsafe {
4101                                storage
4102                                    .as_ptr()
4103                                    .cast::<u8>()
4104                                    .add(offsets[i] + row_index * plane.row_stride_bytes())
4105                            });
4106                            assert_eq!(row, &expected[position..position + active]);
4107                            position += active;
4108                        }
4109                    }
4110                    assert_eq!(position, expected.len());
4111                });
4112                assert_eq!(allocations, 0);
4113                // Preconstructed views and independent iterator clones can be
4114                // moved/shared while this thread retains the FrameSync guard.
4115                let planes = frame.planes();
4116                let moved_planes = planes.clone();
4117                let expected_sum: u64 = expected.iter().map(|&b| u64::from(b)).sum();
4118                std::thread::scope(|scope| {
4119                    let shared = &planes;
4120                    let reader = scope.spawn(move || {
4121                        shared
4122                            .clone()
4123                            .flat_map(|p| p.rows())
4124                            .flatten()
4125                            .map(|&b| u64::from(b))
4126                            .sum::<u64>()
4127                    });
4128                    let moved = scope.spawn(move || {
4129                        moved_planes
4130                            .flat_map(|p| p.rows().rev())
4131                            .flatten()
4132                            .map(|&b| u64::from(b))
4133                            .sum::<u64>()
4134                    });
4135                    assert_eq!(reader.join().unwrap(), expected_sum);
4136                    assert_eq!(moved.join().unwrap(), expected_sum);
4137                });
4138                for plane in frame.planes() {
4139                    let rows = plane.rows();
4140                    let clone = rows.clone();
4141                    let serial = rows.clone().flatten().copied().collect::<Vec<_>>();
4142                    std::thread::scope(|scope| {
4143                        let shared = &plane;
4144                        let reader = scope
4145                            .spawn(move || shared.rows().flatten().copied().collect::<Vec<_>>());
4146                        let moved =
4147                            scope.spawn(move || rows.flatten().copied().collect::<Vec<_>>());
4148                        let reversed = scope.spawn(move || {
4149                            clone.rev().rev().flatten().copied().collect::<Vec<_>>()
4150                        });
4151                        assert_eq!(reader.join().unwrap(), serial);
4152                        assert_eq!(moved.join().unwrap(), serial);
4153                        assert_eq!(reversed.join().unwrap(), serial);
4154                    });
4155                }
4156                assert_eq!(VideoParts::layout(&frame).data_len_bytes(), offset);
4157                assert_eq!(
4158                    VideoParts::layout(&frame).payload_len_bytes(),
4159                    expected.len()
4160                );
4161                let owned = frame.to_owned();
4162                let raw_owned = unsafe { VideoFrame::from_raw(&raw) }.unwrap();
4163                assert_eq!(owned.data(), expected);
4164                assert_eq!(raw_owned.data(), expected);
4165                assert_eq!(owned.pixel_format(), format);
4166                assert_eq!(owned.line_stride_bytes(), dimensions[0].0);
4167                assert_eq!(owned.metadata(), Some("<video-padding/>"));
4168                assert_eq!(owned.frame_rate(), FrameRate::new(30000, 1001).unwrap());
4169                assert_eq!(owned.picture_aspect_ratio().get(), 1.25);
4170                assert_eq!(owned.scan_type(), ScanType::Interlaced);
4171                assert_eq!(
4172                    (owned.timecode(), owned.timestamp()),
4173                    (
4174                        Timecode::from_ticks(12345),
4175                        ReceivedTimestamp::from_sdk(67890)
4176                    )
4177                );
4178                drop(frame);
4179                assert_eq!(
4180                    second.plane(0).unwrap().row(0).unwrap(),
4181                    &expected[..dimensions[0].0]
4182                );
4183                // No metadata: exactly one allocation for active owned pixels.
4184                let raw = NDIlib_video_frame_v2_t {
4185                    p_metadata: ptr::null(),
4186                    ..raw
4187                };
4188                let (copied, allocations) = crate::test_alloc::allocation_count(|| {
4189                    unsafe { VideoFrame::from_raw(&raw) }.unwrap()
4190                });
4191                assert_eq!(allocations, 1);
4192                assert_eq!(copied.data(), expected);
4193                assert!(VideoFrame::builder()
4194                    .resolution(4, 4)
4195                    .pixel_format(format)
4196                    .data(vec![0; expected.len() - 1])
4197                    .build()
4198                    .is_err());
4199                assert!(crate::BorrowedVideoFrame::builder(
4200                    &vec![0; expected.len() - 1],
4201                    4,
4202                    4,
4203                    format,
4204                )
4205                .build()
4206                .is_err());
4207                // Copied-send conversion must use the same normalization.
4208                // This send-side fixture initializes padding too, because its
4209                // constructor takes an already initialized application slice.
4210                let mut initialized = vec![99; offset];
4211                let mut position = 0;
4212                for (i, &(active, rows)) in dimensions.iter().enumerate() {
4213                    let plane_stride = stride * active / dimensions[0].0;
4214                    for row in 0..rows {
4215                        let start = offsets[i] + row * plane_stride;
4216                        initialized[start..start + active]
4217                            .copy_from_slice(&expected[position..position + active]);
4218                        position += active;
4219                    }
4220                }
4221                let send = crate::BorrowedVideoFrame::builder(&initialized, 4, 4, format)
4222                    .frame_rate(FrameRate::new(30000, 1001).unwrap())
4223                    .picture_aspect_ratio(crate::PictureAspectRatio::new(1.25).unwrap())
4224                    .scan_type(ScanType::Interlaced)
4225                    .timecode(Timecode::from_ticks(12345))
4226                    .line_stride_bytes(stride)
4227                    .metadata(&metadata)
4228                    .build()
4229                    .unwrap();
4230                let normalized = send.to_owned();
4231                assert_eq!(normalized.data(), expected);
4232                assert_eq!(normalized.timecode(), Timecode::from_ticks(12345));
4233                // A borrowed frame carries no timestamp.
4234                assert_eq!(normalized.timestamp(), None);
4235                assert_eq!(normalized.line_stride_bytes(), copied.line_stride_bytes());
4236                assert_eq!(normalized.metadata(), Some("<video-padding/>"));
4237                // Copies into existing frames pack the same rows from the
4238                // FrameSync view, over uninitialized padding, and from padded
4239                // borrowed frames with and without metadata.
4240                let bare = crate::BorrowedVideoFrame::builder(&initialized, 4, 4, format)
4241                    .line_stride_bytes(stride)
4242                    .build()
4243                    .unwrap();
4244                let sources: [&dyn CopySource<VideoFrame>; 3] = [&second, &send, &bare];
4245                for source in sources {
4246                    assert_eq!(source.owned().data(), expected);
4247                    assert_copies_reuse(source, video_destinations("<video-padding/>".len()));
4248                }
4249            }
4250        }
4251    }
4252
4253    #[test]
4254    fn borrowed_video_planes_borrow_only_the_active_rows_of_a_padded_buffer() {
4255        fn rows_of(planes: VideoPlanes<'_>) -> Vec<Vec<Vec<u8>>> {
4256            planes
4257                .map(|plane| plane.rows().map(<[u8]>::to_vec).collect())
4258                .collect()
4259        }
4260        const PADDING: u8 = 0xEE;
4261        // Independently specified active plane dimensions for 4x4 images.
4262        let cases: &[(PixelFormat, &[(usize, usize)])] = &[
4263            (PixelFormat::Bgra, &[(16, 4)]),
4264            (PixelFormat::Bgrx, &[(16, 4)]),
4265            (PixelFormat::Rgba, &[(16, 4)]),
4266            (PixelFormat::Rgbx, &[(16, 4)]),
4267            (PixelFormat::Uyvy, &[(8, 4)]),
4268            (PixelFormat::Uyva, &[(8, 4), (4, 4)]),
4269            (PixelFormat::P216, &[(8, 4), (8, 4)]),
4270            (PixelFormat::Pa16, &[(8, 4), (8, 4), (8, 4)]),
4271            (PixelFormat::Yv12, &[(4, 4), (2, 2), (2, 2)]),
4272            (PixelFormat::I420, &[(4, 4), (2, 2), (2, 2)]),
4273            (PixelFormat::Nv12, &[(4, 4), (4, 2)]),
4274        ];
4275        for &(format, dimensions) in cases {
4276            for padding in [0, 4, 8] {
4277                let stride = dimensions[0].0 + padding;
4278                // Each row's active bytes followed by its padding, which holds
4279                // a marker; the expected rows hold the active bytes alone.
4280                let mut buffer = Vec::new();
4281                let mut expected = Vec::new();
4282                let mut row_offsets = Vec::new();
4283                for (i, &(active, rows)) in dimensions.iter().enumerate() {
4284                    let plane_stride = stride * active / dimensions[0].0;
4285                    let mut plane_rows = Vec::new();
4286                    let mut plane_offsets = Vec::new();
4287                    for row in 0..rows {
4288                        let values: Vec<u8> = (0..active)
4289                            .map(|byte| (i * 71 + row * 17 + byte) as u8)
4290                            .collect();
4291                        plane_offsets.push(buffer.len());
4292                        buffer.extend_from_slice(&values);
4293                        buffer.resize(buffer.len() + plane_stride - active, PADDING);
4294                        plane_rows.push(values);
4295                    }
4296                    expected.push(plane_rows);
4297                    row_offsets.push(plane_offsets);
4298                }
4299                let frame = crate::BorrowedVideoFrame::builder(&buffer, 4, 4, format)
4300                    .line_stride_bytes(stride)
4301                    .build()
4302                    .unwrap();
4303                // Storage retains padding; data and plane views expose only active bytes.
4304                assert_eq!(frame.storage(), buffer);
4305                let ((), allocations) = crate::test_alloc::allocation_count(|| {
4306                    assert_eq!(frame.planes().len(), dimensions.len());
4307                    assert!(frame.plane(dimensions.len()).is_none());
4308                    for (i, plane) in frame.planes().enumerate() {
4309                        let (active, rows) = dimensions[i];
4310                        assert_eq!(plane.row_stride_bytes(), stride * active / dimensions[0].0);
4311                        assert_eq!(plane.active_row_bytes(), active);
4312                        assert_eq!(plane.row_count(), rows);
4313                        assert_eq!(plane.data().is_some(), padding == 0);
4314                        assert!(plane.row(rows).is_none());
4315                        let indexed = frame.plane(i).unwrap();
4316                        for (row_index, row) in plane.rows().enumerate() {
4317                            assert_eq!(row, expected[i][row_index]);
4318                            assert_eq!(indexed.row(row_index), Some(row));
4319                            // Borrowed in place, at the row's start in the buffer.
4320                            assert_eq!(row.as_ptr(), buffer[row_offsets[i][row_index]..].as_ptr());
4321                        }
4322                    }
4323                });
4324                assert_eq!(allocations, 0);
4325                assert_eq!(rows_of(frame.planes()), expected);
4326                // The owned copy holds the same rows, packed without padding,
4327                // and a frame borrowing that copy views them unchanged.
4328                let owned = frame.to_owned();
4329                assert_eq!(rows_of(owned.planes()), expected);
4330                assert_eq!(rows_of(owned.planes()), expected);
4331                assert!(owned.planes().all(|plane| plane.data().is_some()));
4332            }
4333        }
4334    }
4335
4336    #[test]
4337    fn video_padding_single_rows_and_zero_stride() {
4338        use crate::capture::{FrameSyncVideoFree, Guard};
4339        use std::mem::MaybeUninit;
4340        for format in [
4341            PixelFormat::Bgra,
4342            PixelFormat::Bgrx,
4343            PixelFormat::Rgba,
4344            PixelFormat::Rgbx,
4345            PixelFormat::Uyvy,
4346            PixelFormat::Uyva,
4347            PixelFormat::P216,
4348            PixelFormat::Pa16,
4349        ] {
4350            let tight = ValidatedVideoLayout::new_uncompressed(format, 2, 1, None).unwrap();
4351            assert!(VideoPlaneLayout::contiguous(tight.planes()).is_some());
4352            let active = format.line_stride_bytes(2).unwrap();
4353            let padded =
4354                ValidatedVideoLayout::new_uncompressed(format, 2, 1, Some(active + 4)).unwrap();
4355            let mut storage = [MaybeUninit::<u8>::uninit(); 64];
4356            for plane in padded.planes() {
4357                for byte in &mut storage[plane.offset()..plane.offset() + plane.active_row_bytes()]
4358                {
4359                    byte.write(42);
4360                }
4361            }
4362            let raw = NDIlib_video_frame_v2_t {
4363                xres: 2,
4364                yres: 1,
4365                FourCC: FourCc::from(format).raw(),
4366                frame_rate_N: 30,
4367                frame_rate_D: 1,
4368                p_data: storage.as_mut_ptr().cast(),
4369                frame_format_type: ScanType::Progressive.to_sdk(),
4370                __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
4371                    line_stride_in_bytes: (active + 4) as i32,
4372                },
4373                ..Default::default()
4374            };
4375            let frame = unsafe {
4376                FrameSyncVideoRef::new(Guard::<FrameSyncVideoFree>::with_test_free(
4377                    ptr::null_mut(),
4378                    raw,
4379                    |_, _| {},
4380                ))
4381            }
4382            .unwrap();
4383            assert_eq!(frame.data().is_some(), padded.plane_count() == 1);
4384            assert!(
4385                !frame.sends_in_place(),
4386                "padded {format:?} capture must stage"
4387            );
4388            assert!(frame.to_owned().sends_in_place());
4389            for plane in frame.planes() {
4390                assert_eq!(plane.data().unwrap(), vec![42; plane.active_row_bytes()]);
4391            }
4392            assert_eq!(frame.to_owned().data(), vec![42; tight.payload_len_bytes()]);
4393        }
4394        for format in [PixelFormat::Yv12, PixelFormat::I420, PixelFormat::Nv12] {
4395            let tight = ValidatedVideoLayout::new_uncompressed(format, 4, 2, None).unwrap();
4396            assert!(VideoPlaneLayout::contiguous(tight.planes()).is_some());
4397            let padded = ValidatedVideoLayout::new_uncompressed(format, 4, 2, Some(8)).unwrap();
4398            assert!(VideoPlaneLayout::contiguous(padded.planes()).is_none()); // Chroma is one row, but plane gaps remain.
4399        }
4400    }
4401
4402    /// Encoders read active bytes only: every format's padding is left
4403    /// uninitialized. The required Miri and Memcheck CI jobs detect reads of it.
4404    #[cfg(feature = "image-encoding")]
4405    #[test]
4406    fn video_padding_encoders_never_read_uninitialized_gaps() {
4407        #[cfg(not(miri))]
4408        use crate::image_encoding::{AlphaMode, Downscale, SampleDepth};
4409        use crate::{
4410            capture::{FrameSyncVideoFree, Guard},
4411            image_encoding::{ImageFormat, ImageOptions},
4412        };
4413        // Miri checks the initialized-region reader for every input format.
4414        // Memcheck and native tests exercise every encoder and option below.
4415        #[cfg(miri)]
4416        let outputs = [ImageOptions::new(ImageFormat::Png)];
4417        #[cfg(not(miri))]
4418        let outputs = [
4419            ImageOptions::new(ImageFormat::Png),
4420            ImageOptions::new(ImageFormat::Png).depth(SampleDepth::Sixteen),
4421            ImageOptions::new(ImageFormat::Png).downscale(Downscale::Half),
4422            ImageOptions::new(ImageFormat::Jpeg(85)),
4423            ImageOptions::new(ImageFormat::WebpLossless).alpha(AlphaMode::Discard),
4424            ImageOptions::new(ImageFormat::WebpLossy(75)),
4425            ImageOptions::new(ImageFormat::WebpLossy(75)).alpha(AlphaMode::Discard),
4426        ];
4427        for format in PixelFormat::ALL {
4428            let (width, height) = (4, 2);
4429            let packed =
4430                ValidatedVideoLayout::new_uncompressed(format, width, height, None).unwrap();
4431            let stride = packed.line_stride_bytes() + 8;
4432            let padded =
4433                ValidatedVideoLayout::new_uncompressed(format, width, height, Some(stride))
4434                    .unwrap();
4435            let mut storage = Box::<[u8]>::new_uninit_slice(padded.data_len_bytes());
4436            let mut active = Vec::new();
4437            let mut value = 7u8;
4438            for plane in padded.planes() {
4439                for row in 0..plane.row_count() {
4440                    for byte in 0..plane.active_row_bytes() {
4441                        value = value.wrapping_mul(31).wrapping_add(17);
4442                        storage[plane.offset() + row * plane.row_stride() + byte].write(value);
4443                        active.push(value);
4444                    }
4445                }
4446            }
4447            let raw = NDIlib_video_frame_v2_t {
4448                xres: width as i32,
4449                yres: height as i32,
4450                FourCC: FourCc::from(format).raw(),
4451                frame_rate_N: 30,
4452                frame_rate_D: 1,
4453                frame_format_type: ScanType::Progressive.to_sdk(),
4454                p_data: storage.as_mut_ptr().cast(),
4455                __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
4456                    line_stride_in_bytes: stride as i32,
4457                },
4458                ..Default::default()
4459            };
4460            // SAFETY: the descriptor points into `storage`, which outlives
4461            // the reference, and the no-op free releases nothing.
4462            let borrowed = unsafe {
4463                FrameSyncVideoRef::new(Guard::<FrameSyncVideoFree>::with_test_free(
4464                    ptr::null_mut(),
4465                    raw,
4466                    |_, _| {},
4467                ))
4468            }
4469            .unwrap();
4470            let owned = VideoFrame::builder()
4471                .resolution(width, height)
4472                .pixel_format(format)
4473                .data(active.clone())
4474                .build()
4475                .unwrap();
4476            for options in &outputs {
4477                assert_eq!(
4478                    borrowed.encode_image(options).unwrap(),
4479                    owned.encode_image(options).unwrap(),
4480                    "{format:?} {options:?}"
4481                );
4482            }
4483            assert_eq!(borrowed.to_owned().data(), active);
4484        }
4485    }
4486
4487    #[test]
4488    fn video_padding_reported_642_pixel_reproduction() {
4489        use crate::capture::{FrameSyncVideoFree, Guard};
4490        use std::mem::MaybeUninit;
4491        let mut storage = vec![MaybeUninit::<u8>::uninit(); 2592 * 32];
4492        for row in 0..32 {
4493            for byte in &mut storage[row * 2592..row * 2592 + 2568] {
4494                byte.write(17);
4495            }
4496        }
4497        let raw = NDIlib_video_frame_v2_t {
4498            xres: 642,
4499            yres: 32,
4500            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
4501            frame_rate_N: 30,
4502            frame_rate_D: 1,
4503            frame_format_type: ScanType::Progressive.to_sdk(),
4504            p_data: storage.as_mut_ptr().cast(),
4505            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
4506                line_stride_in_bytes: 2592,
4507            },
4508            ..Default::default()
4509        };
4510        let frame = unsafe {
4511            FrameSyncVideoRef::new(Guard::<FrameSyncVideoFree>::with_test_free(
4512                ptr::null_mut(),
4513                raw,
4514                |_, _| {},
4515            ))
4516        }
4517        .unwrap();
4518        assert!(frame.data().is_none());
4519        let owned = frame.to_owned();
4520        assert_eq!(owned.data().len(), 82_176);
4521        assert_eq!(owned.line_stride_bytes(), 2568);
4522        assert!(owned.data().iter().all(|&byte| byte == 17));
4523    }
4524
4525    #[test]
4526    fn video_builder_defaults_and_reuse_updates_preserve_pixels() {
4527        let built = VideoFrame::builder().build().unwrap();
4528        assert_eq!((built.width(), built.height()), (1920, 1080));
4529        assert_eq!(built.pixel_format(), PixelFormat::Bgra);
4530        assert_eq!(built.scan_type(), ScanType::Progressive);
4531        assert_eq!(built.frame_rate(), FrameRate::new(60, 1).unwrap());
4532        assert_eq!(built.picture_aspect_ratio().get(), 0.0);
4533        assert_eq!(built.timecode(), Timecode::SYNTHESIZE);
4534        assert_eq!(built.timestamp(), None);
4535        assert!(built.data().iter().all(|&byte| byte == 0));
4536        let mut frame = VideoFrame::builder().resolution(2, 2).build().unwrap();
4537        let pixels = frame.data().as_ptr();
4538        frame.set_timecode(Timecode::from_ticks(123));
4539        frame.set_scan_type(ScanType::Field1);
4540        frame.set_frame_rate(FrameRate::new(30000, 1001).unwrap());
4541        frame.set_picture_aspect_ratio(crate::PictureAspectRatio::new(0.0).unwrap());
4542        assert!(PictureAspectRatio::new(f32::NAN).is_err());
4543        let raw = frame.as_test_raw();
4544        assert_eq!(raw.timecode, 123);
4545        assert_eq!(raw.timestamp, NDIlib_recv_timestamp_undefined);
4546        assert_eq!((raw.frame_rate_N, raw.frame_rate_D), (30000, 1001));
4547        assert_eq!(raw.picture_aspect_ratio, 0.0);
4548        assert_eq!(frame.scan_type(), ScanType::Field1);
4549        assert_eq!(frame.data().as_ptr(), pixels);
4550    }
4551
4552    #[test]
4553    fn owned_frames_clone_into_independent_allocations() {
4554        let mut video = VideoFrame::builder()
4555            .resolution(2, 2)
4556            .data(vec![7; 16])
4557            .metadata("<video/>")
4558            .build()
4559            .unwrap();
4560        let copy = video.clone();
4561        video.data_mut().fill(9);
4562        assert_ne!(copy.data().as_ptr(), video.data().as_ptr());
4563        assert_eq!(copy.data(), &[7; 16]);
4564        assert_eq!(copy.metadata(), Some("<video/>"));
4565        assert_ne!(
4566            copy.metadata_cstr().unwrap().as_ptr(),
4567            video.metadata_cstr().unwrap().as_ptr()
4568        );
4569
4570        let mut audio = AudioFrame::builder()
4571            .num_channels(2)
4572            .num_samples(4)
4573            .metadata("<audio/>")
4574            .build()
4575            .unwrap();
4576        let copy = audio.clone();
4577        audio.data_mut().fill(1.0);
4578        assert_ne!(copy.data().as_ptr(), audio.data().as_ptr());
4579        assert!(copy.data().iter().all(|&sample| sample == 0.0));
4580        assert_eq!(copy.metadata(), Some("<audio/>"));
4581
4582        let metadata = MetadataFrame::new("<text/>").unwrap();
4583        assert_eq!(metadata.clone(), metadata);
4584    }
4585
4586    #[test]
4587    fn video_builder_retains_supplied_allocation_and_rejects_wrong_lengths() {
4588        let data = vec![37; 16];
4589        let pixels = data.as_ptr();
4590        let frame = VideoFrame::builder()
4591            .resolution(2, 2)
4592            .data(data)
4593            .build()
4594            .unwrap();
4595        assert_eq!(frame.data().as_ptr(), pixels);
4596        assert_eq!(frame.data(), &[37; 16]);
4597        for len in [0, 15, 17] {
4598            assert!(VideoFrame::builder()
4599                .resolution(2, 2)
4600                .data(vec![0; len])
4601                .build()
4602                .is_err());
4603        }
4604    }
4605
4606    /// Test PixelFormatInfo for packed RGB formats (32 bpp)
4607    #[test]
4608    fn test_pixel_format_info_packed_rgb() {
4609        let formats = [
4610            PixelFormat::Bgra,
4611            PixelFormat::Bgrx,
4612            PixelFormat::Rgba,
4613            PixelFormat::Rgbx,
4614        ];
4615
4616        for fmt in formats {
4617            let info = fmt.info();
4618            assert_eq!(
4619                info.bytes_per_pixel(),
4620                4,
4621                "Format {:?} bytes per pixel",
4622                fmt
4623            );
4624            assert_eq!(
4625                info.category(),
4626                FormatCategory::Packed,
4627                "Format {:?} category",
4628                fmt
4629            );
4630            assert!(
4631                !info.is_planar_420(),
4632                "Format {:?} should not be planar",
4633                fmt
4634            );
4635
4636            // 1920x1080, stride = 1920 * 4 = 7680
4637            let len = fmt.buffer_len(1920, 1080, Some(7680)).unwrap();
4638            assert_eq!(len, 7680 * 1080, "Format {:?} even dimensions", fmt);
4639
4640            // Padded rows with an odd height
4641            let len = fmt.buffer_len(1920, 1081, Some(7684)).unwrap();
4642            assert_eq!(len, 7684 * 1081, "Format {:?} padded rows", fmt);
4643        }
4644    }
4645
4646    /// Test PixelFormatInfo for packed YUV formats
4647    #[test]
4648    fn test_pixel_format_info_packed_yuv() {
4649        // UYVY: 16 bpp = 2 bytes per pixel
4650        let info = PixelFormat::Uyvy.info();
4651        assert_eq!(info.bytes_per_pixel(), 2);
4652        assert_eq!(info.category(), FormatCategory::Packed);
4653        let len = PixelFormat::Uyvy
4654            .buffer_len(1920, 1080, Some(3840))
4655            .unwrap();
4656        assert_eq!(len, 3840 * 1080);
4657
4658        // UYVA: UYVY plane (2 bytes per pixel) + alpha plane at half stride
4659        let info = PixelFormat::Uyva.info();
4660        assert_eq!(info.bytes_per_pixel(), 2);
4661        assert_eq!(info.category(), FormatCategory::PackedAlpha);
4662        assert!(!info.is_planar_420());
4663        let len = PixelFormat::Uyva
4664            .buffer_len(1920, 1080, Some(3840))
4665            .unwrap();
4666        assert_eq!(len, 3840 * 1080 + 1920 * 1080);
4667        // Padded stride: alpha plane follows at stride / 2
4668        let len = PixelFormat::Uyva
4669            .buffer_len(1920, 1080, Some(4096))
4670            .unwrap();
4671        assert_eq!(len, 4096 * 1080 + 2048 * 1080);
4672        assert!(PixelFormat::Uyva
4673            .buffer_len(1920, 1080, Some(3841))
4674            .is_err());
4675
4676        // P216: 16-bit Y plane + 16-bit CbCr plane, both at the line stride
4677        let info = PixelFormat::P216.info();
4678        assert_eq!(info.bytes_per_pixel(), 2);
4679        assert_eq!(info.category(), FormatCategory::SemiPlanar422);
4680        assert!(!info.is_planar_420());
4681        let len = PixelFormat::P216
4682            .buffer_len(1920, 1080, Some(3840))
4683            .unwrap();
4684        assert_eq!(len, 3840 * 1080 * 2);
4685
4686        // PA16: P216 + 16-bit alpha plane at the line stride
4687        let info = PixelFormat::Pa16.info();
4688        assert_eq!(info.bytes_per_pixel(), 2);
4689        assert_eq!(info.category(), FormatCategory::SemiPlanar422Alpha);
4690        assert!(!info.is_planar_420());
4691        let len = PixelFormat::Pa16
4692            .buffer_len(1920, 1080, Some(3840))
4693            .unwrap();
4694        assert_eq!(len, 3840 * 1080 * 3);
4695    }
4696
4697    /// Test PixelFormatInfo for planar YV12/I420 with even dimensions
4698    #[test]
4699    fn test_pixel_format_info_planar_420_even() {
4700        // 1920x1080 YV12/I420
4701        // Y: 1920 * 1080 = 2,073,600
4702        // U: (1920/2) * (1080/2) = 960 * 540 = 518,400
4703        // V: (1920/2) * (1080/2) = 960 * 540 = 518,400
4704        // Total: 2,073,600 + 518,400 + 518,400 = 3,110,400
4705        let y_stride = 1920;
4706
4707        let info = PixelFormat::Yv12.info();
4708        assert_eq!(info.bytes_per_pixel(), 1);
4709        assert_eq!(info.category(), FormatCategory::Planar420);
4710        assert!(info.is_planar_420());
4711        let len = PixelFormat::Yv12
4712            .buffer_len(1920, 1080, Some(y_stride))
4713            .unwrap();
4714        assert_eq!(len, 3_110_400, "YV12 1920x1080");
4715
4716        let info = PixelFormat::I420.info();
4717        assert_eq!(info.category(), FormatCategory::Planar420);
4718        let len = PixelFormat::I420
4719            .buffer_len(1920, 1080, Some(y_stride))
4720            .unwrap();
4721        assert_eq!(len, 3_110_400, "I420 1920x1080");
4722    }
4723
4724    /// Test PixelFormatInfo rejects planar YV12/I420 with odd layout inputs
4725    #[test]
4726    fn test_pixel_format_info_planar_420_odd() {
4727        let y_stride = 1921;
4728
4729        assert!(PixelFormat::Yv12
4730            .buffer_len(1920, 1081, Some(y_stride))
4731            .is_err());
4732        assert!(PixelFormat::I420
4733            .buffer_len(1920, 1081, Some(y_stride))
4734            .is_err());
4735    }
4736
4737    /// Test PixelFormatInfo for semi-planar NV12 with even dimensions
4738    #[test]
4739    fn test_pixel_format_info_nv12_even() {
4740        // 1920x1080 NV12
4741        // Y: 1920 * 1080 = 2,073,600
4742        // UV: 1920 * (1080/2) = 1920 * 540 = 1,036,800
4743        // Total: 2,073,600 + 1,036,800 = 3,110,400
4744        let y_stride = 1920;
4745
4746        let info = PixelFormat::Nv12.info();
4747        assert_eq!(info.bytes_per_pixel(), 1);
4748        assert_eq!(info.category(), FormatCategory::SemiPlanar420);
4749        assert!(info.is_planar_420());
4750        let len = PixelFormat::Nv12
4751            .buffer_len(1920, 1080, Some(y_stride))
4752            .unwrap();
4753        assert_eq!(len, 3_110_400, "NV12 1920x1080");
4754    }
4755
4756    /// Test PixelFormatInfo rejects semi-planar NV12 with odd layout inputs
4757    #[test]
4758    fn test_pixel_format_info_nv12_odd() {
4759        let y_stride = 1921;
4760        assert!(PixelFormat::Nv12
4761            .buffer_len(1920, 1081, Some(y_stride))
4762            .is_err());
4763    }
4764
4765    /// 4:2:0 parity is decided only by the shared plane layout, so every path
4766    /// answers alike: NV12 accepts an odd stride, YV12/I420 reject odd stride
4767    /// and odd height, and all three reject odd height.
4768    #[test]
4769    fn test_420_parity_is_consistent_across_paths() {
4770        // (format, height, stride, accepted)
4771        let cases = [
4772            (PixelFormat::Nv12, 1080, 1921, true),
4773            (PixelFormat::Nv12, 1080, 1920, true),
4774            (PixelFormat::Nv12, 1081, 1920, false),
4775            (PixelFormat::Yv12, 1080, 1921, false),
4776            (PixelFormat::I420, 1080, 1921, false),
4777            (PixelFormat::Yv12, 1081, 1920, false),
4778            (PixelFormat::I420, 1081, 1920, false),
4779            (PixelFormat::Yv12, 1080, 1920, true),
4780            (PixelFormat::I420, 1080, 1920, true),
4781        ];
4782        for (format, height, stride, accepted) in cases {
4783            let label = format!("{format:?} {stride}x{height}");
4784            let info_len = format.buffer_len(1920, height, Some(stride));
4785            let layout = ValidatedVideoLayout::new_uncompressed(format, 1920, height, Some(stride));
4786            assert_eq!(info_len.is_ok(), accepted, "buffer_len {label}");
4787            assert_eq!(layout.is_ok(), accepted, "new_uncompressed {label}");
4788
4789            let data = vec![0u8; stride * height as usize * 2];
4790            let sender = crate::BorrowedVideoFrame::builder(&data, 1920, height, format)
4791                .line_stride_bytes(stride)
4792                .build();
4793            assert_eq!(sender.is_ok(), accepted, "BorrowedVideoFrame {label}");
4794
4795            if let (Ok(len), Ok(layout)) = (info_len, layout) {
4796                assert_eq!(layout.data_len_bytes(), len, "{label}");
4797            }
4798            if !accepted && height % 2 == 0 {
4799                let msg = format.buffer_len(1920, height, Some(stride)).unwrap_err();
4800                assert!(
4801                    matches!(msg, Error::InvalidFrame(crate::FrameDefect::Layout(crate::LayoutDefect::VideoPlanar420 {stride:found,..})) if found==stride),
4802                    "{label}: {msg}"
4803                );
4804            }
4805        }
4806        // NV12 odd stride: the UV plane is height/2 rows of the full stride.
4807        assert_eq!(
4808            PixelFormat::Nv12
4809                .buffer_len(1920, 1080, Some(1921))
4810                .unwrap(),
4811            1921 * 1080 + 1921 * 540
4812        );
4813    }
4814
4815    /// Test PixelFormat::line_stride_bytes for all formats
4816    #[test]
4817    fn buffer_len_checks_explicit_stride_against_active_width() {
4818        assert_eq!(
4819            PixelFormat::Bgra
4820                .buffer_len(1920, 1080, Some(7684))
4821                .unwrap(),
4822            7684 * 1080
4823        );
4824        assert_eq!(
4825            PixelFormat::Nv12
4826                .buffer_len(1920, 1080, Some(2048))
4827                .unwrap(),
4828            3_317_760
4829        );
4830        assert!(PixelFormat::Bgra
4831            .buffer_len(1920, 1080, Some(7679))
4832            .is_err());
4833        assert!(PixelFormat::Bgra.buffer_len(1920, 1080, Some(0)).is_err());
4834        assert_eq!(
4835            PixelFormat::Bgra.buffer_len(1920, 1080, None).unwrap(),
4836            PixelFormat::Bgra
4837                .buffer_len(1920, 1080, Some(7680))
4838                .unwrap()
4839        );
4840    }
4841
4842    #[test]
4843    fn explicit_zero_video_stride_is_refused_at_every_application_entry() {
4844        let expected = crate::FrameDefect::Layout(crate::LayoutDefect::VideoZeroStride);
4845        for format in PixelFormat::ALL {
4846            assert!(
4847                matches!(format.buffer_len(16, 16, Some(0)), Err(Error::InvalidFrame(defect)) if defect == expected),
4848                "{format:?} buffer_len"
4849            );
4850            let packed = format.buffer_len(16, 16, None).unwrap();
4851            let data = vec![0; packed];
4852            for scan in ScanType::ALL {
4853                assert!(
4854                    matches!(format.send_buffer_len(16, 16, Some(0), scan), Err(Error::InvalidFrame(defect)) if defect == expected),
4855                    "{format:?} {scan:?} send_buffer_len"
4856                );
4857                let frame = crate::BorrowedVideoFrame::builder(&data, 16, 16, format)
4858                    .scan_type(scan)
4859                    .line_stride_bytes(0)
4860                    .build();
4861                assert!(
4862                    matches!(frame, Err(Error::InvalidFrame(defect)) if defect == expected),
4863                    "{format:?} {scan:?} builder"
4864                );
4865                let reset = crate::BorrowedVideoFrame::builder(&data, 16, 16, format)
4866                    .scan_type(scan)
4867                    .line_stride_bytes(0)
4868                    .clear_line_stride_bytes()
4869                    .build()
4870                    .unwrap();
4871                assert_eq!(
4872                    reset.line_stride_bytes(),
4873                    format.line_stride_bytes(16).unwrap()
4874                );
4875            }
4876            // SDK input alone keeps the documented zero-means-packed sentinel.
4877            let sdk = ValidatedVideoLayout::from_sdk(format, 16, 16, 0).unwrap();
4878            assert_eq!(sdk.data_len_bytes(), packed);
4879            assert_eq!(
4880                sdk.line_stride_bytes(),
4881                format.line_stride_bytes(16).unwrap()
4882            );
4883        }
4884    }
4885
4886    #[test]
4887    fn test_pixel_format_line_stride() {
4888        // Packed RGB: 4 bytes per pixel
4889        assert_eq!(PixelFormat::Bgra.line_stride_bytes(1920).unwrap(), 7680);
4890        assert_eq!(PixelFormat::Bgrx.line_stride_bytes(1920).unwrap(), 7680);
4891        assert_eq!(PixelFormat::Rgba.line_stride_bytes(1920).unwrap(), 7680);
4892        assert_eq!(PixelFormat::Rgbx.line_stride_bytes(1920).unwrap(), 7680);
4893
4894        // UYVY: 2 bytes per pixel
4895        assert_eq!(PixelFormat::Uyvy.line_stride_bytes(1920).unwrap(), 3840);
4896
4897        // UYVA: UYVY plane stride = 2 bytes per pixel
4898        assert_eq!(PixelFormat::Uyva.line_stride_bytes(1920).unwrap(), 3840);
4899
4900        // P216/PA16: Y-plane stride = 2 bytes per pixel
4901        assert_eq!(PixelFormat::P216.line_stride_bytes(1920).unwrap(), 3840);
4902        assert_eq!(PixelFormat::Pa16.line_stride_bytes(1920).unwrap(), 3840);
4903
4904        // Planar 4:2:0: Y-plane stride = 1 byte per pixel
4905        assert_eq!(PixelFormat::Yv12.line_stride_bytes(1920).unwrap(), 1920);
4906        assert_eq!(PixelFormat::I420.line_stride_bytes(1920).unwrap(), 1920);
4907        assert_eq!(PixelFormat::Nv12.line_stride_bytes(1920).unwrap(), 1920);
4908    }
4909
4910    /// Test PixelFormat::buffer_size for all formats
4911    #[test]
4912    fn test_pixel_format_buffer_size() {
4913        // Packed RGB: width * 4 * height
4914        assert_eq!(
4915            PixelFormat::Bgra.buffer_len(1920, 1080, None).unwrap(),
4916            8_294_400
4917        );
4918        assert_eq!(
4919            PixelFormat::Rgba.buffer_len(1920, 1080, None).unwrap(),
4920            8_294_400
4921        );
4922
4923        // Planar 4:2:0: Y + U + V = 1.5 * width * height
4924        assert_eq!(
4925            PixelFormat::Yv12.buffer_len(1920, 1080, None).unwrap(),
4926            3_110_400
4927        );
4928        assert_eq!(
4929            PixelFormat::I420.buffer_len(1920, 1080, None).unwrap(),
4930            3_110_400
4931        );
4932
4933        // Semi-planar 4:2:0: Y + UV = 1.5 * width * height
4934        assert_eq!(
4935            PixelFormat::Nv12.buffer_len(1920, 1080, None).unwrap(),
4936            3_110_400
4937        );
4938
4939        // UYVA: UYVY + alpha = 3 * width * height
4940        assert_eq!(
4941            PixelFormat::Uyva.buffer_len(1920, 1080, None).unwrap(),
4942            6_220_800
4943        );
4944
4945        // Semi-planar 4:2:2 16-bit: Y + CbCr = 4 * width * height
4946        assert_eq!(
4947            PixelFormat::P216.buffer_len(1920, 1080, None).unwrap(),
4948            8_294_400
4949        );
4950
4951        // Semi-planar 4:2:2 16-bit with alpha: Y + CbCr + A = 6 * width * height
4952        assert_eq!(
4953            PixelFormat::Pa16.buffer_len(1920, 1080, None).unwrap(),
4954            12_441_600
4955        );
4956    }
4957
4958    /// Test PixelFormatInfo::is_planar_420 helper
4959    #[test]
4960    fn test_pixel_format_info_is_planar_420() {
4961        assert!(PixelFormat::Yv12.info().is_planar_420());
4962        assert!(PixelFormat::I420.info().is_planar_420());
4963        assert!(PixelFormat::Nv12.info().is_planar_420());
4964
4965        assert!(!PixelFormat::Bgra.info().is_planar_420());
4966        assert!(!PixelFormat::Rgba.info().is_planar_420());
4967        assert!(!PixelFormat::Uyvy.info().is_planar_420());
4968        assert!(!PixelFormat::Uyva.info().is_planar_420());
4969    }
4970
4971    /// Test VideoFrame builder with planar formats produces correct buffer sizes
4972    #[test]
4973    fn test_videoframe_builder_planar_even() {
4974        let frame = VideoFrame::builder()
4975            .resolution(1920, 1080)
4976            .pixel_format(PixelFormat::Nv12)
4977            .build()
4978            .expect("Builder should succeed");
4979
4980        assert_eq!(frame.width(), 1920);
4981        assert_eq!(frame.height(), 1080);
4982        assert_eq!(frame.pixel_format(), PixelFormat::Nv12);
4983        assert_eq!(frame.data().len(), 3_110_400, "NV12 1920x1080 buffer size");
4984    }
4985
4986    #[test]
4987    fn test_video_dimensions_across_all_formats() {
4988        let formats = [
4989            PixelFormat::Bgra,
4990            PixelFormat::Bgrx,
4991            PixelFormat::Rgba,
4992            PixelFormat::Rgbx,
4993            PixelFormat::Uyvy,
4994            PixelFormat::Uyva,
4995            PixelFormat::P216,
4996            PixelFormat::Pa16,
4997            PixelFormat::Yv12,
4998            PixelFormat::I420,
4999            PixelFormat::Nv12,
5000        ];
5001        let mut data = vec![0u8; 4096];
5002        for format in formats {
5003            for (width, height) in [(0, 2), (-2, 2), (1, 2), (3, 2), (2, 0), (2, -1)] {
5004                // The API's unsigned dimensions and the SDK's signed ones get
5005                // the same checks.
5006                if let (Ok(width), Ok(height)) = (u32::try_from(width), u32::try_from(height)) {
5007                    assert!(
5008                        format.buffer_len(width, height, None).is_err(),
5009                        "{format:?} {width}x{height}"
5010                    );
5011                    assert!(VideoFrame::builder()
5012                        .resolution(width, height)
5013                        .pixel_format(format)
5014                        .build()
5015                        .is_err());
5016                    assert!(
5017                        crate::BorrowedVideoFrame::builder(&data, width, height, format)
5018                            .build()
5019                            .is_err()
5020                    );
5021                }
5022                let raw = NDIlib_video_frame_v2_t {
5023                    xres: width,
5024                    yres: height,
5025                    FourCC: FourCc::from(format).raw(),
5026                    frame_rate_N: 30,
5027                    frame_rate_D: 1,
5028                    picture_aspect_ratio: 0.0,
5029                    frame_format_type: ScanType::Progressive.to_sdk(),
5030                    timecode: 0,
5031                    p_data: data.as_mut_ptr(),
5032                    __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
5033                        line_stride_in_bytes: 128,
5034                    },
5035                    p_metadata: ptr::null(),
5036                    timestamp: 0,
5037                };
5038                assert!(matches!(
5039                    validate_video_frame(&raw),
5040                    Err(Error::InvalidFrame(_))
5041                ));
5042                // Reject before forming a slice or copying received bytes.
5043                assert!(unsafe { VideoFrame::from_raw(&raw) }.is_err());
5044            }
5045            for width in [0, 1, 3] {
5046                assert!(
5047                    format.line_stride_bytes(width).is_err(),
5048                    "{format:?} width={width}"
5049                );
5050            }
5051            for height in [1, 2, 3] {
5052                let valid = !format.info().is_planar_420() || height % 2 == 0;
5053                assert_eq!(format.buffer_len(2, height, None).is_ok(), valid);
5054                assert_eq!(
5055                    VideoFrame::builder()
5056                        .resolution(2, height)
5057                        .pixel_format(format)
5058                        .build()
5059                        .is_ok(),
5060                    valid
5061                );
5062                assert_eq!(
5063                    crate::BorrowedVideoFrame::builder(&data, 2, height, format)
5064                        .build()
5065                        .is_ok(),
5066                    valid
5067                );
5068            }
5069            // Even width does not imply a larger alignment requirement.
5070            assert!(format.line_stride_bytes(6).is_ok());
5071            assert!(ValidatedVideoLayout::new_uncompressed(format, 6, 2, Some(128)).is_ok());
5072        }
5073        // RGB row padding need not be divisible by two or by a pixel size.
5074        assert!(ValidatedVideoLayout::new_uncompressed(PixelFormat::Bgra, 2, 3, Some(9)).is_ok());
5075    }
5076
5077    /// Test VideoFrame builder rejects planar formats with odd dimensions
5078    #[test]
5079    fn test_videoframe_builder_planar_odd() {
5080        let result = VideoFrame::builder()
5081            .resolution(1921, 1081)
5082            .pixel_format(PixelFormat::I420)
5083            .build()
5084            .map_err(Rejected::into_error);
5085
5086        assert!(
5087            matches!(result, Err(Error::InvalidFrame(_))),
5088            "Planar 4:2:0 odd dimensions should be rejected"
5089        );
5090    }
5091
5092    /// Test VideoFrame builder with packed format (regression test)
5093    #[test]
5094    fn test_videoframe_builder_packed() {
5095        let frame = VideoFrame::builder()
5096            .resolution(1920, 1080)
5097            .pixel_format(PixelFormat::Bgra)
5098            .build()
5099            .expect("Builder should succeed");
5100
5101        assert_eq!(frame.width(), 1920);
5102        assert_eq!(frame.height(), 1080);
5103        assert_eq!(frame.pixel_format(), PixelFormat::Bgra);
5104        assert_eq!(
5105            frame.data().len(),
5106            1920 * 1080 * 4,
5107            "BGRA buffer size unchanged"
5108        );
5109    }
5110
5111    /// Test VideoFrame builder hands the SDK the first-plane stride for 4:2:2
5112    /// formats with extra planes
5113    #[test]
5114    fn test_videoframe_builder_semi_planar_422_and_alpha() {
5115        for (format, expected_len) in [
5116            (PixelFormat::Uyva, 256 * 2 * 64 + 256 * 64),
5117            (PixelFormat::P216, 256 * 2 * 64 * 2),
5118            (PixelFormat::Pa16, 256 * 2 * 64 * 3),
5119        ] {
5120            let frame = VideoFrame::builder()
5121                .resolution(256, 64)
5122                .pixel_format(format)
5123                .build()
5124                .expect("Builder should succeed");
5125
5126            assert_eq!(frame.line_stride_bytes(), 256 * 2, "{format:?} line stride");
5127            assert_eq!(frame.data().len(), expected_len, "{format:?} buffer size");
5128        }
5129    }
5130
5131    /// Test VideoFrame::from_raw with synthetic NV12 frame
5132    #[test]
5133    fn test_videoframe_from_raw_nv12() {
5134        // Create a synthetic NV12 frame
5135        let width = 1920;
5136        let height = 1080;
5137        let y_stride = 1920;
5138        let expected_size = 3_110_400; // Y + UV for NV12
5139
5140        let mut data = vec![0u8; expected_size];
5141        // Mark the last byte to verify it's copied
5142        data[expected_size - 1] = 0xFF;
5143
5144        let c_frame = NDIlib_video_frame_v2_t {
5145            xres: width,
5146            yres: height,
5147            FourCC: FourCc::from(PixelFormat::Nv12).raw(),
5148            frame_rate_N: 60,
5149            frame_rate_D: 1,
5150            picture_aspect_ratio: 16.0 / 9.0,
5151            frame_format_type: ScanType::Progressive.to_sdk(),
5152            timecode: 0,
5153            p_data: data.as_mut_ptr(),
5154            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
5155                line_stride_in_bytes: y_stride,
5156            },
5157            p_metadata: ptr::null(),
5158            timestamp: 0,
5159        };
5160
5161        let frame = unsafe { VideoFrame::from_raw(&c_frame) }.expect("from_raw should succeed");
5162
5163        assert_eq!((frame.width(), frame.height()), (1920, 1080));
5164        assert_eq!(frame.pixel_format(), PixelFormat::Nv12);
5165        assert_eq!(
5166            frame.data().len(),
5167            expected_size,
5168            "Should copy full Y+UV buffer"
5169        );
5170        assert_eq!(
5171            frame.data()[expected_size - 1],
5172            0xFF,
5173            "Last byte should be copied"
5174        );
5175    }
5176
5177    /// Test VideoFrame::from_raw rejects synthetic I420 frame with odd dimensions
5178    #[test]
5179    fn test_videoframe_from_raw_i420_odd() {
5180        let width = 1921;
5181        let height = 1081;
5182        let y_stride = 1921;
5183        let expected_size = 3_116_403; // Y + U + V with ceiling division
5184
5185        let mut data = vec![0u8; expected_size];
5186
5187        let c_frame = NDIlib_video_frame_v2_t {
5188            xres: width,
5189            yres: height,
5190            FourCC: FourCc::from(PixelFormat::I420).raw(),
5191            frame_rate_N: 30,
5192            frame_rate_D: 1,
5193            picture_aspect_ratio: 16.0 / 9.0,
5194            frame_format_type: ScanType::Progressive.to_sdk(),
5195            timecode: 0,
5196            p_data: data.as_mut_ptr(),
5197            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
5198                line_stride_in_bytes: y_stride,
5199            },
5200            p_metadata: ptr::null(),
5201            timestamp: 0,
5202        };
5203
5204        let result = unsafe { VideoFrame::from_raw(&c_frame) };
5205        assert!(
5206            matches!(result, Err(Error::InvalidFrame(_))),
5207            "Planar 4:2:0 odd dimensions should be rejected"
5208        );
5209    }
5210
5211    /// Regression test: VideoFrame::from_raw with packed format should be unchanged
5212    #[test]
5213    fn test_videoframe_from_raw_packed_regression() {
5214        let width = 1920;
5215        let height = 1080;
5216        let stride = 1920 * 4; // BGRA
5217        let expected_size = (stride * height) as usize;
5218
5219        let mut data = vec![0u8; expected_size];
5220
5221        let c_frame = NDIlib_video_frame_v2_t {
5222            xres: width,
5223            yres: height,
5224            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
5225            frame_rate_N: 60,
5226            frame_rate_D: 1,
5227            picture_aspect_ratio: 16.0 / 9.0,
5228            frame_format_type: ScanType::Progressive.to_sdk(),
5229            timecode: 0,
5230            p_data: data.as_mut_ptr(),
5231            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
5232                line_stride_in_bytes: stride,
5233            },
5234            p_metadata: ptr::null(),
5235            timestamp: 0,
5236        };
5237
5238        let frame = unsafe { VideoFrame::from_raw(&c_frame) }.expect("from_raw should succeed");
5239        assert_eq!(
5240            frame.data().len(),
5241            expected_size,
5242            "BGRA buffer size unchanged"
5243        );
5244    }
5245
5246    /// Test that VideoFrameRef::new rejects unknown FourCC
5247    #[test]
5248    fn test_videoframeref_unknown_fourcc() {
5249        use crate::capture::{Guard, VideoKind};
5250
5251        let width = 1920;
5252        let height = 1080;
5253        let stride = 1920 * 4;
5254        let expected_size = (stride * height) as usize;
5255        let mut data = vec![0u8; expected_size];
5256
5257        let c_frame = NDIlib_video_frame_v2_t {
5258            xres: width,
5259            yres: height,
5260            FourCC: 0xDEADBEEF, // Unknown FourCC
5261            frame_rate_N: 60,
5262            frame_rate_D: 1,
5263            picture_aspect_ratio: 16.0 / 9.0,
5264            frame_format_type: ScanType::Progressive.to_sdk(),
5265            timecode: 0,
5266            p_data: data.as_mut_ptr(),
5267            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
5268                line_stride_in_bytes: stride,
5269            },
5270            p_metadata: ptr::null(),
5271            timestamp: 0,
5272        };
5273
5274        let mock_instance = ptr::null_mut();
5275        let guard =
5276            unsafe { Guard::<VideoKind>::with_test_free(mock_instance, c_frame, |_, _| {}) };
5277
5278        // VideoFrameRef::new should return an error for unknown FourCC
5279        let result = VideoFrameRef::new(guard);
5280        assert!(result.is_err(), "Should reject unknown FourCC");
5281
5282        if let Err(Error::InvalidFrame(ref msg)) = result {
5283            assert!(
5284                matches!(
5285                    msg,
5286                    crate::FrameDefect::UnknownPixelFormat { fourcc: 0xDEADBEEF }
5287                ),
5288                "Error message should include FourCC: {}",
5289                msg
5290            );
5291        } else {
5292            panic!("Expected InvalidFrame error");
5293        }
5294    }
5295
5296    /// Test that VideoFrameRef::new accepts known FourCC and stores validated format
5297    #[test]
5298    fn test_videoframeref_known_fourcc() {
5299        use crate::capture::{Guard, VideoKind};
5300
5301        let width = 1920;
5302        let height = 1080;
5303        let stride = 1920 * 4;
5304        let expected_size = (stride * height) as usize;
5305        let mut data = vec![0u8; expected_size];
5306
5307        let c_frame = NDIlib_video_frame_v2_t {
5308            xres: width,
5309            yres: height,
5310            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
5311            frame_rate_N: 60,
5312            frame_rate_D: 1,
5313            picture_aspect_ratio: 16.0 / 9.0,
5314            frame_format_type: ScanType::Progressive.to_sdk(),
5315            timecode: 0,
5316            p_data: data.as_mut_ptr(),
5317            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
5318                line_stride_in_bytes: stride,
5319            },
5320            p_metadata: ptr::null(),
5321            timestamp: 0,
5322        };
5323
5324        let mock_instance = ptr::null_mut();
5325        let guard =
5326            unsafe { Guard::<VideoKind>::with_test_free(mock_instance, c_frame, |_, _| {}) };
5327
5328        let frame_ref = VideoFrameRef::new(guard).expect("Should accept BGRA FourCC");
5329        assert_eq!(
5330            frame_ref.pixel_format(),
5331            PixelFormat::Bgra,
5332            "Should store validated pixel format"
5333        );
5334    }
5335
5336    /// Test that AudioFrameRef::new rejects unknown FourCC
5337    #[test]
5338    fn test_audioframeref_unknown_fourcc() {
5339        let num_samples = 1024;
5340        let num_channels = 2;
5341        let sample_count = (num_samples * num_channels) as usize;
5342        let mut data = vec![0.0f32; sample_count];
5343
5344        // Use an unknown FourCC value (0xBADC0DE)
5345        let c_frame = NDIlib_audio_frame_v3_t {
5346            sample_rate: 48000,
5347            no_channels: num_channels,
5348            no_samples: num_samples,
5349            timecode: 0,
5350            FourCC: 0xBADC0DE, // Unknown audio FourCC
5351            p_data: data.as_mut_ptr() as *mut u8,
5352            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
5353                channel_stride_in_bytes: num_samples * 4,
5354            },
5355            p_metadata: ptr::null(),
5356            timestamp: 0,
5357        };
5358
5359        let mock_instance = ptr::null_mut();
5360        let guard =
5361            unsafe { Guard::<AudioKind>::with_test_free(mock_instance, c_frame, |_, _| {}) };
5362
5363        let result = AudioFrameRef::new(guard);
5364        assert!(result.is_err(), "Should reject unknown audio FourCC");
5365
5366        if let Err(Error::InvalidFrame(ref msg)) = result {
5367            assert!(
5368                matches!(
5369                    msg,
5370                    crate::FrameDefect::UnknownAudioFormat { fourcc: 0x0BADC0DE }
5371                ),
5372                "Error message should include FourCC: {}",
5373                msg
5374            );
5375        } else {
5376            panic!("Expected InvalidFrame error");
5377        }
5378    }
5379
5380    /// Test that AudioFrameRef::new accepts known FourCC and stores validated format
5381    #[test]
5382    fn test_audioframeref_known_fourcc() {
5383        let num_samples = 1024;
5384        let num_channels = 2;
5385        let sample_count = (num_samples * num_channels) as usize;
5386        let mut data = vec![0.0f32; sample_count];
5387
5388        let c_frame = NDIlib_audio_frame_v3_t {
5389            sample_rate: 48000,
5390            no_channels: num_channels,
5391            no_samples: num_samples,
5392            timecode: 0,
5393            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
5394            p_data: data.as_mut_ptr() as *mut u8,
5395            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
5396                channel_stride_in_bytes: num_samples * 4,
5397            },
5398            p_metadata: ptr::null(),
5399            timestamp: 0,
5400        };
5401
5402        let mock_instance = ptr::null_mut();
5403        let guard =
5404            unsafe { Guard::<AudioKind>::with_test_free(mock_instance, c_frame, |_, _| {}) };
5405
5406        let frame_ref = AudioFrameRef::new(guard).expect("Should accept FLTP FourCC");
5407        assert_eq!(
5408            frame_ref.format(),
5409            AudioFormat::Fltp,
5410            "Should store validated audio format"
5411        );
5412    }
5413
5414    /// Test that VideoFrameRef correctly uses validated format for data size calculation
5415    #[test]
5416    fn test_videoframeref_data_uses_validated_format() {
5417        use crate::capture::{Guard, VideoKind};
5418
5419        // Test with uncompressed format (BGRA)
5420        let width = 1920;
5421        let height = 1080;
5422        let stride = 1920 * 4;
5423        let expected_size = (stride * height) as usize;
5424        let mut data = vec![0xAB_u8; expected_size];
5425
5426        let c_frame = NDIlib_video_frame_v2_t {
5427            xres: width,
5428            yres: height,
5429            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
5430            frame_rate_N: 60,
5431            frame_rate_D: 1,
5432            picture_aspect_ratio: 16.0 / 9.0,
5433            frame_format_type: ScanType::Progressive.to_sdk(),
5434            timecode: 0,
5435            p_data: data.as_mut_ptr(),
5436            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
5437                line_stride_in_bytes: stride,
5438            },
5439            p_metadata: ptr::null(),
5440            timestamp: 0,
5441        };
5442
5443        let mock_instance = ptr::null_mut();
5444        let guard =
5445            unsafe { Guard::<VideoKind>::with_test_free(mock_instance, c_frame, |_, _| {}) };
5446        let frame_ref = VideoFrameRef::new(guard).expect("Should create frame ref");
5447
5448        // Verify data() returns correct size based on validated format
5449        assert_eq!(
5450            frame_ref.data().unwrap().len(),
5451            expected_size,
5452            "data() should use validated pixel format for size calculation"
5453        );
5454
5455        // Verify line_stride_bytes() uses validated format
5456        assert_eq!(
5457            frame_ref.line_stride_bytes(),
5458            stride as usize,
5459            "line_stride_bytes() should use validated format"
5460        );
5461    }
5462
5463    /// The receiver and FrameSync video refs agree: given byte-identical raw
5464    /// frames, every shared accessor, `scan_type` included, returns identical
5465    /// results, as both spellings share one [`VideoFrameRef`] core.
5466    #[test]
5467    fn test_receiver_and_framesync_video_refs_agree() {
5468        use crate::capture::{FrameSyncVideoFree, Guard, VideoKind};
5469
5470        let width = 16;
5471        let height = 8;
5472        let stride = width * 4;
5473        let len = (stride * height) as usize;
5474
5475        // Two independent buffers with identical content, so each ref owns a
5476        // distinct (non-aliasing) frame while still comparing equal.
5477        let mut recv_data: Vec<u8> = (0..len).map(|i| (i % 251) as u8).collect();
5478        let mut fs_data = recv_data.clone();
5479        let mut recv_meta = b"shared frame\0".to_vec();
5480        let mut fs_meta = recv_meta.clone();
5481
5482        let raw = |data: &mut [u8], meta: &mut [u8]| NDIlib_video_frame_v2_t {
5483            xres: width,
5484            yres: height,
5485            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
5486            frame_rate_N: 30,
5487            frame_rate_D: 1,
5488            picture_aspect_ratio: 16.0 / 9.0,
5489            // A non-default scan type, which a ref that falls back to
5490            // `Progressive` would report differently.
5491            frame_format_type: ScanType::Interlaced.to_sdk(),
5492            timecode: 123,
5493            p_data: data.as_mut_ptr(),
5494            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
5495                line_stride_in_bytes: stride,
5496            },
5497            p_metadata: meta.as_mut_ptr().cast(),
5498            timestamp: 456,
5499        };
5500
5501        let recv_raw = raw(&mut recv_data, &mut recv_meta);
5502        let fs_raw = raw(&mut fs_data, &mut fs_meta);
5503
5504        let recv_guard =
5505            unsafe { Guard::<VideoKind>::with_test_free(ptr::null_mut(), recv_raw, |_, _| {}) };
5506        let recv = VideoFrameRef::new(recv_guard).expect("receiver video ref");
5507        let fs_guard = unsafe {
5508            Guard::<FrameSyncVideoFree>::with_test_free(ptr::null_mut(), fs_raw, |_, _| {})
5509        };
5510        let fs = FrameSyncVideoRef::new(fs_guard).expect("framesync video ref");
5511
5512        assert_eq!(recv.width(), fs.width());
5513        assert_eq!(recv.height(), fs.height());
5514        assert_eq!(recv.pixel_format(), fs.pixel_format());
5515        assert_eq!(recv.frame_rate(), fs.frame_rate());
5516        assert_eq!(
5517            recv.picture_aspect_ratio().get(),
5518            fs.picture_aspect_ratio().get()
5519        );
5520        assert_eq!(recv.scan_type(), fs.scan_type());
5521        assert_eq!(recv.scan_type(), ScanType::Interlaced);
5522        assert_eq!(recv.timecode(), fs.timecode());
5523        assert_eq!(recv.timestamp(), fs.timestamp());
5524        assert_eq!(recv.line_stride_bytes(), fs.line_stride_bytes());
5525        assert_eq!(recv.metadata(), fs.metadata());
5526        assert_eq!(recv.data(), fs.data());
5527    }
5528
5529    /// An out-of-range `frame_format_type` must be rejected by `validate_video_frame`
5530    /// before either video ref is constructed, so `scan_type()` can return the
5531    /// validated header without a fallible conversion.
5532    #[test]
5533    fn test_video_ref_rejects_out_of_range_scan_type() {
5534        use crate::capture::{FrameSyncVideoFree, Guard, VideoKind};
5535
5536        let width = 16;
5537        let height = 8;
5538        let stride = width * 4;
5539        let len = (stride * height) as usize;
5540        let mut recv_data = vec![0u8; len];
5541        let mut fs_data = vec![0u8; len];
5542
5543        let raw = |data: &mut [u8]| NDIlib_video_frame_v2_t {
5544            xres: width,
5545            yres: height,
5546            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
5547            frame_rate_N: 30,
5548            frame_rate_D: 1,
5549            picture_aspect_ratio: 16.0 / 9.0,
5550            frame_format_type: 0x0BAD_F00D, // not a valid NDIlib_frame_format_type_e
5551            timecode: 0,
5552            p_data: data.as_mut_ptr(),
5553            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
5554                line_stride_in_bytes: stride,
5555            },
5556            p_metadata: ptr::null(),
5557            timestamp: 0,
5558        };
5559
5560        // Frame validation rejects it directly...
5561        assert!(matches!(
5562            validate_video_frame(&raw(&mut recv_data)),
5563            Err(Error::InvalidFrame(_))
5564        ));
5565
5566        // ...and so both ref constructors fail before any `scan_type()` call.
5567        let recv_guard = unsafe {
5568            Guard::<VideoKind>::with_test_free(ptr::null_mut(), raw(&mut recv_data), |_, _| {})
5569        };
5570        assert!(matches!(
5571            VideoFrameRef::new(recv_guard),
5572            Err(Error::InvalidFrame(_))
5573        ));
5574
5575        let fs_guard = unsafe {
5576            Guard::<FrameSyncVideoFree>::with_test_free(
5577                ptr::null_mut(),
5578                raw(&mut fs_data),
5579                |_, _| {},
5580            )
5581        };
5582        assert!(matches!(
5583            FrameSyncVideoRef::new(fs_guard),
5584            Err(Error::InvalidFrame(_))
5585        ));
5586    }
5587
5588    #[test]
5589    fn dci_8k_fits_every_supported_pixel_format() {
5590        for format in PixelFormat::ALL {
5591            let stride = format.line_stride_bytes(DCI_8K_WIDTH).unwrap();
5592            let extent = format
5593                .buffer_len(DCI_8K_WIDTH, DCI_8K_HEIGHT, Some(stride))
5594                .unwrap();
5595            let sdk_layout = ValidatedVideoLayout::from_sdk_checked(
5596                format,
5597                DCI_8K_WIDTH as i32,
5598                DCI_8K_HEIGHT as i32,
5599                stride as i32,
5600            )
5601            .unwrap();
5602            assert_eq!(sdk_layout.data_len_bytes(), extent, "{format:?}");
5603            assert!(extent <= MAX_VIDEO_BYTES, "{format:?}");
5604
5605            // An empty input lets each builder report its admitted extent
5606            // without allocating hundreds of megabytes for the test.
5607            let owned = VideoFrame::builder()
5608                .resolution(DCI_8K_WIDTH, DCI_8K_HEIGHT)
5609                .pixel_format(format)
5610                .data(Vec::new())
5611                .build()
5612                .unwrap_err();
5613            assert!(
5614                matches!(owned.error(), Error::InvalidFrame(
5615                crate::FrameDefect::VideoDataLength { actual: 0, expected }
5616            ) if *expected == extent),
5617                "{format:?}: {owned}"
5618            );
5619            let borrowed = BorrowedVideoFrame::builder(&[], DCI_8K_WIDTH, DCI_8K_HEIGHT, format)
5620                .line_stride_bytes(stride)
5621                .build()
5622                .unwrap_err();
5623            assert!(
5624                matches!(borrowed, Error::InvalidFrame(
5625                crate::FrameDefect::VideoBufferTooSmall { actual: 0, minimum, .. }
5626            ) if minimum == extent),
5627                "{format:?}: {borrowed}"
5628            );
5629        }
5630    }
5631
5632    #[test]
5633    fn nb4g_dci_8k_sets_the_video_extent_limit() {
5634        let format = PixelFormat::Nb4g;
5635        let stride = format.line_stride_bytes(DCI_8K_WIDTH).unwrap();
5636        assert_eq!(
5637            format
5638                .buffer_len(DCI_8K_WIDTH, DCI_8K_HEIGHT, Some(stride))
5639                .unwrap(),
5640            MAX_VIDEO_BYTES
5641        );
5642
5643        let height = DCI_8K_HEIGHT + 1;
5644        let extent = MAX_VIDEO_BYTES + stride * format.info().plane_count();
5645        let expected = crate::LayoutDefect::VideoBytes((extent as u64).into());
5646        let matches_extent = |error: &Error| {
5647            matches!(error, Error::InvalidFrame(
5648            crate::FrameDefect::Layout(cause)
5649        ) if *cause == expected)
5650        };
5651        let sdk_layout = ValidatedVideoLayout::from_sdk_checked(
5652            format,
5653            DCI_8K_WIDTH as i32,
5654            height as i32,
5655            stride as i32,
5656        );
5657        assert_eq!(sdk_layout.unwrap_err(), expected);
5658        assert!(matches_extent(
5659            &format
5660                .buffer_len(DCI_8K_WIDTH, height, Some(stride))
5661                .unwrap_err()
5662        ));
5663        assert!(matches_extent(
5664            VideoFrame::builder()
5665                .resolution(DCI_8K_WIDTH, height)
5666                .pixel_format(format)
5667                .data(Vec::new())
5668                .build()
5669                .unwrap_err()
5670                .error()
5671        ));
5672        assert!(matches_extent(
5673            &BorrowedVideoFrame::builder(&[], DCI_8K_WIDTH, height, format)
5674                .line_stride_bytes(stride)
5675                .build()
5676                .unwrap_err()
5677        ));
5678    }
5679
5680    /// Test that MAX_AUDIO_BYTES constant is properly defined
5681    #[test]
5682    fn test_max_audio_bytes_constant() {
5683        // Verify the constant is set to 64 MiB as specified
5684        assert_eq!(MAX_AUDIO_BYTES, 64 * 1024 * 1024);
5685    }
5686
5687    /// Test that MAX_METADATA_BYTES constant is properly defined.
5688    #[test]
5689    fn test_max_metadata_bytes_constant() {
5690        assert_eq!(MAX_METADATA_BYTES, 4 * 1024 * 1024);
5691    }
5692
5693    fn metadata_raw_from_bytes(data: &mut [u8], length: i32) -> NDIlib_metadata_frame_t {
5694        NDIlib_metadata_frame_t {
5695            length,
5696            timecode: 12345,
5697            p_data: data.as_mut_ptr().cast::<c_char>(),
5698        }
5699    }
5700
5701    fn null_metadata_raw(length: i32) -> NDIlib_metadata_frame_t {
5702        NDIlib_metadata_frame_t {
5703            length,
5704            timecode: 12345,
5705            p_data: ptr::null_mut(),
5706        }
5707    }
5708
5709    #[test]
5710    fn test_validate_metadata_layout_accepts_empty_null_frame() {
5711        let raw = null_metadata_raw(0);
5712        let layout = unsafe { validate_metadata_layout(&raw) }.expect("empty null frame is valid");
5713
5714        assert!(layout.is_none());
5715    }
5716
5717    #[test]
5718    fn test_validate_metadata_layout_accepts_one_byte_empty_payload() {
5719        let mut data = vec![0u8];
5720        let raw = metadata_raw_from_bytes(&mut data, 1);
5721        let layout =
5722            unsafe { validate_metadata_layout(&raw) }.expect("explicit empty payload is valid");
5723
5724        assert_eq!(layout.map(MetadataText::as_str), Some(""));
5725        assert_eq!(
5726            layout.map(MetadataText::as_ptr),
5727            Some(raw.p_data.cast_const())
5728        );
5729    }
5730
5731    #[test]
5732    fn test_validate_metadata_layout_accepts_utf8_with_bounded_length() {
5733        let mut data = "<ndi tally=\"preview\"/>".as_bytes().to_vec();
5734        data.push(0);
5735        let length = data.len() as i32;
5736        let raw = metadata_raw_from_bytes(&mut data, length);
5737        let layout = unsafe { validate_metadata_layout(&raw) }.expect("valid UTF-8 metadata");
5738
5739        // The SDK length includes the terminator; the text excludes it.
5740        assert_eq!(
5741            layout.map(MetadataText::as_str),
5742            Some("<ndi tally=\"preview\"/>")
5743        );
5744        assert_eq!(layout.map(MetadataText::len_with_nul), Some(data.len()));
5745    }
5746
5747    #[test]
5748    fn test_validate_metadata_layout_ignores_bytes_after_length() {
5749        let mut data = b"ok\0\0\xFF".to_vec();
5750        let raw = metadata_raw_from_bytes(&mut data, 3);
5751        let layout =
5752            unsafe { validate_metadata_layout(&raw) }.expect("extra bytes after length ignored");
5753
5754        assert_eq!(layout.map(MetadataText::as_str), Some("ok"));
5755        let owned = MetadataFrame::copied(layout, Timecode::from_ticks(raw.timecode));
5756        assert_eq!(owned.data(), "ok");
5757    }
5758
5759    #[test]
5760    fn test_validate_metadata_layout_rejects_negative_length() {
5761        let raw = null_metadata_raw(-1);
5762
5763        assert!(matches!(
5764            unsafe { validate_metadata_layout(&raw) },
5765            Err(Error::InvalidFrame(_))
5766        ));
5767    }
5768
5769    #[test]
5770    fn test_validate_metadata_layout_accepts_lengthless_non_null_data() {
5771        let mut data = b"<ndi/>\0ignored".to_vec();
5772        let raw = metadata_raw_from_bytes(&mut data, 0);
5773        let layout = unsafe { validate_metadata_layout(&raw) }.expect("SDK C-string sentinel");
5774        assert_eq!(layout.map(MetadataText::as_str), Some("<ndi/>"));
5775        let owned = MetadataFrame::copied(layout, Timecode::from_ticks(raw.timecode));
5776        assert_eq!(owned.data(), "<ndi/>");
5777    }
5778
5779    #[test]
5780    fn test_lengthless_metadata_rejects_invalid_utf8_and_missing_nul() {
5781        let mut invalid = vec![0xff, 0];
5782        assert!(matches!(
5783            unsafe { validate_metadata_layout(&metadata_raw_from_bytes(&mut invalid, 0)) },
5784            Err(Error::InvalidUtf8(_))
5785        ));
5786        let mut unterminated = vec![b'x'; MAX_METADATA_BYTES];
5787        assert!(unsafe {
5788            validate_metadata_layout(&metadata_raw_from_bytes(&mut unterminated, 0))
5789        }
5790        .is_err());
5791    }
5792
5793    #[test]
5794    fn test_validate_metadata_layout_rejects_nonzero_length_null_data() {
5795        let raw = null_metadata_raw(1);
5796
5797        assert!(matches!(
5798            unsafe { validate_metadata_layout(&raw) },
5799            Err(Error::InvalidFrame(_))
5800        ));
5801    }
5802
5803    #[test]
5804    fn test_validate_metadata_layout_rejects_missing_trailing_nul() {
5805        let mut data = b"abc".to_vec();
5806        let length = data.len() as i32;
5807        let raw = metadata_raw_from_bytes(&mut data, length);
5808
5809        assert!(matches!(
5810            unsafe { validate_metadata_layout(&raw) },
5811            Err(Error::InvalidFrame(_))
5812        ));
5813    }
5814
5815    #[test]
5816    fn test_validate_metadata_layout_rejects_interior_nul() {
5817        let mut data = b"a\0b\0".to_vec();
5818        let length = data.len() as i32;
5819        let raw = metadata_raw_from_bytes(&mut data, length);
5820
5821        assert!(matches!(
5822            unsafe { validate_metadata_layout(&raw) },
5823            Err(Error::InvalidFrame(_))
5824        ));
5825    }
5826
5827    #[test]
5828    fn test_validate_metadata_layout_rejects_oversized_length_before_reading() {
5829        let mut data = vec![0u8];
5830        let raw = metadata_raw_from_bytes(&mut data, (MAX_METADATA_BYTES + 1) as i32);
5831
5832        assert!(matches!(
5833            unsafe { validate_metadata_layout(&raw) },
5834            Err(Error::InvalidFrame(_))
5835        ));
5836    }
5837
5838    #[test]
5839    fn test_validate_metadata_layout_rejects_invalid_utf8() {
5840        let mut data = vec![0xFF, 0];
5841        let length = data.len() as i32;
5842        let raw = metadata_raw_from_bytes(&mut data, length);
5843
5844        assert!(matches!(
5845            unsafe { validate_metadata_layout(&raw) },
5846            Err(Error::InvalidUtf8(_))
5847        ));
5848    }
5849
5850    #[test]
5851    fn sender_metadata_uses_terminated_text_with_different_reported_counts() {
5852        for text in ["<ascii/>", "<payload>é🎥</payload>", ""] {
5853            let mut bytes = text.as_bytes().to_vec();
5854            bytes.push(0);
5855            for count in [0, text.len(), text.len() + 1, text.chars().count() + 1] {
5856                let raw = metadata_raw_from_bytes(&mut bytes, count as i32);
5857                // SAFETY: bytes retains the full NUL-terminated string,
5858                // independent of the descriptor's reported count.
5859                let actual = unsafe { validate_sender_metadata(&raw) }.unwrap().unwrap();
5860                assert_eq!(actual.as_str(), text);
5861                assert_eq!(actual.as_ptr(), raw.p_data.cast_const());
5862                assert_eq!(actual.len_with_nul(), bytes.len());
5863                assert_eq!(
5864                    raw.length, count as i32,
5865                    "the SDK free descriptor is unchanged"
5866                );
5867            }
5868        }
5869    }
5870
5871    #[test]
5872    fn sender_metadata_rejects_invalid_fields_utf8_and_unbounded_text() {
5873        // SAFETY: null pointers are checked without reading, and zero means
5874        // the documented empty-null metadata representation.
5875        assert!(unsafe { validate_sender_metadata(&null_metadata_raw(0)) }
5876            .unwrap()
5877            .is_none());
5878        for count in [-1, 1, i32::MAX] {
5879            assert!(matches!(
5880                unsafe { validate_sender_metadata(&null_metadata_raw(count)) },
5881                Err(Error::InvalidFrame(_)),
5882            ));
5883        }
5884        let mut empty = [0];
5885        let excessive = metadata_raw_from_bytes(&mut empty, (MAX_METADATA_BYTES + 1) as i32);
5886        // SAFETY: the pointed-to C string is complete, even though its
5887        // descriptor's excessive count is rejected before scanning it.
5888        assert!(matches!(
5889            unsafe { validate_sender_metadata(&excessive) },
5890            Err(Error::InvalidFrame(_))
5891        ));
5892
5893        let mut invalid = [0xff, 0];
5894        let raw = metadata_raw_from_bytes(&mut invalid, 1);
5895        // SAFETY: full NUL-terminated storage is retained; UTF-8 is checked.
5896        assert!(matches!(
5897            unsafe { validate_sender_metadata(&raw) },
5898            Err(Error::InvalidUtf8(_))
5899        ));
5900
5901        let mut boundary = vec![b'x'; MAX_METADATA_BYTES];
5902        boundary[MAX_METADATA_BYTES - 1] = 0;
5903        let raw = metadata_raw_from_bytes(&mut boundary, 1);
5904        // SAFETY: storage covers the entire string through its terminator.
5905        assert_eq!(
5906            unsafe { validate_sender_metadata(&raw) }
5907                .unwrap()
5908                .unwrap()
5909                .len_with_nul(),
5910            MAX_METADATA_BYTES
5911        );
5912        boundary[MAX_METADATA_BYTES - 1] = b'x';
5913        let raw = metadata_raw_from_bytes(&mut boundary, 1);
5914        // SAFETY: the entire capped scan is readable even without a terminator.
5915        assert!(matches!(
5916            unsafe { validate_sender_metadata(&raw) },
5917            Err(Error::InvalidFrame(_))
5918        ));
5919    }
5920
5921    #[test]
5922    fn test_metadata_frame_constructor_and_accessors_preserve_text() {
5923        let frame = MetadataFrame::new("<ndi_product/>").unwrap();
5924        assert_eq!(frame.timecode(), Timecode::SYNTHESIZE);
5925        let frame = frame.with_timecode(Timecode::from_ticks(9876));
5926
5927        assert_eq!(frame.data(), "<ndi_product/>");
5928        assert_eq!(frame.timecode(), Timecode::from_ticks(9876));
5929        assert_eq!(frame.clone().into_data(), "<ndi_product/>");
5930    }
5931
5932    #[test]
5933    fn test_metadata_frame_rejects_interior_nul_input() {
5934        assert!(matches!(
5935            MetadataFrame::new("bad\0metadata").map_err(Rejected::into_error),
5936            Err(Error::InvalidCString(_))
5937        ));
5938
5939        let mut frame = MetadataFrame::new("").unwrap();
5940        assert!(matches!(
5941            frame
5942                .set_data("bad\0metadata")
5943                .map_err(Rejected::into_error),
5944            Err(Error::InvalidCString(_))
5945        ));
5946    }
5947
5948    #[test]
5949    fn test_metadata_frame_rejects_oversized_input() {
5950        let oversized = "x".repeat(MAX_METADATA_BYTES);
5951
5952        assert!(matches!(
5953            MetadataFrame::new(oversized).map_err(Rejected::into_error),
5954            Err(Error::InvalidFrame(_))
5955        ));
5956    }
5957
5958    #[test]
5959    fn test_metadata_frame_setters_preserve_invariants() {
5960        let mut frame = MetadataFrame::new("").unwrap();
5961
5962        frame.set_data("updated").unwrap();
5963        frame.set_timecode(Timecode::from_ticks(42));
5964
5965        assert_eq!(frame.data(), "updated");
5966        assert_eq!(frame.timecode(), Timecode::from_ticks(42));
5967        assert!(frame.set_data("bad\0text").is_err());
5968        assert_eq!(frame.data(), "updated");
5969    }
5970
5971    #[test]
5972    fn validated_metadata_reuses_storage_and_copies_once() {
5973        let text = "é".repeat(550);
5974        let frame = MetadataFrame::new(text).unwrap();
5975        let expected = frame.data.text().as_ptr() as *mut c_char;
5976        let ((), allocations) = crate::test_alloc::allocation_count(|| {
5977            for _ in 0..100 {
5978                let raw = frame.metadata_raw();
5979                assert_eq!(raw.p_data, expected);
5980                assert_eq!(raw.length, 1101);
5981                assert_eq!(frame.data().len(), 1100);
5982            }
5983        });
5984        assert_eq!(allocations, 0);
5985
5986        let (copy, allocations) =
5987            crate::test_alloc::allocation_count(|| TerminatedText::copied(frame.data.text()));
5988        assert_eq!(allocations, 1);
5989        assert_eq!(copy.as_str(), frame.data());
5990        let (text, allocations) = crate::test_alloc::allocation_count(|| copy.into_string());
5991        assert_eq!(allocations, 0);
5992        assert_eq!(text, frame.data());
5993    }
5994
5995    #[test]
5996    fn metadata_construction_retains_owned_storage() {
5997        fn text() -> String {
5998            let mut text = String::with_capacity(1024);
5999            text.push_str("<metadata label='é'/>");
6000            text
6001        }
6002        let supplied = text();
6003        let (pointer, capacity) = (supplied.as_ptr(), supplied.capacity());
6004        let (metadata, allocations) =
6005            crate::test_alloc::allocation_count(|| MetadataFrame::new(supplied).unwrap());
6006        assert_eq!(allocations, 0);
6007        assert_eq!(metadata.data().as_ptr(), pointer);
6008        assert_eq!(metadata.into_data().capacity(), capacity);
6009
6010        let supplied = text();
6011        let (pointer, capacity) = (supplied.as_ptr(), supplied.capacity());
6012        let builder = VideoFrame::builder()
6013            .resolution(2, 2)
6014            .data(vec![7; 16])
6015            .metadata(supplied);
6016        let (video, allocations) = crate::test_alloc::allocation_count(|| builder.build().unwrap());
6017        assert_eq!(allocations, 0);
6018        assert_eq!(video.metadata().unwrap().as_ptr(), pointer);
6019        assert_eq!(video.metadata.retained_bytes(), capacity);
6020
6021        let supplied = text();
6022        let (pointer, capacity) = (supplied.as_ptr(), supplied.capacity());
6023        let builder = AudioFrame::builder()
6024            .num_channels(2)
6025            .num_samples(2)
6026            .data(vec![0.25; 4])
6027            .metadata(supplied);
6028        let (audio, allocations) = crate::test_alloc::allocation_count(|| builder.build().unwrap());
6029        assert_eq!(allocations, 0);
6030        assert_eq!(audio.metadata().unwrap().as_ptr(), pointer);
6031        assert_eq!(audio.metadata.retained_bytes(), capacity);
6032    }
6033
6034    #[test]
6035    fn rejected_builders_preserve_the_supplied_text_and_media_allocations() {
6036        for (valid_length, text) in [
6037            (true, "bad\0metadata".to_owned()),
6038            (true, "x".repeat(MAX_METADATA_BYTES)),
6039            (false, "valid metadata".to_owned()),
6040            (false, "bad\0metadata".to_owned()),
6041        ] {
6042            let (pixel_len, sample_len) = if valid_length { (16, 4) } else { (15, 3) };
6043            let mut video_text = String::with_capacity(text.len() + 16);
6044            video_text.push_str(&text);
6045            let (pointer, text_capacity) = (video_text.as_ptr(), video_text.capacity());
6046            let mut pixels = Vec::with_capacity(64);
6047            pixels.resize(pixel_len, 7);
6048            let (pixels_pointer, pixels_capacity) = (pixels.as_ptr(), pixels.capacity());
6049            let refused = VideoFrame::builder()
6050                .resolution(2, 2)
6051                .data(pixels)
6052                .metadata(video_text)
6053                .build()
6054                .unwrap_err();
6055            assert_eq!(
6056                matches!(
6057                    refused.error(),
6058                    Error::InvalidFrame(crate::FrameDefect::VideoDataLength { .. })
6059                ),
6060                !valid_length
6061            );
6062            let mut builder = refused.into_inner();
6063            let metadata = builder.take_metadata().unwrap();
6064            let pixels = builder.into_data().unwrap();
6065            assert_eq!(metadata.as_str(), text);
6066            assert_eq!(
6067                (metadata.as_ptr(), metadata.capacity()),
6068                (pointer, text_capacity)
6069            );
6070            assert_eq!(pixels, vec![7; pixel_len]);
6071            assert_eq!(
6072                (pixels.as_ptr(), pixels.capacity()),
6073                (pixels_pointer, pixels_capacity)
6074            );
6075
6076            let mut audio_text = String::with_capacity(text.len() + 16);
6077            audio_text.push_str(&text);
6078            let (pointer, text_capacity) = (audio_text.as_ptr(), audio_text.capacity());
6079            let mut samples = Vec::with_capacity(16);
6080            samples.extend_from_slice(&[1.0, 3.0, 2.0, 4.0][..sample_len]);
6081            let (samples_pointer, samples_capacity) = (samples.as_ptr(), samples.capacity());
6082            let refused = AudioFrame::builder()
6083                .num_channels(2)
6084                .num_samples(2)
6085                .data(samples)
6086                .metadata(audio_text)
6087                .build()
6088                .unwrap_err();
6089            assert_eq!(
6090                matches!(
6091                    refused.error(),
6092                    Error::InvalidFrame(crate::FrameDefect::AudioDataLength { .. })
6093                ),
6094                !valid_length
6095            );
6096            let mut builder = refused.into_inner();
6097            let metadata = builder.take_metadata().unwrap();
6098            let samples = builder.into_data().unwrap();
6099            assert_eq!(metadata.as_str(), text);
6100            assert_eq!(
6101                (metadata.as_ptr(), metadata.capacity()),
6102                (pointer, text_capacity)
6103            );
6104            assert_eq!(samples, [1.0, 3.0, 2.0, 4.0][..sample_len]);
6105            assert_eq!(
6106                (samples.as_ptr(), samples.capacity()),
6107                (samples_pointer, samples_capacity)
6108            );
6109        }
6110    }
6111
6112    #[test]
6113    fn metadata_copies_reuse_storage_across_lengths() {
6114        let sources = ["same", "é", "", "longer text", "same"].map(|text| {
6115            MetadataFrame::new(text)
6116                .unwrap()
6117                .with_timecode(Timecode::from_ticks(42))
6118        });
6119        let mut destination = MetadataFrame::new("x".repeat(64)).unwrap();
6120        let pointer = destination.data().as_ptr();
6121        let ((), allocations) = crate::test_alloc::allocation_count(|| {
6122            for source in &sources {
6123                let source: &dyn MetadataSource = source;
6124                source.copy_into(&mut destination);
6125                assert_eq!(destination.data(), source.data());
6126                assert_eq!(destination.timecode(), source.timecode());
6127                assert_eq!(destination.data().as_ptr(), pointer);
6128                let raw = destination.metadata_raw();
6129                assert_eq!(raw.length as usize, source.data().len() + 1);
6130                // SAFETY: the descriptor borrows the live, validated destination.
6131                assert_eq!(
6132                    unsafe { CStr::from_ptr(raw.p_data) }.to_bytes(),
6133                    source.as_bytes()
6134                );
6135            }
6136        });
6137        assert_eq!(allocations, 0);
6138    }
6139
6140    #[test]
6141    fn media_copies_reuse_metadata_storage_across_lengths() {
6142        let pixels = [7; 16];
6143        let samples = [0.25; 4];
6144        let mut video = VideoFrame::builder()
6145            .resolution(2, 2)
6146            .metadata("x".repeat(64))
6147            .build()
6148            .unwrap();
6149        let mut audio = AudioFrame::builder()
6150            .num_channels(2)
6151            .num_samples(2)
6152            .metadata("x".repeat(64))
6153            .build()
6154            .unwrap();
6155        let video_pointer = video.data().as_ptr();
6156        let audio_pointer = audio.data().as_ptr();
6157        let video_text = video.metadata().unwrap().as_ptr();
6158        let audio_text = audio.metadata().unwrap().as_ptr();
6159        #[cfg(feature = "advanced")]
6160        let retained = video.retained_bytes();
6161        let ((), allocations) = crate::test_alloc::allocation_count(|| {
6162            for text in [c"same", c"é", c"", c"longer text", c"same"] {
6163                let source = crate::BorrowedVideoFrame::builder(&pixels, 2, 2, PixelFormat::Bgra)
6164                    .metadata(text)
6165                    .timecode(Timecode::from_ticks(42))
6166                    .build()
6167                    .unwrap();
6168                VideoSource::copy_into(&source, &mut video);
6169                let source = BorrowedAudioFrame::builder(&samples, 48_000, 2, 2)
6170                    .metadata(text)
6171                    .timecode(Timecode::from_ticks(42))
6172                    .build()
6173                    .unwrap();
6174                AudioSource::copy_into(&source, &mut audio);
6175                let text = text.to_str().unwrap();
6176                assert_eq!(video.metadata(), Some(text));
6177                assert_eq!(audio.metadata(), Some(text));
6178                assert_eq!(video.metadata().unwrap().as_ptr(), video_text);
6179                assert_eq!(audio.metadata().unwrap().as_ptr(), audio_text);
6180                assert_eq!(video.data().as_ptr(), video_pointer);
6181                assert_eq!(audio.data().as_ptr(), audio_pointer);
6182                assert_eq!(video.data(), pixels);
6183                assert_eq!(audio.data(), samples);
6184                assert_eq!(video.timecode().ticks(), 42);
6185                assert_eq!(audio.timecode().ticks(), 42);
6186                #[cfg(feature = "advanced")]
6187                assert_eq!(video.retained_bytes(), retained);
6188            }
6189        });
6190        assert_eq!(allocations, 0);
6191    }
6192
6193    #[test]
6194    fn metadata_storage_grows_once_then_keeps_capacity() {
6195        let larger = MetadataFrame::new("é".repeat(64)).unwrap();
6196        let smaller = MetadataFrame::new("").unwrap();
6197        let mut destination = MetadataFrame::new("x").unwrap();
6198        let ((), allocations) =
6199            crate::test_alloc::allocation_count(|| larger.copy_into(&mut destination));
6200        assert_eq!(allocations, 1);
6201        let pointer = destination.data().as_ptr();
6202        let capacity = destination.data.capacity();
6203        let (text, allocations) = crate::test_alloc::allocation_count(|| {
6204            for _ in 0..10 {
6205                smaller.copy_into(&mut destination);
6206                larger.copy_into(&mut destination);
6207                assert_eq!(destination.data().as_ptr(), pointer);
6208                assert_eq!(destination.data.capacity(), capacity);
6209            }
6210            destination.into_data()
6211        });
6212        assert_eq!(allocations, 0);
6213        assert_eq!(text, larger.data());
6214        assert_eq!(text.as_ptr(), pointer);
6215        assert_eq!(text.capacity(), capacity);
6216    }
6217
6218    #[test]
6219    fn test_metadata_frame_copy_holds_only_payload() {
6220        let mut data = b"copy-me\0\0\xFF".to_vec();
6221        let raw = metadata_raw_from_bytes(&mut data, 8);
6222        let layout = unsafe { validate_metadata_layout(&raw) }.unwrap();
6223        let frame = MetadataFrame::copied(layout, Timecode::from_ticks(raw.timecode));
6224
6225        assert_eq!(frame.data(), "copy-me");
6226        assert_eq!(frame.timecode(), Timecode::from_ticks(12345));
6227    }
6228
6229    #[test]
6230    fn test_metadata_frame_from_raw_reports_invalid_utf8() {
6231        let mut data = vec![0xFF, 0];
6232        let raw = metadata_raw_from_bytes(&mut data, 2);
6233
6234        assert!(matches!(
6235            unsafe { MetadataFrame::from_raw(&raw) },
6236            Err(Error::InvalidUtf8(_))
6237        ));
6238    }
6239
6240    #[test]
6241    fn test_metadata_frame_to_raw_includes_trailing_nul() {
6242        let frame = MetadataFrame::new("abc")
6243            .unwrap()
6244            .with_timecode(Timecode::from_ticks(101));
6245        let raw = frame.metadata_raw();
6246
6247        assert_eq!(raw.length, 4);
6248        assert_eq!(raw.timecode, 101);
6249        assert_eq!(raw.p_data, frame.data.text().as_ptr() as *mut c_char);
6250        assert_eq!(frame.data.terminated_bytes(), b"abc\0");
6251    }
6252
6253    #[test]
6254    fn test_empty_metadata_frame_to_raw_sends_explicit_nul() {
6255        let frame = MetadataFrame::new("").unwrap();
6256        let raw = frame.metadata_raw();
6257
6258        assert_eq!(raw.length, 1);
6259        assert_eq!(raw.timecode, NDIlib_send_timecode_synthesize);
6260        assert_eq!(frame.data.terminated_bytes(), b"\0");
6261    }
6262
6263    #[test]
6264    fn captured_metadata_source_reborrows_text_without_allocation() {
6265        use crate::capture::RecvMetadataGuard;
6266
6267        let mut bytes = b"<relay>\xc3\xa9</relay>\0".to_vec();
6268        let length = bytes.len() as i32;
6269        let raw = metadata_raw_from_bytes(&mut bytes, length);
6270        let guard = unsafe { RecvMetadataGuard::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
6271        let captured = MetadataFrameRef::new(guard).unwrap();
6272        let source: &dyn MetadataSource = &captured;
6273        let (descriptor, allocations) = crate::test_alloc::allocation_count(|| {
6274            assert_eq!(source.data(), "<relay>é</relay>");
6275            assert_eq!(source.as_bytes(), "<relay>é</relay>".as_bytes());
6276            assert_eq!(source.timecode().ticks(), raw.timecode);
6277            source.metadata_raw()
6278        });
6279        assert_eq!(allocations, 0);
6280        assert_eq!(descriptor.p_data, raw.p_data);
6281        assert_eq!(descriptor.length, length);
6282        assert_eq!(descriptor.timecode, raw.timecode);
6283
6284        let mut destination = MetadataFrame::new("x".repeat(bytes.len() - 1)).unwrap();
6285        let pointer = destination.data().as_ptr();
6286        let ((), allocations) =
6287            crate::test_alloc::allocation_count(|| source.copy_into(&mut destination));
6288        assert_eq!(allocations, 0);
6289        assert_eq!(destination.data().as_ptr(), pointer);
6290        assert_eq!(destination.data(), source.data());
6291        assert_eq!(destination.timecode(), source.timecode());
6292        assert_eq!(MetadataSource::to_owned(source), destination);
6293    }
6294
6295    #[test]
6296    fn captured_empty_metadata_source_sends_a_terminated_empty_payload() {
6297        use crate::capture::RecvMetadataGuard;
6298
6299        let raw = null_metadata_raw(0);
6300        let guard = unsafe { RecvMetadataGuard::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
6301        let captured = MetadataFrameRef::new(guard).unwrap();
6302        let source: &dyn MetadataSource = &captured;
6303        let outgoing = source.metadata_raw();
6304        assert_eq!(outgoing.length, 1);
6305        assert_eq!(outgoing.timecode, raw.timecode);
6306        assert!(!outgoing.p_data.is_null());
6307        assert_eq!(unsafe { CStr::from_ptr(outgoing.p_data) }, c"");
6308        assert_eq!(source.to_owned().data(), "");
6309    }
6310
6311    #[test]
6312    fn metadata_sdk_length_uses_the_validated_metadata_bound() {
6313        assert_eq!(MetadataText::EMPTY.sdk_len(), 1);
6314        assert_eq!(
6315            MetadataText::from_cstr(&CString::new("x".repeat(MAX_METADATA_BYTES - 1)).unwrap())
6316                .unwrap()
6317                .sdk_len(),
6318            MAX_METADATA_BYTES as i32
6319        );
6320        let text = "x".repeat(MAX_METADATA_BYTES);
6321        let error = MetadataFrame::new(text).unwrap_err().into_error();
6322        assert!(
6323            matches!(error, Error::InvalidFrame(crate::FrameDefect::MetadataTooLarge { length }) if length == MAX_METADATA_BYTES + 1)
6324        );
6325    }
6326
6327    #[test]
6328    fn test_metadata_frame_ref_uses_cached_layout() {
6329        use crate::capture::RecvMetadataGuard;
6330
6331        let mut data = b"zero-copy\0\0\xFF".to_vec();
6332        let raw = metadata_raw_from_bytes(&mut data, 10);
6333        let guard = unsafe { RecvMetadataGuard::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
6334        let frame_ref = MetadataFrameRef::new(guard).expect("valid metadata ref");
6335
6336        assert_eq!(frame_ref.data(), "zero-copy");
6337        assert_eq!(frame_ref.as_bytes(), b"zero-copy");
6338        // The text is borrowed in place, with the length the SDK declared.
6339        assert_eq!(frame_ref.data().as_ptr(), data.as_ptr());
6340        assert_eq!(
6341            frame_ref.frame.metadata().map(MetadataText::len_with_nul),
6342            Some(10)
6343        );
6344
6345        assert_eq!(frame_ref.timecode(), Timecode::from_ticks(12345));
6346        let owned = frame_ref.to_owned();
6347        assert_eq!(owned.data(), "zero-copy");
6348        assert_eq!(owned.timecode(), Timecode::from_ticks(12345));
6349    }
6350
6351    #[test]
6352    fn test_empty_null_frame_and_empty_sentinel_both_read_as_empty() {
6353        use crate::capture::RecvMetadataGuard;
6354
6355        // The empty null frame is absent text: nothing is read from `p_data`.
6356        let raw = null_metadata_raw(0);
6357        let guard = unsafe { RecvMetadataGuard::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
6358        let frame_ref = MetadataFrameRef::new(guard).expect("empty null frame");
6359        assert!(frame_ref.frame.metadata().is_none());
6360        assert_eq!(frame_ref.data(), "");
6361        assert_eq!(frame_ref.as_bytes(), b"");
6362        let owned = frame_ref.to_owned();
6363        assert_eq!(owned.data(), "");
6364        assert_eq!(owned.timecode(), Timecode::from_ticks(12345));
6365        assert_eq!(owned.data.terminated_bytes(), b"\0");
6366
6367        // A zero length with a non-null empty C string is present, empty text.
6368        let mut data = b"\0ignored".to_vec();
6369        let raw = metadata_raw_from_bytes(&mut data, 0);
6370        let guard = unsafe { RecvMetadataGuard::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
6371        let frame_ref = MetadataFrameRef::new(guard).expect("empty C-string sentinel");
6372        assert_eq!(
6373            frame_ref.frame.metadata().map(MetadataText::len_with_nul),
6374            Some(1)
6375        );
6376        assert_eq!(frame_ref.data(), "");
6377        assert_eq!(frame_ref.as_bytes(), b"");
6378        assert_eq!(frame_ref.to_owned().data(), "");
6379    }
6380
6381    #[test]
6382    fn test_validate_frame_metadata_accepts_null_without_allocation_state() {
6383        let layout = unsafe { validate_frame_metadata(ptr::null()) }.expect("null is valid");
6384
6385        assert!(layout.is_none());
6386    }
6387
6388    #[test]
6389    fn test_validate_frame_metadata_accepts_explicit_empty() {
6390        let mut data = b"\0".to_vec();
6391        let layout = unsafe { validate_frame_metadata(data.as_mut_ptr().cast::<c_char>()) }
6392            .expect("explicit empty metadata is valid");
6393
6394        let text = layout.expect("explicit empty text");
6395        assert_eq!(text.as_str(), "");
6396        assert_eq!(text.as_ptr(), data.as_ptr().cast::<c_char>());
6397    }
6398
6399    #[test]
6400    fn test_validate_frame_metadata_accepts_utf8_and_ignores_after_first_nul() {
6401        let mut data = b"hello metadata\0\0\xFF".to_vec();
6402        let layout = unsafe { validate_frame_metadata(data.as_mut_ptr().cast::<c_char>()) }
6403            .expect("valid UTF-8 metadata");
6404
6405        let text = layout.expect("text");
6406        assert_eq!(text.as_str(), "hello metadata");
6407        assert_eq!(text.len_with_nul(), "hello metadata".len() + 1);
6408        assert_eq!(text.as_ptr(), data.as_ptr().cast::<c_char>());
6409    }
6410
6411    #[test]
6412    fn test_validate_frame_metadata_accepts_max_boundary() {
6413        let mut data = vec![b'x'; MAX_METADATA_BYTES];
6414        data[MAX_METADATA_BYTES - 1] = 0;
6415
6416        let layout = unsafe { validate_frame_metadata(data.as_mut_ptr().cast::<c_char>()) }
6417            .expect("metadata exactly at cap including terminator is valid");
6418
6419        // Exactly `MAX_METADATA_BYTES` including the terminator.
6420        assert_eq!(
6421            layout.map(MetadataText::len_with_nul),
6422            Some(MAX_METADATA_BYTES)
6423        );
6424    }
6425
6426    #[test]
6427    fn test_validate_frame_metadata_rejects_missing_nul_within_cap() {
6428        let mut data = vec![b'x'; MAX_METADATA_BYTES];
6429
6430        assert!(matches!(
6431            unsafe { validate_frame_metadata(data.as_mut_ptr().cast::<c_char>()) },
6432            Err(Error::InvalidFrame(_))
6433        ));
6434    }
6435
6436    #[test]
6437    fn test_validate_frame_metadata_rejects_invalid_utf8_before_nul() {
6438        let mut data = vec![0xFF, 0];
6439
6440        assert!(matches!(
6441            unsafe { validate_frame_metadata(data.as_mut_ptr().cast::<c_char>()) },
6442            Err(Error::InvalidUtf8(_))
6443        ));
6444    }
6445
6446    #[test]
6447    fn test_video_frame_ref_metadata_is_cached_and_owned_conversion_appends_nul() {
6448        use crate::capture::{Guard, VideoKind};
6449
6450        let width = 16;
6451        let height = 8;
6452        let stride = width * 4;
6453        let expected_len = (stride * height) as usize;
6454        let data = vec![0u8; expected_len];
6455        let mut metadata = b"cached\0\xFF".to_vec();
6456
6457        let raw = NDIlib_video_frame_v2_t {
6458            xres: width,
6459            yres: height,
6460            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
6461            frame_rate_N: 60,
6462            frame_rate_D: 1,
6463            picture_aspect_ratio: 16.0 / 9.0,
6464            frame_format_type: ScanType::Progressive.to_sdk(),
6465            timecode: 123,
6466            p_data: data.as_ptr() as *mut u8,
6467            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
6468                line_stride_in_bytes: stride,
6469            },
6470            p_metadata: metadata.as_mut_ptr().cast::<c_char>(),
6471            timestamp: 456,
6472        };
6473
6474        let guard = unsafe { Guard::<VideoKind>::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
6475        let frame_ref = VideoFrameRef::new(guard).expect("valid video ref");
6476
6477        assert_eq!(frame_ref.metadata(), Some("cached"));
6478        metadata[6] = b'!';
6479        assert_eq!(frame_ref.metadata(), Some("cached"));
6480        assert!(format!("{frame_ref:?}").contains("metadata: Some(\"cached\")"));
6481
6482        let owned = frame_ref.to_owned();
6483        assert_eq!(owned.metadata(), Some("cached"));
6484        assert_eq!(owned.data().len(), expected_len);
6485        assert_eq!(owned.timecode(), Timecode::from_ticks(123));
6486        assert_eq!(owned.timestamp(), ReceivedTimestamp::from_sdk(456));
6487    }
6488
6489    #[test]
6490    fn test_audio_frame_ref_metadata_is_text_and_owned_conversion_preserves_it() {
6491        let no_samples = 4;
6492        let no_channels = 2;
6493        let sample_count = (no_samples * no_channels) as usize;
6494        let data = vec![0.25f32; sample_count];
6495        let mut metadata = b"audio meta\0".to_vec();
6496
6497        let raw = NDIlib_audio_frame_v3_t {
6498            sample_rate: 48000,
6499            no_channels,
6500            no_samples,
6501            timecode: 123,
6502            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
6503            p_data: data.as_ptr() as *mut u8,
6504            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
6505                channel_stride_in_bytes: no_samples * 4,
6506            },
6507            p_metadata: metadata.as_mut_ptr().cast::<c_char>(),
6508            timestamp: 456,
6509        };
6510
6511        let guard = unsafe { Guard::<AudioKind>::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
6512        let frame_ref = AudioFrameRef::new(guard).expect("valid audio ref");
6513
6514        assert_eq!(frame_ref.metadata(), Some("audio meta"));
6515        assert_eq!(frame_ref.timecode(), Timecode::from_ticks(123));
6516        assert_eq!(frame_ref.timestamp(), ReceivedTimestamp::from_sdk(456));
6517        let owned = frame_ref.to_owned();
6518        assert_eq!(owned.metadata(), Some("audio meta"));
6519        assert_eq!(owned.data().len(), sample_count);
6520        assert_eq!(owned.timecode(), Timecode::from_ticks(123));
6521        assert_eq!(owned.timestamp(), ReceivedTimestamp::from_sdk(456));
6522    }
6523
6524    #[test]
6525    fn test_owned_video_from_raw_omits_malformed_frame_metadata() {
6526        let width = 16;
6527        let height = 8;
6528        let stride = width * 4;
6529        let expected_len = (stride * height) as usize;
6530        let mut data = vec![0u8; expected_len];
6531        let mut metadata = vec![b'x'; MAX_METADATA_BYTES];
6532
6533        let raw = NDIlib_video_frame_v2_t {
6534            xres: width,
6535            yres: height,
6536            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
6537            frame_rate_N: 60,
6538            frame_rate_D: 1,
6539            picture_aspect_ratio: 16.0 / 9.0,
6540            frame_format_type: ScanType::Progressive.to_sdk(),
6541            timecode: 0,
6542            p_data: data.as_mut_ptr(),
6543            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
6544                line_stride_in_bytes: stride,
6545            },
6546            p_metadata: metadata.as_mut_ptr().cast::<c_char>(),
6547            timestamp: 0,
6548        };
6549
6550        let frame = unsafe { VideoFrame::from_raw(&raw) }.unwrap();
6551        assert_eq!(frame.metadata(), None);
6552        assert_eq!(frame.data(), data);
6553        assert!(frame.as_test_raw().p_metadata.is_null());
6554
6555        metadata[0] = 0xFF;
6556        metadata[1] = 0;
6557        let frame = unsafe { VideoFrame::from_raw(&raw) }.unwrap();
6558        assert_eq!(frame.metadata(), None);
6559        assert_eq!(frame.data(), data);
6560        assert!(frame.as_test_raw().p_metadata.is_null());
6561    }
6562
6563    #[test]
6564    fn test_owned_frame_metadata_builders_setters_and_raw_conversion() {
6565        let mut video = VideoFrame::builder().metadata("").build().unwrap();
6566        assert_eq!(video.metadata(), Some(""));
6567        let raw = video.as_test_raw();
6568        assert!(!raw.p_metadata.is_null());
6569        assert_eq!(
6570            unsafe { slice::from_raw_parts(raw.p_metadata.cast::<u8>(), 1) },
6571            b"\0"
6572        );
6573
6574        video.set_metadata("video meta").unwrap();
6575        assert_eq!(video.metadata(), Some("video meta"));
6576        let raw = video.as_test_raw();
6577        assert_eq!(
6578            unsafe { slice::from_raw_parts(raw.p_metadata.cast::<u8>(), 11) },
6579            b"video meta\0"
6580        );
6581
6582        video.clear_metadata();
6583        assert!(video.metadata().is_none());
6584        assert!(video.as_test_raw().p_metadata.is_null());
6585
6586        let mut audio = AudioFrame::builder().metadata("").build().unwrap();
6587        assert_eq!(audio.metadata(), Some(""));
6588        assert!(!audio.audio_descriptor().p_metadata.is_null());
6589        audio.set_metadata("audio meta").unwrap();
6590        assert_eq!(audio.metadata(), Some("audio meta"));
6591
6592        assert!(matches!(
6593            VideoFrame::builder()
6594                .metadata("bad\0metadata")
6595                .build()
6596                .map_err(Rejected::into_error),
6597            Err(Error::InvalidCString(_))
6598        ));
6599        assert!(matches!(
6600            AudioFrame::builder()
6601                .metadata("bad\0metadata")
6602                .build()
6603                .map_err(Rejected::into_error),
6604            Err(Error::InvalidCString(_))
6605        ));
6606        video.set_metadata("preserved video").unwrap();
6607        assert!(matches!(
6608            video
6609                .set_metadata("bad\0metadata")
6610                .map_err(Rejected::into_error),
6611            Err(Error::InvalidCString(_))
6612        ));
6613        assert!(matches!(
6614            audio
6615                .set_metadata("bad\0metadata")
6616                .map_err(Rejected::into_error),
6617            Err(Error::InvalidCString(_))
6618        ));
6619
6620        assert_eq!(video.metadata(), Some("preserved video"));
6621        assert_eq!(audio.metadata(), Some("audio meta"));
6622        let oversized = "x".repeat(MAX_METADATA_BYTES);
6623        assert!(matches!(
6624            VideoFrame::builder()
6625                .metadata(oversized.clone())
6626                .build()
6627                .map_err(Rejected::into_error),
6628            Err(Error::InvalidFrame(_))
6629        ));
6630        assert!(matches!(
6631            AudioFrame::builder()
6632                .metadata(oversized.clone())
6633                .build()
6634                .map_err(Rejected::into_error),
6635            Err(Error::InvalidFrame(_))
6636        ));
6637        assert!(matches!(
6638            video
6639                .set_metadata(oversized.clone())
6640                .map_err(Rejected::into_error),
6641            Err(Error::InvalidFrame(_))
6642        ));
6643        assert!(matches!(
6644            audio.set_metadata(oversized).map_err(Rejected::into_error),
6645            Err(Error::InvalidFrame(_))
6646        ));
6647        assert_eq!(video.metadata(), Some("preserved video"));
6648        assert_eq!(audio.metadata(), Some("audio meta"));
6649        // Clearing an already empty frame is also infallible.
6650        for _ in 0..2 {
6651            video.clear_metadata();
6652            audio.clear_metadata();
6653            assert_eq!(video.metadata(), None);
6654            assert_eq!(audio.metadata(), None);
6655            assert!(video.as_test_raw().p_metadata.is_null());
6656            assert!(audio.audio_descriptor().p_metadata.is_null());
6657        }
6658    }
6659
6660    #[test]
6661    fn oversized_layouts_have_one_size_cause_on_every_target() {
6662        for samples in [1 << 25, 1 << 29, 1 << 30] {
6663            let expected = crate::LayoutDefect::AudioBytes((u64::from(samples) * 2 * 4).into());
6664            assert!(matches!(
6665                AudioFrame::builder().num_samples(samples).build().map_err(crate::Rejected::into_error),
6666                Err(Error::InvalidFrame(crate::FrameDefect::Layout(cause))) if cause == expected
6667            ));
6668            assert!(matches!(
6669                crate::FrameSyncAudioRequest::capture_at(48_000, 2, samples),
6670                Err(Error::InvalidInput(crate::InputDefect::Layout(cause))) if cause == expected
6671            ));
6672        }
6673        for (width, height, bytes) in [
6674            (1 << 31, 2, 17_179_869_184u64),
6675            (1 << 31, 1 << 31, u64::MAX),
6676            (1 << 14, 1 << 18, 17_179_869_184),
6677        ] {
6678            let expected = crate::LayoutDefect::VideoBytes(bytes.into());
6679            assert!(matches!(
6680                VideoFrame::builder().resolution(width, height).build().map_err(crate::Rejected::into_error),
6681                Err(Error::InvalidFrame(crate::FrameDefect::Layout(cause))) if cause == expected
6682            ));
6683            assert!(matches!(
6684                PixelFormat::Bgra.buffer_len(width, height, None),
6685                Err(Error::InvalidFrame(crate::FrameDefect::Layout(cause))) if cause == expected
6686            ));
6687        }
6688        for (width, bytes) in [(400_000_000, 1_600_000_000u64), (1 << 30, 4_294_967_296)] {
6689            assert!(matches!(
6690                PixelFormat::Bgra.line_stride_bytes(width),
6691                Err(Error::InvalidFrame(crate::FrameDefect::Layout(crate::LayoutDefect::VideoBytes(n))))
6692                    if n.get() == bytes
6693            ));
6694        }
6695    }
6696
6697    /// Test that audio frames with overflow in checked_mul are rejected
6698    #[test]
6699    fn test_audio_overflow_checked_mul() {
6700        // Use an extreme channel count to exceed the maximum backing buffer size.
6701        let no_samples = 1024;
6702        let no_channels = i32::MAX;
6703        let mut dummy_data = vec![0f32; 1024]; // Small buffer, won't be used due to guard
6704
6705        let raw = NDIlib_audio_frame_v3_t {
6706            sample_rate: 48000,
6707            no_channels,
6708            no_samples,
6709            timecode: 0,
6710            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
6711            p_data: dummy_data.as_mut_ptr() as *mut u8,
6712            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
6713                channel_stride_in_bytes: no_samples * 4,
6714            },
6715            p_metadata: ptr::null(),
6716            timestamp: 0,
6717        };
6718
6719        let result = unsafe { AudioFrame::from_raw(raw) };
6720        assert!(
6721            result.is_err(),
6722            "Should reject audio frame with sample count overflow or exceeding size limit"
6723        );
6724
6725        let expected = crate::LayoutDefect::AudioBytes(8_796_093_018_112u64.into());
6726        assert!(matches!(
6727            result,
6728            Err(Error::InvalidFrame(crate::FrameDefect::Layout(cause))) if cause == expected
6729        ));
6730    }
6731
6732    /// Test that normal audio frames within bounds succeed
6733    #[test]
6734    fn test_audio_within_bounds_succeeds() {
6735        // Typical audio frame: 48kHz, 2 channels, 1024 samples
6736        let sample_rate = 48000;
6737        let no_channels = 2;
6738        let no_samples = 1024;
6739        let sample_count = (no_samples * no_channels) as usize;
6740        let mut data = vec![0.5f32; sample_count];
6741
6742        let raw = NDIlib_audio_frame_v3_t {
6743            sample_rate,
6744            no_channels,
6745            no_samples,
6746            timecode: 12345,
6747            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
6748            p_data: data.as_mut_ptr() as *mut u8,
6749            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
6750                channel_stride_in_bytes: no_samples * 4,
6751            },
6752            p_metadata: ptr::null(),
6753            timestamp: 67890,
6754        };
6755
6756        let result = unsafe { AudioFrame::from_raw(raw) };
6757        assert!(
6758            result.is_ok(),
6759            "Should accept normal audio frame within bounds"
6760        );
6761
6762        let frame = result.unwrap();
6763        assert_eq!(frame.data().len(), sample_count);
6764        assert_eq!((frame.num_samples(), frame.num_channels()), (1024, 2));
6765        assert_eq!(frame.sample_rate(), 48_000);
6766        assert_eq!(frame.timestamp(), ReceivedTimestamp::from_sdk(67890));
6767    }
6768
6769    #[test]
6770    fn builder_and_view_debug_summarizes_storage_and_remaining_extents() {
6771        fn summaries(width: u32, height: u32, samples: u32) -> Vec<String> {
6772            let pixels = vec![7; width as usize * height as usize * 4];
6773            let audio = vec![0.25; samples as usize * 2];
6774            let frame = VideoFrame::builder()
6775                .resolution(width, height)
6776                .pixel_format(PixelFormat::Nv12)
6777                .build()
6778                .unwrap();
6779            let plane = frame.planes().next().unwrap();
6780            let audio_frame = AudioFrame::builder()
6781                .num_channels(2)
6782                .num_samples(samples)
6783                .build()
6784                .unwrap();
6785            vec![
6786                format!(
6787                    "{:?}",
6788                    VideoFrame::builder()
6789                        .resolution(width, height)
6790                        .data(pixels.clone())
6791                        .metadata("<x/>")
6792                ),
6793                format!(
6794                    "{:?}",
6795                    crate::BorrowedVideoFrame::builder(&pixels, width, height, PixelFormat::Bgra)
6796                        .metadata(c"<x/>")
6797                ),
6798                format!(
6799                    "{:?}",
6800                    AudioFrame::builder()
6801                        .num_channels(2)
6802                        .num_samples(samples)
6803                        .data(audio.clone())
6804                        .metadata("<x/>")
6805                ),
6806                format!(
6807                    "{:?}",
6808                    BorrowedAudioFrame::builder(&audio, 48_000, 2, samples).metadata(c"<x/>")
6809                ),
6810                format!("{plane:?}"),
6811                format!("{:?}", plane.rows()),
6812                format!("{:?}", frame.planes()),
6813                format!("{:?}", audio_frame.channels()),
6814                format!("{audio_frame:?}"),
6815                format!(
6816                    "{:?}",
6817                    BorrowedAudioFrame::builder(&audio, 48_000, 2, samples)
6818                        .build()
6819                        .unwrap()
6820                ),
6821            ]
6822        }
6823        crate::test_support::assert_bounded_debug(
6824            &summaries(4, 2, 3),
6825            &summaries(1920, 1080, 48_000),
6826        );
6827        assert!(format!("{:?}", VideoFrame::builder()).contains("data (bytes): None"));
6828        assert!(format!("{:?}", AudioFrame::builder()).contains("data (samples): None"));
6829        let frame = VideoFrame::builder()
6830            .resolution(4, 2)
6831            .pixel_format(PixelFormat::Nv12)
6832            .build()
6833            .unwrap();
6834        let mut planes = frame.planes();
6835        let plane = planes.next().unwrap();
6836        assert!(format!("{planes:?}").contains("remaining_planes: 1"));
6837        let mut rows = plane.rows();
6838        rows.next();
6839        assert!(format!("{rows:?}").contains("remaining_rows: 1"));
6840        let audio = AudioFrame::builder()
6841            .num_channels(2)
6842            .num_samples(3)
6843            .build()
6844            .unwrap();
6845        let mut channels = audio.channels();
6846        channels.next();
6847        assert!(format!("{channels:?}").contains("remaining_channels: 1"));
6848    }
6849
6850    #[test]
6851    fn owned_metadata_debug_uses_the_borrowed_frame_fields() {
6852        let frame = MetadataFrame::new("<x/>")
6853            .unwrap()
6854            .with_timecode(Timecode::from_ticks(42));
6855        assert_eq!(
6856            format!("{frame:?}"),
6857            "MetadataFrame { data: \"<x/>\", data (bytes): 4, timecode: Timecode(42) }"
6858        );
6859    }
6860
6861    #[test]
6862    fn captured_audio_debug_reports_active_samples_without_padding() {
6863        let samples = [0.0f32; 11];
6864        let raw = NDIlib_audio_frame_v3_t {
6865            sample_rate: 48_000,
6866            no_channels: 2,
6867            no_samples: 3,
6868            FourCC: FourCc::from(AudioFormat::Fltp).raw(),
6869            p_data: samples.as_ptr().cast_mut().cast(),
6870            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
6871                channel_stride_in_bytes: 32,
6872            },
6873            ..Default::default()
6874        };
6875        // SAFETY: the synthetic guard retains the initialized sample array;
6876        // the test free callback does not own or release it.
6877        let guard = unsafe { Guard::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
6878        let frame = AudioFrameRef::new(guard).unwrap();
6879        let debug = format!("{frame:?}");
6880        assert!(debug.contains("num_samples: 3"));
6881        assert!(debug.contains("active data (samples): 6"));
6882        assert!(!debug.contains("samples per channel"));
6883    }
6884
6885    #[test]
6886    fn audio_frame_debug_lists_the_borrowed_frame_fields_not_samples() {
6887        let frame = AudioFrame::builder()
6888            .num_channels(2)
6889            .num_samples(3)
6890            .timecode(Timecode::from_ticks(5))
6891            .metadata("<audio/>")
6892            .build()
6893            .unwrap();
6894        assert_eq!(
6895            format!("{frame:?}"),
6896            "AudioFrame { sample_rate: 48000, num_channels: 2, num_samples: 3, \
6897             timecode: Timecode(5), format: Fltp, data (samples): 6, \
6898             channel_stride_bytes: 12, metadata: Some(\"<audio/>\"), timestamp: None }"
6899        );
6900    }
6901
6902    #[test]
6903    fn test_audio_builder_rejects_invalid_dimensions() {
6904        assert!(matches!(
6905            AudioFrame::builder()
6906                .sample_rate(0)
6907                .build()
6908                .map_err(Rejected::into_error),
6909            Err(Error::InvalidFrame(_))
6910        ));
6911        assert!(matches!(
6912            AudioFrame::builder()
6913                .sample_rate(1 << 31)
6914                .build()
6915                .map_err(Rejected::into_error),
6916            Err(Error::InvalidFrame(_))
6917        ));
6918        assert!(matches!(
6919            AudioFrame::builder()
6920                .num_channels(0)
6921                .build()
6922                .map_err(Rejected::into_error),
6923            Err(Error::InvalidFrame(_))
6924        ));
6925        assert!(matches!(
6926            AudioFrame::builder()
6927                .num_samples(0)
6928                .build()
6929                .map_err(Rejected::into_error),
6930            Err(Error::InvalidFrame(_))
6931        ));
6932        assert!(matches!(
6933            AudioFrame::builder()
6934                .num_samples(u32::MAX)
6935                .build()
6936                .map_err(Rejected::into_error),
6937            Err(Error::InvalidFrame(_))
6938        ));
6939    }
6940
6941    #[test]
6942    fn test_audio_builder_rejects_oversized_layout() {
6943        let samples = (MAX_AUDIO_BYTES / std::mem::size_of::<f32>()) as u32 + 1;
6944        let result = AudioFrame::builder()
6945            .num_channels(1)
6946            .num_samples(samples)
6947            .build()
6948            .map_err(Rejected::into_error);
6949
6950        assert!(matches!(result, Err(Error::InvalidFrame(_))));
6951    }
6952
6953    #[test]
6954    fn test_default_outbound_timecodes_are_synthesized() {
6955        let video = VideoFrame::builder().resolution(16, 16).build().unwrap();
6956        assert_eq!(video.timecode(), Timecode::SYNTHESIZE);
6957        assert_eq!(
6958            video.as_test_raw().timecode,
6959            NDIlib_send_timecode_synthesize
6960        );
6961        let audio = AudioFrame::builder().num_samples(1).build().unwrap();
6962        assert_eq!(audio.timecode(), Timecode::SYNTHESIZE);
6963        assert_eq!(
6964            audio.audio_descriptor().timecode,
6965            NDIlib_send_timecode_synthesize
6966        );
6967        assert_eq!(
6968            MetadataFrame::new("<x/>").unwrap().timecode(),
6969            Timecode::SYNTHESIZE
6970        );
6971        let zero = Timecode::from_ticks(0);
6972        assert_eq!(
6973            VideoFrame::builder()
6974                .resolution(16, 16)
6975                .timecode(zero)
6976                .build()
6977                .unwrap()
6978                .as_test_raw()
6979                .timecode,
6980            0
6981        );
6982        assert_eq!(
6983            AudioFrame::builder()
6984                .num_samples(1)
6985                .timecode(zero)
6986                .build()
6987                .unwrap()
6988                .audio_descriptor()
6989                .timecode,
6990            0
6991        );
6992        assert_eq!(
6993            MetadataFrame::new("<x/>")
6994                .unwrap()
6995                .with_timecode(zero)
6996                .metadata_raw()
6997                .timecode,
6998            0
6999        );
7000    }
7001
7002    #[test]
7003    fn invalid_send_metadata_is_rejected_at_value_construction() {
7004        assert!(matches!(FrameRate::new(0, 1), Err(Error::InvalidInput(_))));
7005        assert!(matches!(FrameRate::new(30, 0), Err(Error::InvalidInput(_))));
7006        for ratio in [-1.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
7007            assert!(matches!(
7008                PictureAspectRatio::new(ratio),
7009                Err(Error::InvalidInput(_))
7010            ));
7011        }
7012    }
7013
7014    #[test]
7015    fn video_aspect_defaults_follow_dimensions_and_override_order_is_independent() {
7016        for (width, height) in [(640, 480), (1920, 1080), (1080, 1920), (64, 64)] {
7017            let frame = VideoFrame::builder()
7018                .resolution(width, height)
7019                .build()
7020                .unwrap();
7021            assert_eq!(frame.picture_aspect_ratio().get(), 0.0);
7022            assert_eq!(frame.as_test_raw().picture_aspect_ratio, 0.0);
7023            for builder in [
7024                VideoFrame::builder()
7025                    .picture_aspect_ratio(crate::PictureAspectRatio::new(1.25).unwrap())
7026                    .resolution(width, height),
7027                VideoFrame::builder()
7028                    .resolution(width, height)
7029                    .picture_aspect_ratio(crate::PictureAspectRatio::new(1.25).unwrap()),
7030            ] {
7031                let frame = builder.build().unwrap();
7032                assert_eq!(frame.picture_aspect_ratio().get(), 1.25);
7033                assert_eq!(frame.as_test_raw().picture_aspect_ratio, 1.25);
7034            }
7035        }
7036        for ratio in [0.0, 1.25] {
7037            let frame = VideoFrame::builder()
7038                .resolution(16, 16)
7039                .picture_aspect_ratio(crate::PictureAspectRatio::new(ratio).unwrap())
7040                .build()
7041                .unwrap();
7042            let raw = frame.as_test_raw();
7043            // SAFETY: `raw` borrows this live owned frame's initialized pixels.
7044            let captured = unsafe { ValidatedVideo::video_descriptor(&raw).unwrap() };
7045            let mut copy = captured.owned_copy();
7046            assert_eq!(copy.picture_aspect_ratio().get(), ratio);
7047            copy.set_picture_aspect_ratio(crate::PictureAspectRatio::new(2.0).unwrap());
7048            captured.copy_into_owned(&mut copy);
7049            assert_eq!(copy.as_test_raw().picture_aspect_ratio, ratio);
7050        }
7051    }
7052
7053    #[test]
7054    fn test_owned_frame_data_replacement_preserves_layout_size() {
7055        let mut video = VideoFrame::builder()
7056            .resolution(16, 16)
7057            .pixel_format(PixelFormat::Bgra)
7058            .build()
7059            .unwrap();
7060        let pixels = video.data().as_ptr();
7061        let rejected = video
7062            .replace_data(vec![0; video.data().len() - 1])
7063            .unwrap_err();
7064        assert!(matches!(rejected.error(), Error::InvalidFrame(_)));
7065        assert_eq!(rejected.into_inner().len(), 16 * 16 * 4 - 1);
7066        assert_eq!(video.data().as_ptr(), pixels);
7067        video.replace_data(vec![5; 16 * 16 * 4]).unwrap();
7068        assert_eq!(video.data(), vec![5; 16 * 16 * 4]);
7069
7070        let mut audio = AudioFrame::builder()
7071            .num_channels(2)
7072            .num_samples(16)
7073            .build()
7074            .unwrap();
7075        let rejected = audio
7076            .replace_data(vec![0.0; audio.data().len() + 1])
7077            .unwrap_err();
7078        assert!(matches!(rejected.error(), Error::InvalidFrame(_)));
7079        assert_eq!(rejected.into_inner().len(), 33);
7080        audio.replace_data(vec![0.5; 32]).unwrap();
7081        assert_eq!(audio.channel_data(1), Some(&[0.5; 16][..]));
7082    }
7083
7084    #[test]
7085    fn test_video_cap_allows_8k_bgra_without_allocating() {
7086        let layout =
7087            ValidatedVideoLayout::new_uncompressed(PixelFormat::Bgra, 7680, 4320, None).unwrap();
7088        assert_eq!(layout.data_len_bytes(), 132_710_400);
7089        assert!(matches!(
7090            ValidatedVideoLayout::new_uncompressed(PixelFormat::Bgra, 16_384, 8_640, None),
7091            Err(Error::InvalidFrame(_))
7092        ));
7093    }
7094
7095    // =========================================================================
7096    // Tests for frame layout validation helpers
7097    // =========================================================================
7098
7099    /// Test validate_video_layout with valid uncompressed frame
7100    #[test]
7101    fn test_validate_video_layout_valid_uncompressed() {
7102        let width = 1920;
7103        let height = 1080;
7104        let stride = width * 4; // BGRA
7105        let expected_size = (stride * height) as usize;
7106        let mut data = vec![0u8; expected_size];
7107
7108        let raw = NDIlib_video_frame_v2_t {
7109            xres: width,
7110            yres: height,
7111            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
7112            frame_rate_N: 60,
7113            frame_rate_D: 1,
7114            picture_aspect_ratio: 16.0 / 9.0,
7115            frame_format_type: ScanType::Progressive.to_sdk(),
7116            timecode: 0,
7117            p_data: data.as_mut_ptr(),
7118            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
7119                line_stride_in_bytes: stride,
7120            },
7121            p_metadata: ptr::null(),
7122            timestamp: 0,
7123        };
7124
7125        let result = validate_video_layout(&raw);
7126        assert!(result.is_ok(), "Should validate valid uncompressed frame");
7127
7128        let layout = result.unwrap();
7129        assert_eq!(layout.pixel_format(), PixelFormat::Bgra);
7130        assert_eq!(layout.data_len_bytes(), expected_size);
7131        assert_eq!(layout.sdk_line_stride(), stride);
7132        assert_eq!(layout.line_stride_bytes(), stride as usize);
7133    }
7134
7135    /// Test validate_video_layout accepts the first-plane strides the SDK
7136    /// delivers for UYVA, P216 and PA16
7137    #[test]
7138    fn test_validate_video_layout_semi_planar_422_and_alpha() {
7139        let width = 256;
7140        let height = 64;
7141        let stride = width * 2;
7142        let plane = (stride * height) as usize;
7143
7144        for (format, expected_size) in [
7145            (PixelFormat::Uyva, plane + plane / 2),
7146            (PixelFormat::P216, plane * 2),
7147            (PixelFormat::Pa16, plane * 3),
7148        ] {
7149            let mut data = vec![0u8; expected_size];
7150
7151            let raw = NDIlib_video_frame_v2_t {
7152                xres: width,
7153                yres: height,
7154                FourCC: FourCc::from(format).raw(),
7155                frame_rate_N: 60,
7156                frame_rate_D: 1,
7157                picture_aspect_ratio: 16.0 / 9.0,
7158                frame_format_type: ScanType::Progressive.to_sdk(),
7159                timecode: 0,
7160                p_data: data.as_mut_ptr(),
7161                __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
7162                    line_stride_in_bytes: stride,
7163                },
7164                p_metadata: ptr::null(),
7165                timestamp: 0,
7166            };
7167
7168            let layout = validate_video_layout(&raw)
7169                .unwrap_or_else(|e| panic!("{format:?} stride {stride} rejected: {e}"));
7170            assert_eq!(layout.pixel_format(), format);
7171            assert_eq!(layout.data_len_bytes(), expected_size, "{format:?}");
7172            assert_eq!(layout.sdk_line_stride(), stride);
7173            assert_eq!(layout.line_stride_bytes(), stride as usize);
7174        }
7175    }
7176
7177    /// Test validate_video_layout rejects an odd UYVA stride, since the alpha
7178    /// plane stride is half the line stride
7179    #[test]
7180    fn test_validate_video_layout_rejects_odd_uyva_stride() {
7181        let width = 256;
7182        let height = 64;
7183        let stride = width * 2 + 1;
7184        let mut data = vec![0u8; (stride * height * 2) as usize];
7185
7186        let raw = NDIlib_video_frame_v2_t {
7187            xres: width,
7188            yres: height,
7189            FourCC: FourCc::from(PixelFormat::Uyva).raw(),
7190            frame_rate_N: 60,
7191            frame_rate_D: 1,
7192            picture_aspect_ratio: 16.0 / 9.0,
7193            frame_format_type: ScanType::Progressive.to_sdk(),
7194            timecode: 0,
7195            p_data: data.as_mut_ptr(),
7196            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
7197                line_stride_in_bytes: stride,
7198            },
7199            p_metadata: ptr::null(),
7200            timestamp: 0,
7201        };
7202
7203        assert!(matches!(
7204            validate_video_layout(&raw),
7205            Err(Error::InvalidFrame(_))
7206        ));
7207    }
7208
7209    /// Test validate_video_layout rejects null data pointer
7210    #[test]
7211    fn test_validate_video_layout_null_pointer() {
7212        let raw = NDIlib_video_frame_v2_t {
7213            xres: 1920,
7214            yres: 1080,
7215            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
7216            frame_rate_N: 60,
7217            frame_rate_D: 1,
7218            picture_aspect_ratio: 16.0 / 9.0,
7219            frame_format_type: ScanType::Progressive.to_sdk(),
7220            timecode: 0,
7221            p_data: ptr::null_mut(),
7222            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
7223                line_stride_in_bytes: 7680,
7224            },
7225            p_metadata: ptr::null(),
7226            timestamp: 0,
7227        };
7228
7229        let result = validate_video_layout(&raw);
7230        assert!(result.is_err(), "Should reject null data pointer");
7231
7232        if let Err(Error::InvalidFrame(msg)) = result {
7233            assert!(
7234                matches!(msg, crate::FrameDefect::NullVideoData),
7235                "Error should mention null pointer, got: {msg}"
7236            );
7237        } else {
7238            panic!("Expected InvalidFrame error");
7239        }
7240    }
7241
7242    /// Test validate_video_layout rejects invalid line_stride
7243    #[test]
7244    fn test_validate_video_layout_invalid_stride() {
7245        let mut data = vec![0u8; 1024];
7246
7247        let raw = NDIlib_video_frame_v2_t {
7248            xres: 1920,
7249            yres: 1080,
7250            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
7251            frame_rate_N: 60,
7252            frame_rate_D: 1,
7253            picture_aspect_ratio: 16.0 / 9.0,
7254            frame_format_type: ScanType::Progressive.to_sdk(),
7255            timecode: 0,
7256            p_data: data.as_mut_ptr(),
7257            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
7258                line_stride_in_bytes: -1, // Invalid stride
7259            },
7260            p_metadata: ptr::null(),
7261            timestamp: 0,
7262        };
7263
7264        let result = validate_video_layout(&raw);
7265        assert!(result.is_err(), "Should reject negative line_stride");
7266
7267        if let Err(Error::InvalidFrame(msg)) = result {
7268            assert!(
7269                matches!(
7270                    msg,
7271                    crate::FrameDefect::Layout(crate::LayoutDefect::VideoSdkStride(_))
7272                ),
7273                "Error should mention invalid stride, got: {msg}"
7274            );
7275        } else {
7276            panic!("Expected InvalidFrame error");
7277        }
7278    }
7279
7280    #[test]
7281    fn test_validate_video_layout_accepts_default_zero_stride() {
7282        let mut data = vec![0u8; 16 * 16 * 4];
7283        let raw = NDIlib_video_frame_v2_t {
7284            xres: 16,
7285            yres: 16,
7286            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
7287            frame_rate_N: 60,
7288            frame_rate_D: 1,
7289            picture_aspect_ratio: 1.0,
7290            frame_format_type: ScanType::Progressive.to_sdk(),
7291            timecode: 0,
7292            p_data: data.as_mut_ptr(),
7293            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
7294                line_stride_in_bytes: 0,
7295            },
7296            p_metadata: ptr::null(),
7297            timestamp: 0,
7298        };
7299        let layout = validate_video_layout(&raw).unwrap();
7300        assert_eq!(layout.data_len_bytes(), data.len());
7301        assert_eq!(layout.sdk_line_stride(), 64);
7302        assert_eq!(layout.line_stride_bytes(), 64);
7303        let owned = unsafe { VideoFrame::from_raw(&raw) }.unwrap();
7304        assert_eq!(owned.data().len(), data.len());
7305    }
7306
7307    /// Test validate_video_layout rejects strides smaller than one row.
7308    #[test]
7309    fn test_validate_video_layout_rejects_short_stride() {
7310        let mut data = vec![0u8; 1024];
7311
7312        let raw = NDIlib_video_frame_v2_t {
7313            xres: 1920,
7314            yres: 1080,
7315            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
7316            frame_rate_N: 60,
7317            frame_rate_D: 1,
7318            picture_aspect_ratio: 16.0 / 9.0,
7319            frame_format_type: ScanType::Progressive.to_sdk(),
7320            timecode: 0,
7321            p_data: data.as_mut_ptr(),
7322            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
7323                line_stride_in_bytes: 1919 * 4,
7324            },
7325            p_metadata: ptr::null(),
7326            timestamp: 0,
7327        };
7328
7329        let result = validate_video_layout(&raw);
7330        assert!(matches!(result, Err(Error::InvalidFrame(_))));
7331    }
7332
7333    /// Test validate_video_layout rejects odd dimensions for planar 4:2:0.
7334    #[test]
7335    fn test_validate_video_layout_rejects_planar_odd_dimensions() {
7336        let mut data = vec![0u8; 4096];
7337
7338        let raw = NDIlib_video_frame_v2_t {
7339            xres: 641,
7340            yres: 480,
7341            FourCC: FourCc::from(PixelFormat::I420).raw(),
7342            frame_rate_N: 60,
7343            frame_rate_D: 1,
7344            picture_aspect_ratio: 4.0 / 3.0,
7345            frame_format_type: ScanType::Progressive.to_sdk(),
7346            timecode: 0,
7347            p_data: data.as_mut_ptr(),
7348            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
7349                line_stride_in_bytes: 642,
7350            },
7351            p_metadata: ptr::null(),
7352            timestamp: 0,
7353        };
7354
7355        let result = validate_video_layout(&raw);
7356        assert!(matches!(result, Err(Error::InvalidFrame(_))));
7357    }
7358
7359    /// Test validate_video_layout rejects negative dimensions
7360    #[test]
7361    fn test_validate_video_layout_negative_dimensions() {
7362        let mut data = vec![0u8; 1024];
7363
7364        let raw = NDIlib_video_frame_v2_t {
7365            xres: 1920,
7366            yres: -1, // Negative height
7367            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
7368            frame_rate_N: 60,
7369            frame_rate_D: 1,
7370            picture_aspect_ratio: 16.0 / 9.0,
7371            frame_format_type: ScanType::Progressive.to_sdk(),
7372            timecode: 0,
7373            p_data: data.as_mut_ptr(),
7374            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
7375                line_stride_in_bytes: 7680,
7376            },
7377            p_metadata: ptr::null(),
7378            timestamp: 0,
7379        };
7380
7381        let result = validate_video_layout(&raw);
7382        assert!(result.is_err(), "Should reject negative height");
7383
7384        if let Err(Error::InvalidFrame(msg)) = result {
7385            assert!(
7386                matches!(
7387                    msg,
7388                    crate::FrameDefect::Layout(crate::LayoutDefect::VideoHeight(_))
7389                ),
7390                "Error should mention invalid height, got: {msg}"
7391            );
7392        } else {
7393            panic!("Expected InvalidFrame error");
7394        }
7395    }
7396
7397    /// Test validate_video_layout rejects oversized frames
7398    #[test]
7399    fn test_validate_video_layout_exceeds_max() {
7400        // Validation rejects before reading data, so no large allocation is needed.
7401        let width = 16_384;
7402        let height = 8_640;
7403        let stride = width * 4;
7404        let mut data = [0u8; 1];
7405
7406        let raw = NDIlib_video_frame_v2_t {
7407            xres: width,
7408            yres: height,
7409            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
7410            frame_rate_N: 60,
7411            frame_rate_D: 1,
7412            picture_aspect_ratio: 16.0 / 9.0,
7413            frame_format_type: ScanType::Progressive.to_sdk(),
7414            timecode: 0,
7415            p_data: data.as_mut_ptr(),
7416            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
7417                line_stride_in_bytes: stride,
7418            },
7419            p_metadata: ptr::null(),
7420            timestamp: 0,
7421        };
7422
7423        let result = validate_video_layout(&raw);
7424        assert!(result.is_err(), "Should reject oversized frame");
7425
7426        if let Err(Error::InvalidFrame(msg)) = result {
7427            assert!(
7428                matches!(
7429                    msg,
7430                    crate::FrameDefect::Layout(crate::LayoutDefect::VideoBytes(_))
7431                ),
7432                "Error should mention size limit, got: {msg}"
7433            );
7434        } else {
7435            panic!("Expected InvalidFrame error");
7436        }
7437    }
7438
7439    #[test]
7440    fn explicit_audio_stride_keeps_its_sdk_range_proof_for_one_channel() {
7441        let layout = ValidatedAudioLayout::new_uncompressed_checked(
7442            AudioFormat::Fltp,
7443            48_000,
7444            1,
7445            1,
7446            Some(1 << 30),
7447        )
7448        .unwrap();
7449        assert_eq!(layout.sample_count(), 1);
7450        assert_eq!(layout.channel_stride_bytes(), 1 << 30);
7451        assert_eq!(layout.sdk_channel_stride(), 1 << 30);
7452        assert_ne!(
7453            layout.channel_stride_bytes(),
7454            layout.packed().as_layout().channel_stride_bytes()
7455        );
7456        assert_eq!(
7457            ValidatedAudioLayout::new_uncompressed_checked(
7458                AudioFormat::Fltp,
7459                48_000,
7460                1,
7461                1,
7462                Some(i32::MAX as usize + 1),
7463            ),
7464            Err(crate::LayoutDefect::AudioStrideRange)
7465        );
7466        assert_eq!(
7467            ValidatedAudioLayout::new_uncompressed_checked(
7468                AudioFormat::Fltp,
7469                48_000,
7470                1,
7471                1,
7472                Some(0),
7473            ),
7474            Err(crate::LayoutDefect::AudioStride(0.into()))
7475        );
7476    }
7477
7478    #[test]
7479    fn an_explicit_packed_audio_stride_has_the_same_identity_as_implicit() {
7480        let implicit =
7481            ValidatedAudioLayout::new_uncompressed_checked(AudioFormat::Fltp, 48_000, 2, 4, None)
7482                .unwrap();
7483        let explicit = ValidatedAudioLayout::new_uncompressed_checked(
7484            AudioFormat::Fltp,
7485            48_000,
7486            2,
7487            4,
7488            Some(16),
7489        )
7490        .unwrap();
7491        assert_eq!(implicit, explicit);
7492        assert_eq!(&implicit, explicit.packed().as_layout());
7493        assert_eq!(
7494            explicit.channel_stride_bytes(),
7495            explicit.packed().as_layout().channel_stride_bytes()
7496        );
7497    }
7498
7499    /// Test validate_audio_layout with valid frame
7500    #[test]
7501    fn test_validate_audio_layout_valid() {
7502        let no_samples = 1024;
7503        let no_channels = 2;
7504        let sample_count = (no_samples * no_channels) as usize;
7505        let mut data = vec![0.0f32; sample_count];
7506
7507        let raw = NDIlib_audio_frame_v3_t {
7508            sample_rate: 48000,
7509            no_channels,
7510            no_samples,
7511            timecode: 0,
7512            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7513            p_data: data.as_mut_ptr() as *mut u8,
7514            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
7515                channel_stride_in_bytes: no_samples * 4,
7516            },
7517            p_metadata: ptr::null(),
7518            timestamp: 0,
7519        };
7520
7521        let result = validate_audio_layout(&raw);
7522        assert!(result.is_ok(), "Should validate valid audio frame");
7523
7524        let layout = result.unwrap();
7525        assert_eq!(layout.format(), AudioFormat::Fltp);
7526        assert_eq!(layout.sample_count(), sample_count);
7527    }
7528
7529    #[test]
7530    fn test_audio_channel_views_and_owned_conversion_skip_padding() {
7531        use crate::capture::FrameSyncAudioFree;
7532        use std::mem::MaybeUninit;
7533        // Only samples are initialized; gap slots are not audio data.
7534        let mut storage = [MaybeUninit::<f32>::uninit(); 10];
7535        for (index, value) in [(0, 1.0), (1, 2.0), (2, 3.0), (6, 4.0), (7, 5.0), (8, 6.0)] {
7536            storage[index].write(value);
7537        }
7538        let raw = NDIlib_audio_frame_v3_t {
7539            sample_rate: 48000,
7540            no_channels: 2,
7541            no_samples: 3,
7542            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7543            p_data: storage.as_mut_ptr().cast(),
7544            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
7545                channel_stride_in_bytes: 24,
7546            },
7547            timecode: 123,
7548            timestamp: 456,
7549            p_metadata: ptr::null(),
7550        };
7551        let guard =
7552            unsafe { Guard::<FrameSyncAudioFree>::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
7553        let frame = FrameSyncAudioRef::new(guard).unwrap();
7554        assert!(frame.data().is_none());
7555        assert_eq!(frame.channel_data(0).unwrap(), &[1.0, 2.0, 3.0]);
7556        assert_eq!(frame.channel_data(1).unwrap(), &[4.0, 5.0, 6.0]);
7557        assert_eq!(frame.channel_data(1).unwrap().as_ptr(), unsafe {
7558            storage.as_ptr().add(6).cast::<f32>()
7559        });
7560        assert!(frame.channel_data(2).is_none());
7561        assert_eq!(frame.channels().len(), 2);
7562        assert_eq!(
7563            frame.channels().flatten().copied().collect::<Vec<_>>(),
7564            vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
7565        );
7566        let mut owned = frame.to_owned();
7567        assert_eq!(owned.channel_stride_bytes(), 12);
7568        assert_eq!(owned.data(), &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]);
7569        assert_eq!(
7570            owned.channels().flatten().copied().collect::<Vec<_>>(),
7571            owned.data()
7572        );
7573        assert_eq!(owned.timecode(), Timecode::from_ticks(123));
7574        assert_eq!(owned.timestamp(), ReceivedTimestamp::from_sdk(456));
7575        assert_eq!(owned.channel_data(1).unwrap().as_ptr(), unsafe {
7576            owned.data().as_ptr().add(3)
7577        });
7578        owned.channel_data_mut(1).unwrap()[0] = 99.0;
7579        assert_eq!(owned.data()[3], 99.0);
7580        assert!(owned.channel_data_mut(2).is_none());
7581        assert!(owned.replace_data(vec![0.0; 10]).is_err());
7582    }
7583
7584    #[test]
7585    fn test_audio_rejects_unaligned_float_pointer_before_access() {
7586        let mut storage = [0.0f32; 4];
7587        let raw = NDIlib_audio_frame_v3_t {
7588            sample_rate: 48000,
7589            no_channels: 1,
7590            no_samples: 1,
7591            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7592            p_data: unsafe { storage.as_mut_ptr().cast::<u8>().add(1) },
7593            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
7594                channel_stride_in_bytes: 4,
7595            },
7596            timecode: 0,
7597            timestamp: 0,
7598            p_metadata: ptr::null(),
7599        };
7600        assert!(matches!(
7601            validate_audio_layout(&raw),
7602            Err(Error::InvalidFrame(_))
7603        ));
7604    }
7605
7606    /// Test validate_audio_layout supports strided planar FLTP audio.
7607    #[test]
7608    fn test_validate_audio_layout_strided_planar() {
7609        let no_samples = 4;
7610        let no_channels = 2;
7611        let stride_samples = 6;
7612        let backing_samples = (stride_samples + no_samples) as usize;
7613        let mut data = vec![0.0f32; backing_samples];
7614
7615        let raw = NDIlib_audio_frame_v3_t {
7616            sample_rate: 48000,
7617            no_channels,
7618            no_samples,
7619            timecode: 0,
7620            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7621            p_data: data.as_mut_ptr() as *mut u8,
7622            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
7623                channel_stride_in_bytes: stride_samples * 4,
7624            },
7625            p_metadata: ptr::null(),
7626            timestamp: 0,
7627        };
7628
7629        let layout = validate_audio_layout(&raw).expect("strided FLTP should validate");
7630        assert_eq!(layout.sample_count(), backing_samples);
7631        assert_eq!(layout.channel_stride_samples(), stride_samples as usize);
7632        assert_eq!(layout.channel_range(1), Some(6..10));
7633    }
7634
7635    /// The SDK's no-source answer has no samples and no format, whether it
7636    /// leaves the FourCC unset or sets it.
7637    #[test]
7638    fn returned_audio_accepts_the_no_source_state() {
7639        let unset = NDIlib_audio_frame_v3_t::default();
7640        let set = NDIlib_audio_frame_v3_t {
7641            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7642            ..unset
7643        };
7644        for raw in [unset, set] {
7645            assert!(matches!(
7646                validate_returned_audio(&raw),
7647                Ok(ReturnedAudio::Empty(None))
7648            ));
7649        }
7650    }
7651
7652    /// A positive sample rate and channel count without samples is the
7653    /// source's format.
7654    #[test]
7655    fn returned_audio_reports_a_format_without_samples() {
7656        let raw = NDIlib_audio_frame_v3_t {
7657            sample_rate: 48000,
7658            no_channels: 2,
7659            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7660            ..Default::default()
7661        };
7662        match validate_returned_audio(&raw) {
7663            Ok(ReturnedAudio::Empty(Some(format))) => {
7664                assert_eq!((format.sample_rate(), format.num_channels()), (48000, 2));
7665            }
7666            other => panic!("expected a format without samples, got {other:?}"),
7667        }
7668    }
7669
7670    /// Samples are validated exactly as every other frame of audio is, and
7671    /// neither state without samples is a frame of audio.
7672    #[test]
7673    fn returned_audio_validates_samples_strictly() {
7674        let mut data = [0.0f32; 8];
7675        let raw = NDIlib_audio_frame_v3_t {
7676            sample_rate: 48000,
7677            no_channels: 2,
7678            no_samples: 4,
7679            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7680            p_data: data.as_mut_ptr().cast(),
7681            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
7682                channel_stride_in_bytes: 16,
7683            },
7684            ..Default::default()
7685        };
7686        match validate_returned_audio(&raw) {
7687            Ok(ReturnedAudio::Samples(layout)) => {
7688                assert_eq!(layout.format(), AudioFormat::Fltp);
7689                assert_eq!((layout.no_channels(), layout.no_samples()), (2, 4));
7690                assert_eq!(layout.sample_count(), 8);
7691            }
7692            other => panic!("expected samples, got {other:?}"),
7693        }
7694        // A negative count is not "no samples"; it fails strict validation.
7695        let negative = NDIlib_audio_frame_v3_t {
7696            no_samples: -1,
7697            ..raw
7698        };
7699        assert!(matches!(
7700            validate_returned_audio(&negative),
7701            Err(Error::InvalidFrame(_))
7702        ));
7703
7704        let format_only = NDIlib_audio_frame_v3_t {
7705            sample_rate: 48000,
7706            no_channels: 2,
7707            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7708            ..Default::default()
7709        };
7710        for raw in [NDIlib_audio_frame_v3_t::default(), format_only] {
7711            match validate_audio_layout(&raw) {
7712                Err(Error::InvalidFrame(message)) => {
7713                    assert_eq!(
7714                        message,
7715                        crate::FrameDefect::Layout(crate::LayoutDefect::AudioCount {
7716                            value: 0.into(),
7717                            kind: crate::AudioCountKind::Samples
7718                        })
7719                    );
7720                }
7721                other => panic!("expected InvalidFrame, got {other:?}"),
7722            }
7723        }
7724    }
7725
7726    /// Every other shape without samples is rejected.
7727    #[test]
7728    fn returned_audio_rejects_partial_and_malformed_empty_states() {
7729        let format = NDIlib_audio_frame_v3_t {
7730            sample_rate: 48000,
7731            no_channels: 2,
7732            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7733            ..Default::default()
7734        };
7735        let mut sample = 0.0f32;
7736        let rejected = [
7737            // Only one of the sample rate and channel count is known.
7738            NDIlib_audio_frame_v3_t {
7739                no_channels: 0,
7740                ..format
7741            },
7742            NDIlib_audio_frame_v3_t {
7743                sample_rate: 0,
7744                ..format
7745            },
7746            // Negative values.
7747            NDIlib_audio_frame_v3_t {
7748                sample_rate: -48000,
7749                ..format
7750            },
7751            NDIlib_audio_frame_v3_t {
7752                no_channels: -2,
7753                ..format
7754            },
7755            // A buffer or a channel stride without samples.
7756            NDIlib_audio_frame_v3_t {
7757                p_data: (&mut sample as *mut f32).cast(),
7758                ..format
7759            },
7760            NDIlib_audio_frame_v3_t {
7761                __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
7762                    channel_stride_in_bytes: 4,
7763                },
7764                ..format
7765            },
7766            // A format needs a supported FourCC; no source allows only an
7767            // unset or supported one.
7768            NDIlib_audio_frame_v3_t {
7769                FourCC: 0,
7770                ..format
7771            },
7772            NDIlib_audio_frame_v3_t {
7773                FourCC: 0x1234_5678,
7774                ..format
7775            },
7776            NDIlib_audio_frame_v3_t {
7777                FourCC: 0x1234_5678,
7778                ..Default::default()
7779            },
7780        ];
7781        for (index, raw) in rejected.iter().enumerate() {
7782            let result = validate_returned_audio(raw);
7783            assert!(
7784                matches!(result, Err(Error::InvalidFrame(_))),
7785                "shape {index}: {result:?}"
7786            );
7787        }
7788    }
7789
7790    /// Test validate_audio_layout rejects invalid channel stride.
7791    #[test]
7792    fn test_validate_audio_layout_rejects_invalid_channel_stride() {
7793        let mut data = vec![0.0f32; 2048];
7794
7795        let raw = NDIlib_audio_frame_v3_t {
7796            sample_rate: 48000,
7797            no_channels: 2,
7798            no_samples: 1024,
7799            timecode: 0,
7800            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7801            p_data: data.as_mut_ptr() as *mut u8,
7802            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
7803                channel_stride_in_bytes: 1024 * 4 - 4,
7804            },
7805            p_metadata: ptr::null(),
7806            timestamp: 0,
7807        };
7808
7809        let result = validate_audio_layout(&raw);
7810        assert!(matches!(result, Err(Error::InvalidFrame(_))));
7811    }
7812
7813    /// Test validate_audio_layout rejects null data pointer
7814    #[test]
7815    fn test_validate_audio_layout_null_pointer() {
7816        let raw = NDIlib_audio_frame_v3_t {
7817            sample_rate: 48000,
7818            no_channels: 2,
7819            no_samples: 1024,
7820            timecode: 0,
7821            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7822            p_data: ptr::null_mut(),
7823            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
7824                channel_stride_in_bytes: 1024 * 4,
7825            },
7826            p_metadata: ptr::null(),
7827            timestamp: 0,
7828        };
7829
7830        let result = validate_audio_layout(&raw);
7831        assert!(result.is_err(), "Should reject null data pointer");
7832
7833        if let Err(Error::InvalidFrame(msg)) = result {
7834            assert!(
7835                matches!(msg, crate::FrameDefect::NullAudioData),
7836                "Error should mention null pointer, got: {msg}"
7837            );
7838        } else {
7839            panic!("Expected InvalidFrame error");
7840        }
7841    }
7842
7843    /// Test validate_audio_layout rejects negative sample count
7844    #[test]
7845    fn test_validate_audio_layout_negative_samples() {
7846        let mut data = vec![0.0f32; 1024];
7847
7848        let raw = NDIlib_audio_frame_v3_t {
7849            sample_rate: 48000,
7850            no_channels: 2,
7851            no_samples: -1, // Negative
7852            timecode: 0,
7853            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7854            p_data: data.as_mut_ptr() as *mut u8,
7855            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
7856                channel_stride_in_bytes: 1024 * 4,
7857            },
7858            p_metadata: ptr::null(),
7859            timestamp: 0,
7860        };
7861
7862        let result = validate_audio_layout(&raw);
7863        assert!(result.is_err(), "Should reject negative sample count");
7864
7865        if let Err(Error::InvalidFrame(msg)) = result {
7866            assert!(
7867                matches!(
7868                    msg,
7869                    crate::FrameDefect::Layout(crate::LayoutDefect::AudioCount {
7870                        kind: crate::AudioCountKind::Samples,
7871                        ..
7872                    })
7873                ),
7874                "Error should mention invalid samples, got: {msg}"
7875            );
7876        } else {
7877            panic!("Expected InvalidFrame error");
7878        }
7879    }
7880
7881    /// Test validate_audio_layout rejects overflow scenario
7882    #[test]
7883    fn test_validate_audio_layout_overflow() {
7884        let mut data = vec![0.0f32; 1024];
7885
7886        let raw = NDIlib_audio_frame_v3_t {
7887            sample_rate: 48000,
7888            no_channels: i32::MAX,
7889            no_samples: 1024,
7890            timecode: 0,
7891            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
7892            p_data: data.as_mut_ptr() as *mut u8,
7893            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
7894                channel_stride_in_bytes: 1024 * 4,
7895            },
7896            p_metadata: ptr::null(),
7897            timestamp: 0,
7898        };
7899
7900        let result = validate_audio_layout(&raw);
7901        assert!(
7902            result.is_err(),
7903            "Should reject audio frame with overflow potential"
7904        );
7905
7906        let expected = crate::LayoutDefect::AudioBytes(8_796_093_018_112u64.into());
7907        assert!(matches!(
7908            result,
7909            Err(Error::InvalidFrame(crate::FrameDefect::Layout(cause))) if cause == expected
7910        ));
7911    }
7912
7913    /// Test the raw plane-size kernel matches the public validated layout sizing
7914    #[test]
7915    fn test_calculate_buffer_len_checked_matches_public_helper() {
7916        let test_cases = [
7917            (PixelFormat::Bgra, 7680usize, 1080usize),
7918            (PixelFormat::Uyvy, 3840usize, 1080usize),
7919            (PixelFormat::Nv12, 1920usize, 1080usize),
7920            (PixelFormat::Yv12, 1920usize, 1080usize),
7921            (PixelFormat::I420, 1920usize, 1080usize),
7922        ];
7923
7924        for (format, stride, height) in test_cases {
7925            let expected = format
7926                .buffer_len(1920, height as u32, Some(stride))
7927                .unwrap();
7928            let result = calculate_buffer_len_checked(format, stride, height);
7929
7930            assert!(
7931                result.is_ok(),
7932                "Should succeed for valid inputs: {:?}",
7933                format
7934            );
7935            assert_eq!(
7936                result.unwrap(),
7937                expected,
7938                "Checked calculation should match unchecked for {:?}",
7939                format
7940            );
7941        }
7942    }
7943
7944    /// Test that VideoFrameRef::data() uses cached length
7945    #[test]
7946    fn test_video_frame_ref_uses_cached_length() {
7947        use crate::capture::{Guard, VideoKind};
7948
7949        // Create a mock video frame for testing
7950        let width = 1920;
7951        let height = 1080;
7952        let stride = width * 4;
7953        let expected_size = (stride * height) as usize;
7954        let data = vec![0u8; expected_size];
7955
7956        let raw = NDIlib_video_frame_v2_t {
7957            xres: width,
7958            yres: height,
7959            FourCC: FourCc::from(PixelFormat::Bgra).raw(),
7960            frame_rate_N: 60,
7961            frame_rate_D: 1,
7962            picture_aspect_ratio: 16.0 / 9.0,
7963            frame_format_type: ScanType::Progressive.to_sdk(),
7964            timecode: 12345,
7965            p_data: data.as_ptr() as *mut u8,
7966            __bindgen_anon_1: NDIlib_video_frame_v2_t__bindgen_ty_1 {
7967                line_stride_in_bytes: stride,
7968            },
7969            p_metadata: ptr::null(),
7970            timestamp: 67890,
7971        };
7972
7973        let guard = unsafe { Guard::<VideoKind>::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
7974
7975        // Create the VideoFrameRef
7976        let frame_ref = VideoFrameRef::new(guard);
7977        assert!(frame_ref.is_ok(), "Should create valid VideoFrameRef");
7978
7979        let frame_ref = frame_ref.unwrap();
7980
7981        // Verify the cached length is used
7982        assert_eq!(
7983            frame_ref.data().unwrap().len(),
7984            expected_size,
7985            "data() should return slice with cached length"
7986        );
7987        assert_eq!(
7988            VideoParts::layout(&frame_ref).data_len_bytes(),
7989            expected_size,
7990            "Cached data_len_bytes should match expected"
7991        );
7992    }
7993
7994    /// Test that AudioFrameRef::data() uses cached sample count
7995    #[test]
7996    fn test_audio_frame_ref_uses_cached_sample_count() {
7997        let no_samples = 1024;
7998        let no_channels = 2;
7999        let sample_count = (no_samples * no_channels) as usize;
8000        let data = vec![0.5f32; sample_count];
8001
8002        let raw = NDIlib_audio_frame_v3_t {
8003            sample_rate: 48000,
8004            no_channels,
8005            no_samples,
8006            timecode: 12345,
8007            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
8008            p_data: data.as_ptr() as *mut u8,
8009            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
8010                channel_stride_in_bytes: no_samples * 4,
8011            },
8012            p_metadata: ptr::null(),
8013            timestamp: 67890,
8014        };
8015
8016        let guard = unsafe { Guard::<AudioKind>::with_test_free(ptr::null_mut(), raw, |_, _| {}) };
8017
8018        // Create the AudioFrameRef
8019        let frame_ref = AudioFrameRef::new(guard);
8020        assert!(frame_ref.is_ok(), "Should create valid AudioFrameRef");
8021
8022        let frame_ref = frame_ref.unwrap();
8023
8024        // Verify the cached sample count is used
8025        assert_eq!(
8026            frame_ref.data().unwrap().len(),
8027            sample_count,
8028            "data() should return slice with cached sample count"
8029        );
8030        assert_eq!(
8031            AudioParts::layout(&frame_ref).sample_count(),
8032            sample_count,
8033            "Cached sample_count should match expected"
8034        );
8035    }
8036
8037    /// A borrowed frame's two owned copies: a new frame, and a copy into an
8038    /// existing one.
8039    trait CopySource<F> {
8040        fn owned(&self) -> F;
8041        fn copy(&self, destination: &mut F);
8042    }
8043
8044    impl CopySource<VideoFrame> for VideoFrameRef<'_> {
8045        fn owned(&self) -> VideoFrame {
8046            self.to_owned()
8047        }
8048        fn copy(&self, destination: &mut VideoFrame) {
8049            self.copy_into(destination);
8050        }
8051    }
8052
8053    impl CopySource<VideoFrame> for FrameSyncVideoRef<'_> {
8054        fn owned(&self) -> VideoFrame {
8055            self.to_owned()
8056        }
8057        fn copy(&self, destination: &mut VideoFrame) {
8058            self.copy_into(destination);
8059        }
8060    }
8061    impl CopySource<AudioFrame> for FrameSyncAudioRef<'_> {
8062        fn owned(&self) -> AudioFrame {
8063            self.to_owned()
8064        }
8065        fn copy(&self, destination: &mut AudioFrame) {
8066            self.copy_into(destination);
8067        }
8068    }
8069
8070    impl CopySource<VideoFrame> for crate::BorrowedVideoFrame<'_> {
8071        fn owned(&self) -> VideoFrame {
8072            self.to_owned()
8073        }
8074        fn copy(&self, destination: &mut VideoFrame) {
8075            self.copy_into(destination);
8076        }
8077    }
8078
8079    impl CopySource<AudioFrame> for AudioFrameRef<'_> {
8080        fn owned(&self) -> AudioFrame {
8081            self.to_owned()
8082        }
8083        fn copy(&self, destination: &mut AudioFrame) {
8084            self.copy_into(destination);
8085        }
8086    }
8087
8088    /// However an owned frame gets its pixels, their allocation ends with
8089    /// the zeroed room the SDK reads after a frame of its format, and a
8090    /// format that needs none keeps the vector it was given.
8091    #[test]
8092    fn owned_frames_hold_the_room_the_sdk_reads_after_them() {
8093        for format in PixelFormat::ALL {
8094            // The x86 SDK reads past these two formats; the SDK for 64-bit
8095            // ARM Linux reads every frame exactly.
8096            let read_past = matches!(format, PixelFormat::Uyvy | PixelFormat::Uyva)
8097                && !cfg!(all(target_os = "linux", target_arch = "aarch64"));
8098            assert_eq!(
8099                format.send_tail_room(),
8100                if read_past { 64 } else { 0 },
8101                "{format:?}"
8102            );
8103            for height in [4, 6] {
8104                for scan in ScanType::ALL {
8105                    let builder = || {
8106                        VideoFrame::builder()
8107                            .resolution(18, height)
8108                            .pixel_format(format)
8109                            .scan_type(scan)
8110                    };
8111                    let room = format.send_buffer_len(18, height, None, scan).unwrap()
8112                        - format.buffer_len(18, height, None).unwrap();
8113                    let holds_room = |frame: &VideoFrame, label: &str| {
8114                        assert_eq!(frame.tail_room(), room, "{format:?} {label}");
8115                        assert_eq!(frame.data.room_bytes(), vec![0; room], "{format:?} {label}");
8116                        assert!(VideoSource::sends_in_place(frame), "{format:?} {label}");
8117                    };
8118
8119                    let (built, allocations) =
8120                        crate::test_alloc::allocation_count(|| builder().build().unwrap());
8121                    assert_eq!(allocations, 1, "{format:?}");
8122                    let len = built.data().len();
8123                    assert_eq!(built.data.capacity(), len + room, "{format:?}");
8124                    holds_room(&built, "built");
8125
8126                    // A vector that ends with the frame is kept only when the format
8127                    // needs no room.
8128                    let exact = vec![7; len];
8129                    let address = exact.as_ptr();
8130                    let supplied = builder().data(exact).build().unwrap();
8131                    assert_eq!(supplied.data(), vec![7; len], "{format:?}");
8132                    if room == 0 {
8133                        assert_eq!(
8134                            (supplied.data().as_ptr(), supplied.data.capacity()),
8135                            (address, len),
8136                            "{format:?}"
8137                        );
8138                    }
8139                    holds_room(&supplied, "supplied");
8140
8141                    // A vector with the room is always kept, whatever its spare
8142                    // capacity held.
8143                    let mut roomy = vec![9; len + room];
8144                    roomy.truncate(len);
8145                    let address = roomy.as_ptr();
8146                    let (kept, allocations) = crate::test_alloc::allocation_count(|| {
8147                        builder().data(roomy).build().unwrap()
8148                    });
8149                    assert_eq!(allocations, 0, "{format:?}");
8150                    assert_eq!(kept.data().as_ptr(), address, "{format:?}");
8151                    holds_room(&kept, "kept");
8152
8153                    let mut replaced = built;
8154                    replaced.replace_data(vec![5; len]).unwrap();
8155                    assert_eq!(replaced.data(), vec![5; len], "{format:?}");
8156                    holds_room(&replaced, "replaced");
8157                    let rejected = replaced.replace_data(vec![5; len + 1]).unwrap_err();
8158                    assert_eq!(rejected.into_inner().len(), len + 1);
8159                    holds_room(&replaced, "after a rejected replacement");
8160
8161                    let (clone, allocations) =
8162                        crate::test_alloc::allocation_count(|| replaced.clone());
8163                    assert_eq!(allocations, 1, "{format:?}");
8164                    assert_eq!(clone.data(), replaced.data(), "{format:?}");
8165                    holds_room(&clone, "cloned");
8166
8167                    let borrowed =
8168                        crate::BorrowedVideoFrame::builder(replaced.data(), 18, height, format)
8169                            .scan_type(scan)
8170                            .build()
8171                            .unwrap();
8172                    assert_eq!(borrowed.sends_in_place(), room == 0, "{format:?}");
8173                    let (copy, allocations) =
8174                        crate::test_alloc::allocation_count(|| borrowed.to_owned());
8175                    assert_eq!(allocations, 1, "{format:?}");
8176                    assert_eq!(copy.data.capacity(), len + room, "{format:?}");
8177                    holds_room(&copy, "copied");
8178                    let mut destination = VideoFrame::builder().resolution(2, 2).build().unwrap();
8179                    borrowed.copy_into(&mut destination);
8180                    holds_room(&destination, "copied into");
8181                    let pointer = destination.data().as_ptr();
8182                    let ((), allocations) = crate::test_alloc::allocation_count(|| {
8183                        borrowed.copy_into(&mut destination);
8184                    });
8185                    assert_eq!(allocations, 0);
8186                    assert_eq!(destination.data().as_ptr(), pointer);
8187                    holds_room(&destination, "copied again");
8188                }
8189            }
8190        }
8191    }
8192
8193    /// Changing the scan type establishes its complete read extent before
8194    /// the frame can be borrowed, without moving pixels again on later changes.
8195    #[test]
8196    fn scan_type_changes_preserve_owned_send_room() {
8197        for format in PixelFormat::ALL {
8198            let room = format.send_tail_room();
8199            // Six rows: not a multiple of four.
8200            let mut frame = VideoFrame::builder()
8201                .resolution(18, 6)
8202                .pixel_format(format)
8203                .build()
8204                .unwrap();
8205            frame.data_mut().fill(7);
8206            let len = frame.data().len();
8207            let rows = if room == 0 {
8208                0
8209            } else {
8210                2 * frame.line_stride_bytes()
8211            };
8212            for scan in ScanType::ALL {
8213                frame.set_scan_type(scan);
8214                let needed = crate::pixels::send_room(frame.layout(), scan);
8215                let more = scan != ScanType::Progressive;
8216                assert_eq!(
8217                    needed,
8218                    room + if more { rows } else { 0 },
8219                    "{format:?} {scan:?}"
8220                );
8221                let raw = frame.as_test_raw();
8222                assert_eq!(raw.p_data.cast_const(), frame.data().as_ptr());
8223                assert_eq!(frame.tail_room(), needed, "{format:?} {scan:?}");
8224                assert_eq!(
8225                    frame.data.room_bytes(),
8226                    vec![0; needed],
8227                    "{format:?} {scan:?}"
8228                );
8229                assert_eq!(frame.data(), vec![7; len], "{format:?} {scan:?}");
8230                assert!(VideoSource::sends_in_place(&frame));
8231                // Repeating this scan type and every already-covered type
8232                // preserves the allocation and its initialized tail.
8233                let ((), allocations) = crate::test_alloc::allocation_count(|| {
8234                    frame.set_scan_type(scan);
8235                    frame.set_scan_type(ScanType::Progressive);
8236                    frame.set_scan_type(scan);
8237                    assert_eq!(frame.as_test_raw().p_data, raw.p_data);
8238                });
8239                assert_eq!(allocations, 0, "{format:?} {scan:?}");
8240            }
8241            // Even the first change needs no growth when the caller supplied
8242            // enough capacity. Stale bytes in that capacity must be zeroed.
8243            let mut pixels = frame.into_data();
8244            let address = pixels.as_ptr();
8245            pixels.resize(pixels.capacity(), 255);
8246            pixels.truncate(len);
8247            let mut frame = VideoFrame::builder()
8248                .resolution(18, 6)
8249                .pixel_format(format)
8250                .data(pixels)
8251                .build()
8252                .unwrap();
8253            let ((), allocations) = crate::test_alloc::allocation_count(|| {
8254                frame.set_scan_type(ScanType::Interlaced);
8255            });
8256            assert_eq!(allocations, 0);
8257            assert_eq!(frame.data().as_ptr(), address);
8258            assert!(frame.data.room_bytes().iter().all(|&byte| byte == 0));
8259        }
8260    }
8261
8262    /// An owned frame as a copy destination: the storage a copy can reuse,
8263    /// and every field a copy sets.
8264    trait CopyDestination {
8265        /// The sample buffer's address, capacity and length, in elements.
8266        fn buffer(&self) -> (*const (), usize, usize);
8267        /// The elements the frame keeps after its samples for the SDK to
8268        /// read.
8269        fn room(&self) -> usize;
8270        fn text(&self) -> Option<&str>;
8271        fn text_capacity(&self) -> usize;
8272        /// Require the same layout, header, samples, metadata and timestamp,
8273        /// and the frame's own buffer to fill its layout exactly.
8274        fn assert_same(&self, expected: &Self);
8275    }
8276
8277    impl CopyDestination for VideoFrame {
8278        fn buffer(&self) -> (*const (), usize, usize) {
8279            (
8280                self.data.as_ptr().cast(),
8281                self.data.capacity(),
8282                self.data.len(),
8283            )
8284        }
8285        fn room(&self) -> usize {
8286            self.tail_room()
8287        }
8288        fn text(&self) -> Option<&str> {
8289            self.metadata()
8290        }
8291        fn text_capacity(&self) -> usize {
8292            self.metadata.retained_bytes()
8293        }
8294        fn assert_same(&self, expected: &Self) {
8295            let Self {
8296                timing,
8297                data,
8298                metadata,
8299                timestamp,
8300            } = self;
8301            let Self {
8302                timing: expected_timing,
8303                data: expected_data,
8304                metadata: expected_metadata,
8305                timestamp: expected_timestamp,
8306            } = expected;
8307            let layout = data.layout();
8308            let expected_layout = expected_data.layout();
8309            assert_eq!(data.len(), layout.data_len_bytes());
8310            let room = crate::pixels::send_room(layout, data.scan_type());
8311            assert_eq!(data.room_bytes(), vec![0; room]);
8312            assert_eq!(format!("{layout:?}"), format!("{expected_layout:?}"));
8313            assert_eq!(format!("{timing:?}"), format!("{expected_timing:?}"));
8314            assert_eq!(data.scan_type(), expected_data.scan_type());
8315            assert_eq!(data.as_slice(), expected_data.as_slice());
8316            assert_eq!(metadata.view().status(), expected_metadata.view().status());
8317            assert_eq!(
8318                metadata.view().text().map(MetadataText::as_str),
8319                expected_metadata.view().text().map(MetadataText::as_str)
8320            );
8321            assert_eq!(timestamp, expected_timestamp);
8322        }
8323    }
8324
8325    impl CopyDestination for AudioFrame {
8326        fn buffer(&self) -> (*const (), usize, usize) {
8327            (
8328                self.data.as_ptr().cast(),
8329                self.data.capacity(),
8330                self.data.len(),
8331            )
8332        }
8333        fn room(&self) -> usize {
8334            0
8335        }
8336        fn text(&self) -> Option<&str> {
8337            self.metadata()
8338        }
8339        fn text_capacity(&self) -> usize {
8340            self.metadata.retained_bytes()
8341        }
8342        fn assert_same(&self, expected: &Self) {
8343            let Self {
8344                timecode,
8345                data,
8346                metadata,
8347                timestamp,
8348            } = self;
8349            let Self {
8350                timecode: expected_timecode,
8351                data: expected_data,
8352                metadata: expected_metadata,
8353                timestamp: expected_timestamp,
8354            } = expected;
8355            let layout = data.layout();
8356            let expected_layout = expected_data.layout();
8357            assert_eq!(data.len(), layout.as_layout().sample_count());
8358            assert_eq!(format!("{layout:?}"), format!("{expected_layout:?}"));
8359            assert_eq!(timecode, expected_timecode);
8360            assert_eq!(data.as_slice(), expected_data.as_slice());
8361            assert_eq!(metadata.view().status(), expected_metadata.view().status());
8362            assert_eq!(
8363                metadata.view().text().map(MetadataText::as_str),
8364                expected_metadata.view().text().map(MetadataText::as_str)
8365            );
8366            assert_eq!(timestamp, expected_timestamp);
8367        }
8368    }
8369
8370    /// Require `copy_into` to make each destination exactly the frame
8371    /// `to_owned` returns, whatever it held, allocating only what the
8372    /// destination lacks: a buffer too small for the packed copy and the
8373    /// room after it, and metadata storage too small for the new text.
8374    /// Copying again into the result, a copy loop's steady state, must allocate nothing
8375    /// and keep both allocations.
8376    fn assert_copies_reuse<F: CopyDestination>(source: &dyn CopySource<F>, destinations: Vec<F>) {
8377        let expected = source.owned();
8378        let needed = expected.buffer().2 + expected.room();
8379        for mut destination in destinations {
8380            let (pixels, capacity, _) = destination.buffer();
8381            let fits = capacity >= needed;
8382            let resized_text = expected
8383                .text()
8384                .is_some_and(|text| destination.text_capacity() < text.len() + 1);
8385            let ((), allocations) =
8386                crate::test_alloc::allocation_count(|| source.copy(&mut destination));
8387            assert_eq!(allocations, usize::from(!fits) + usize::from(resized_text));
8388            assert_eq!(destination.buffer().0 == pixels, fits);
8389            destination.assert_same(&expected);
8390
8391            let (pixels, capacity, _) = destination.buffer();
8392            let text = destination.text().map(str::as_ptr);
8393            let ((), allocations) =
8394                crate::test_alloc::allocation_count(|| source.copy(&mut destination));
8395            assert_eq!(allocations, 0);
8396            assert_eq!(destination.buffer().0, pixels);
8397            assert_eq!(destination.buffer().1, capacity);
8398            assert_eq!(destination.text().map(str::as_ptr), text);
8399            destination.assert_same(&expected);
8400        }
8401    }
8402
8403    /// Frames a copy of a 4x4 video frame must overwrite completely, with
8404    /// metadata of `metadata_len` bytes: larger, of another format and with
8405    /// longer metadata; too small, without metadata; planar, large enough,
8406    /// with a timestamp and metadata of the same length; and one whose
8407    /// buffer holds a 4x4 UYVY frame exactly, without the room after it.
8408    fn video_destinations(metadata_len: usize) -> Vec<VideoFrame> {
8409        let built = |width, height, format, metadata: Option<String>| {
8410            let mut builder = VideoFrame::builder()
8411                .resolution(width, height)
8412                .pixel_format(format)
8413                .timecode(Timecode::from_ticks(1));
8414            if let Some(metadata) = metadata {
8415                builder = builder.metadata(metadata);
8416            }
8417            builder.build().unwrap()
8418        };
8419        let mut planar = built(16, 8, PixelFormat::I420, Some("m".repeat(metadata_len)));
8420        planar.timestamp = ReceivedTimestamp::from_sdk(1);
8421        vec![
8422            built(
8423                64,
8424                32,
8425                PixelFormat::Uyvy,
8426                Some("<longer metadata/>".repeat(8)),
8427            ),
8428            built(2, 2, PixelFormat::Bgra, None),
8429            planar,
8430            built(2, 4, PixelFormat::P216, None),
8431        ]
8432    }
8433
8434    /// Frames a copy of fifteen samples must overwrite completely, with
8435    /// metadata of `metadata_len` bytes: larger, with longer metadata; too
8436    /// small, without metadata; and of another shape that holds exactly as
8437    /// many samples, with a timestamp and metadata of the same length.
8438    fn audio_destinations(metadata_len: usize) -> Vec<AudioFrame> {
8439        let built = |channels, samples, metadata: Option<String>| {
8440            let mut builder = AudioFrame::builder()
8441                .sample_rate(44_100)
8442                .num_channels(channels)
8443                .num_samples(samples)
8444                .timecode(Timecode::from_ticks(1));
8445            if let Some(metadata) = metadata {
8446                builder = builder.metadata(metadata);
8447            }
8448            builder.build().unwrap()
8449        };
8450        let mut reshaped = built(5, 3, Some("m".repeat(metadata_len)));
8451        reshaped.timestamp = ReceivedTimestamp::from_sdk(1);
8452        vec![
8453            built(8, 1024, Some("<longer metadata/>".repeat(8))),
8454            built(1, 1, None),
8455            reshaped,
8456        ]
8457    }
8458
8459    #[test]
8460    fn audio_copy_into_skips_channel_padding_and_reuses_storage() {
8461        use std::mem::MaybeUninit;
8462        // Three channels of five samples, eight samples apart. Only samples
8463        // are initialized; the slots between channels are not audio data.
8464        let (channels, samples, stride) = (3, 5, 8);
8465        let mut storage = [MaybeUninit::<f32>::uninit(); 21];
8466        let mut expected = Vec::new();
8467        for channel in 0..channels {
8468            for sample in 0..samples {
8469                let value = (10 * channel + sample) as f32 + 0.5;
8470                storage[channel * stride + sample].write(value);
8471                expected.push(value);
8472            }
8473        }
8474        let metadata = CString::new("<audio-copy/>").unwrap();
8475        let raw = NDIlib_audio_frame_v3_t {
8476            sample_rate: 48_000,
8477            no_channels: channels as i32,
8478            no_samples: samples as i32,
8479            FourCC: crate::FourCc::from(crate::AudioFormat::Fltp).raw(),
8480            p_data: storage.as_mut_ptr().cast(),
8481            __bindgen_anon_1: NDIlib_audio_frame_v3_t__bindgen_ty_1 {
8482                channel_stride_in_bytes: (stride * 4) as i32,
8483            },
8484            timecode: 123,
8485            timestamp: 456,
8486            p_metadata: metadata.as_ptr(),
8487        };
8488        let bare = NDIlib_audio_frame_v3_t {
8489            p_metadata: ptr::null(),
8490            ..raw
8491        };
8492        // Null guards with no-op frees skip SDK calls; the samples and the
8493        // metadata outlive every reference.
8494        let (framesync, received, bare) = unsafe {
8495            (
8496                FrameSyncAudioRef::new(Guard::with_test_free(ptr::null_mut(), raw, |_, _| {})),
8497                AudioFrameRef::new(Guard::<AudioKind>::with_test_free(
8498                    ptr::null_mut(),
8499                    raw,
8500                    |_, _| {},
8501                )),
8502                AudioFrameRef::new(Guard::<AudioKind>::with_test_free(
8503                    ptr::null_mut(),
8504                    bare,
8505                    |_, _| {},
8506                )),
8507            )
8508        };
8509        let (framesync, received, bare) = (framesync.unwrap(), received.unwrap(), bare.unwrap());
8510        assert!(framesync.data().is_none());
8511        let sources: [(&dyn CopySource<AudioFrame>, _); 3] = [
8512            (&framesync, Some("<audio-copy/>")),
8513            (&received, Some("<audio-copy/>")),
8514            (&bare, None),
8515        ];
8516        for (source, metadata) in sources {
8517            let owned = source.owned();
8518            assert_eq!(owned.data(), expected);
8519            assert_eq!(owned.channel_stride_bytes(), samples * 4);
8520            assert_eq!(owned.metadata(), metadata);
8521            assert_eq!(
8522                (owned.sample_rate(), owned.timecode(), owned.timestamp()),
8523                (
8524                    48_000,
8525                    Timecode::from_ticks(123),
8526                    ReceivedTimestamp::from_sdk(456)
8527                )
8528            );
8529            assert_copies_reuse(source, audio_destinations("<audio-copy/>".len()));
8530        }
8531    }
8532
8533    /// One pass of the copy-and-send loop `BorrowedVideoFrame::copy_into`
8534    /// documents, returning the address of the pixels it sent.
8535    fn copy_and_send(
8536        sender: &mut crate::Sender,
8537        spare: &mut Option<VideoFrame>,
8538        pixels: &[u8],
8539    ) -> *const u8 {
8540        let frame = crate::BorrowedVideoFrame::builder(pixels, 64, 32, PixelFormat::Bgra)
8541            .line_stride_bytes(512)
8542            .metadata(c"<copy-loop/>")
8543            .build()
8544            .unwrap();
8545        let owned = match spare.take() {
8546            Some(mut reused) => {
8547                frame.copy_into(&mut reused);
8548                reused
8549            }
8550            None => frame.to_owned(),
8551        };
8552        let sent = owned.data().as_ptr();
8553        *spare = sender.submit_video(owned).unwrap();
8554        sent
8555    }
8556
8557    #[test]
8558    fn copy_and_send_loop_allocates_nothing_once_two_frames_exist() {
8559        let Some(ndi) = crate::test_support::ndi() else {
8560            return;
8561        };
8562        let options =
8563            crate::SenderOptions::new(crate::test_support::unique_name("frame copy loop"))
8564                .clock_video(false);
8565        let mut sender = crate::Sender::new(&ndi, &options).unwrap();
8566        // 64 pixels per row, padded to a 512-byte stride.
8567        let mut buffer = vec![0u8; 512 * 32];
8568        let mut spare = None;
8569        // The first two passes make the two frames that then alternate.
8570        let first = copy_and_send(&mut sender, &mut spare, &buffer);
8571        assert!(spare.is_none());
8572        buffer.fill(1);
8573        let second = copy_and_send(&mut sender, &mut spare, &buffer);
8574        assert_eq!(spare.as_ref().unwrap().data().as_ptr(), first);
8575        let ((), allocations) = crate::test_alloc::allocation_count(|| {
8576            for shade in 2..10 {
8577                buffer.fill(shade);
8578                copy_and_send(&mut sender, &mut spare, &buffer);
8579            }
8580        });
8581        assert_eq!(allocations, 0);
8582        let last = sender.reclaim_video().unwrap();
8583        let previous = spare.unwrap();
8584        assert_eq!(
8585            (last.data().as_ptr(), previous.data().as_ptr()),
8586            (second, first)
8587        );
8588        for (frame, shade) in [(last, 9), (previous, 8)] {
8589            assert_eq!(frame.data().len(), 64 * 32 * 4);
8590            assert!(frame.data().iter().all(|&byte| byte == shade));
8591            assert_eq!(frame.metadata(), Some("<copy-loop/>"));
8592        }
8593    }
8594}
8595
8596#[cfg(test)]
8597#[path = "frames/descriptor_tests.rs"]
8598pub(crate) mod descriptor_tests;
8599
8600#[cfg(test)]
8601#[path = "frames/metadata_tests.rs"]
8602mod metadata_tests;
8603
8604// Compile in the real module so a missing DescriptorParts bound, rather than
8605// visibility of crate internals, refuses unvalidated caller-selected parts.
8606#[cfg(ndi_test_descriptor_parts)]
8607#[path = "../tests/ui/internal/descriptor_parts.rs"]
8608mod descriptor_parts_fixture;
8609
8610#[cfg(test)]
8611#[path = "frames/video_layout_tests.rs"]
8612mod video_layout_tests;
8613
8614#[cfg(ndi_test_frames_privacy)]
8615#[path = "../tests/ui/internal/frames_privacy.rs"]
8616mod frames_privacy_fixture;