1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50#[non_exhaustive]
51#[repr(u32)]
53pub enum PixelFormat {
54 Uyvy = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_UYVY,
56 Uyva = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_UYVA,
58 P216 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_P216,
60 Pa16 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_PA16,
62 Yv12 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_YV12,
64 I420 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_I420,
66 Nv12 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_NV12,
68 Bgra = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_BGRA,
70 Bgrx = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_BGRX,
72 Rgba = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_RGBA,
74 Rgbx = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_RGBX,
76 Na48 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_NA48,
79 Nb48 = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_NB48,
82 Na4g = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_NA4G,
85 Nb4g = NDIlib_FourCC_video_type_e_NDIlib_FourCC_video_type_NB4G,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
107#[non_exhaustive]
108pub enum FormatCategory {
109 Packed,
111 Planar420,
113 SemiPlanar420,
115 PackedAlpha,
118 SemiPlanar422,
121 SemiPlanar422Alpha,
124 Planar444,
126 Planar444Alpha,
128}
129
130#[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
148enum ChromaOrder {
149 CbCr,
150 CrCb,
151}
152
153#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
173pub struct PixelFormatInfo {
174 bytes_per_pixel: u8,
177 category: FormatCategory,
179 has_alpha: bool,
180 sample_width: PixelSampleWidth,
181 chroma_order: ChromaOrder,
182}
183
184impl PixelFormatInfo {
185 #[must_use]
189 pub const fn bytes_per_pixel(&self) -> u8 {
190 self.bytes_per_pixel
191 }
192
193 #[must_use]
195 pub const fn category(&self) -> FormatCategory {
196 self.category
197 }
198
199 #[cfg(feature = "image-encoding")]
201 pub(crate) const fn has_alpha(self) -> bool {
202 self.has_alpha
203 }
204
205 #[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 #[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 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 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 Ok(layout.data_len_bytes() + crate::pixels::send_room(&layout, scan_type))
288 }
289
290 #[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 #[must_use]
472 pub const fn send_tail_room(self) -> usize {
473 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 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 Ok(stride as usize)
531 }
532
533 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
623#[non_exhaustive]
624pub enum ScanType {
625 Progressive,
627 Interlaced,
629 Field0,
631 Field1,
633}
634
635crate::media::decoded_variants!(ScanType: Progressive, Interlaced, Field0, Field1);
636
637impl ScanType {
638 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 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#[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#[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 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
728pub(crate) unsafe trait VideoParts {
755 fn layout(&self) -> &ValidatedVideoLayout;
757
758 fn header(&self) -> VideoHeader;
760
761 fn pixels(&self) -> *const u8;
763
764 fn frame_metadata(&self) -> FrameMetadataRef<'_>;
766
767 fn sdk_timestamp(&self) -> Option<ReceivedTimestamp>;
769
770 fn initialized(&self) -> Initialized {
773 Initialized::ActiveRows
774 }
775}
776
777#[derive(Clone, Copy, Debug, PartialEq, Eq)]
779pub(crate) enum Initialized {
780 ActiveRows,
782 Storage { room_after: usize },
787 PackedSendReady,
789}
790
791unsafe 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
814pub(crate) trait VideoPartsExt: VideoParts {
816 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 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 fn color_metadata(&self) -> crate::color_info::Metadata<'_> {
856 crate::color_info::Metadata::new(self.frame_metadata())
857 }
858
859 #[inline]
862 fn plane_view(&self, index: usize) -> Option<VideoPlane<'_>> {
863 unsafe { self.layout().view_plane(self.pixels(), index) }
867 }
868
869 #[inline]
872 fn plane_views(&self) -> VideoPlanes<'_> {
873 unsafe { self.layout().view_planes(self.pixels()) }
875 }
876
877 #[cfg(feature = "image-encoding")]
879 fn plane_roles(&self) -> PlaneRoles<'_> {
880 unsafe { self.layout().plane_roles(self.pixels()) }
882 }
883
884 #[inline]
887 fn active_data(&self) -> Option<&[u8]> {
888 unsafe { self.layout().view_data(self.pixels()) }
890 }
891
892 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 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#[allow(private_bounds)]
930pub trait VideoSource: VideoParts {
931 fn width(&self) -> u32;
933
934 fn height(&self) -> u32;
936
937 fn pixel_format(&self) -> PixelFormat;
939
940 fn frame_rate(&self) -> FrameRate;
942
943 fn picture_aspect_ratio(&self) -> PictureAspectRatio;
945
946 fn scan_type(&self) -> ScanType;
948
949 fn timecode(&self) -> Timecode;
951
952 fn timestamp(&self) -> Option<ReceivedTimestamp>;
954
955 fn line_stride_bytes(&self) -> usize;
957
958 fn metadata(&self) -> Option<&str>;
961
962 fn metadata_status(&self) -> FrameMetadataStatus;
964
965 fn color_info(&self) -> Result<Option<crate::ColorInfo>>;
973
974 fn plane(&self, index: usize) -> Option<VideoPlane<'_>>;
976
977 fn planes(&self) -> VideoPlanes<'_>;
979
980 fn data(&self) -> Option<&[u8]>;
983
984 fn to_owned(&self) -> VideoFrame;
988
989 fn copy_into(&self, destination: &mut VideoFrame);
995
996 fn sends_in_place(&self) -> bool;
1004
1005 #[cfg(feature = "image-encoding")]
1007 fn encode_image(&self, options: &crate::image_encoding::ImageOptions) -> Result<Vec<u8>>;
1008
1009 #[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 #[cfg(feature = "image-encoding")]
1021 fn encode_image_data_url(
1022 &self,
1023 options: &crate::image_encoding::ImageOptions,
1024 ) -> Result<String>;
1025}
1026
1027macro_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
1093macro_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 #[inline]
1128 fn width(&self) -> u32 {
1129 $crate::frames::VideoParts::layout(self).width()
1130 }
1131
1132 #[inline]
1134 fn height(&self) -> u32 {
1135 $crate::frames::VideoParts::layout(self).height()
1136 }
1137
1138 #[inline]
1143 fn pixel_format(&self) -> $crate::PixelFormat {
1144 $crate::frames::VideoParts::layout(self).pixel_format()
1145 }
1146
1147 #[inline]
1149 fn frame_rate(&self) -> $crate::FrameRate {
1150 $crate::frames::VideoParts::header(self).frame_rate()
1151 }
1152
1153 #[inline]
1156 fn picture_aspect_ratio(&self) -> $crate::PictureAspectRatio {
1157 $crate::frames::VideoParts::header(self).picture_aspect_ratio()
1158 }
1159
1160 #[inline]
1162 fn scan_type(&self) -> $crate::ScanType {
1163 $crate::frames::VideoParts::header(self).scan_type()
1164 }
1165
1166 $(#[$timecode])*
1169 #[inline]
1170 fn timecode(&self) -> $crate::Timecode {
1171 $crate::frames::VideoParts::header(self).timecode()
1172 }
1173
1174 $(#[$line_stride])*
1179 #[inline]
1180 fn line_stride_bytes(&self) -> usize {
1181 $crate::frames::VideoParts::layout(self).line_stride_bytes()
1182 }
1183
1184 #[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 #[inline]
1198 fn metadata_status(&self) -> $crate::FrameMetadataStatus {
1199 $crate::frames::VideoParts::frame_metadata(self).status()
1200 }
1201
1202 #[doc = concat!("```", $fence)]
1225 #[doc = $example]
1226 fn color_info(&self) -> $crate::Result<Option<$crate::ColorInfo>> {
1234 $crate::frames::VideoPartsExt::color_metadata(self).read()
1235 }
1236
1237 $(#[$plane])*
1244 #[inline]
1245 fn plane(&self, index: usize) -> Option<$crate::VideoPlane<'_>> {
1246 $crate::frames::VideoPartsExt::plane_view(self, index)
1247 }
1248
1249 #[inline]
1251 fn planes(&self) -> $crate::VideoPlanes<'_> {
1252 $crate::frames::VideoPartsExt::plane_views(self)
1253 }
1254
1255 $(#[$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 $(#[$images])*
1294 #[doc = concat!("```", $fence)]
1310 #[doc = $example]
1311 #[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 #[doc = concat!("```", $fence)]
1346 #[doc = $example]
1347 #[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 #[doc = concat!("```", $fence)]
1382 #[doc = $example]
1383 #[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#[derive(Clone)]
1435pub struct VideoFrame {
1436 timing: VideoTiming,
1437 data: VideoStorage,
1439 metadata: OwnedFrameMetadata,
1440 timestamp: Option<ReceivedTimestamp>,
1441}
1442
1443unsafe 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 }
1481 line_stride_bytes {
1482 }
1485 plane {
1486 }
1488 timestamp {
1489 }
1492 data(self -> &[u8] => Some) {
1493 } {
1495 self.data.as_slice()
1496 }
1497 to_owned(self) {
1498 #[must_use]
1501 } {
1502 self.clone()
1503 }
1504 copy_into {
1505 }
1517 sends_in_place {
1518 }
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 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 #[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 pub fn set_timecode(&mut self, timecode: Timecode) {
1563 self.timing.timecode = timecode;
1564 }
1565
1566 pub fn set_scan_type(&mut self, scan_type: ScanType) {
1572 self.data.set_scan_type(scan_type);
1573 }
1574
1575 pub fn set_frame_rate(&mut self, frame_rate: FrameRate) {
1577 self.timing.frame_rate = frame_rate;
1578 }
1579
1580 pub fn set_picture_aspect_ratio(&mut self, ratio: PictureAspectRatio) {
1585 self.timing.picture_aspect_ratio = ratio;
1586 }
1587
1588 pub fn into_data(self) -> Vec<u8> {
1593 self.data.into_vec()
1594 }
1595
1596 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 pub fn data_mut(&mut self) -> &mut [u8] {
1611 self.data.as_mut_slice()
1612 }
1613
1614 #[cfg(test)]
1617 pub(crate) fn tail_room(&self) -> usize {
1618 self.data.room()
1619 }
1620
1621 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 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 pub fn clear_metadata(&mut self) {
1665 self.metadata.clear();
1666 }
1667
1668 #[cfg(test)]
1673 pub(crate) unsafe fn from_raw(c_frame: &NDIlib_video_frame_v2_t) -> Result<VideoFrame> {
1674 let frame = unsafe { ValidatedVideo::video_descriptor(c_frame)? };
1676 Ok(frame.owned_copy())
1677 }
1678}
1679
1680#[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 #[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 #[must_use]
1722 pub fn pixel_format(mut self, pixel_format: PixelFormat) -> Self {
1723 self.pixel_format = pixel_format;
1724 self
1725 }
1726
1727 #[must_use]
1729 pub fn frame_rate(mut self, frame_rate: FrameRate) -> Self {
1730 self.frame_rate = frame_rate;
1731 self
1732 }
1733
1734 #[must_use]
1737 pub fn picture_aspect_ratio(mut self, ratio: PictureAspectRatio) -> Self {
1738 self.picture_aspect_ratio = ratio;
1739 self
1740 }
1741
1742 #[must_use]
1744 pub fn scan_type(mut self, scan_type: ScanType) -> Self {
1745 self.scan_type = scan_type;
1746 self
1747 }
1748
1749 #[must_use]
1751 pub fn timecode(mut self, timecode: Timecode) -> Self {
1752 self.timecode = timecode;
1753 self
1754 }
1755
1756 #[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 #[must_use]
1775 pub fn data(mut self, data: Vec<u8>) -> Self {
1776 self.data = Some(data);
1777 self
1778 }
1779
1780 pub fn supplied_data(&self) -> Option<&[u8]> {
1782 self.data.as_deref()
1783 }
1784
1785 pub fn take_data(&mut self) -> Option<Vec<u8>> {
1790 self.data.take()
1791 }
1792
1793 pub fn into_data(self) -> Option<Vec<u8>> {
1798 self.data
1799 }
1800
1801 #[must_use]
1805 pub fn clear_data(mut self) -> Self {
1806 self.data = None;
1807 self
1808 }
1809
1810 pub fn supplied_metadata(&self) -> Option<&str> {
1812 self.metadata.as_deref()
1813 }
1814
1815 pub fn take_metadata(&mut self) -> Option<String> {
1818 self.metadata.take()
1819 }
1820
1821 #[must_use]
1823 pub fn clear_metadata(mut self) -> Self {
1824 self.metadata = None;
1825 self
1826 }
1827
1828 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
1879pub(crate) unsafe trait AudioParts {
1899 fn layout(&self) -> &ValidatedAudioLayout;
1901
1902 fn audio_timecode(&self) -> Timecode;
1904
1905 fn sdk_timestamp(&self) -> Option<ReceivedTimestamp>;
1907
1908 fn samples(&self) -> *const f32;
1910
1911 fn frame_metadata(&self) -> FrameMetadataRef<'_>;
1913}
1914
1915pub(crate) trait AudioPartsExt: AudioParts {
1917 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 #[inline]
1938 fn channel_view(&self, channel: usize) -> Option<&[f32]> {
1939 unsafe { self.layout().channel(self.samples(), channel) }
1943 }
1944
1945 #[inline]
1948 fn channel_views(&self) -> AudioChannels<'_> {
1949 unsafe { self.layout().channels(self.samples()) }
1951 }
1952
1953 #[inline]
1956 fn contiguous_samples(&self) -> Option<&[f32]> {
1957 unsafe { self.layout().view_samples(self.samples()) }
1959 }
1960
1961 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 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#[allow(private_bounds)]
2000pub trait AudioSource: AudioParts {
2001 fn sample_rate(&self) -> u32;
2003
2004 fn num_channels(&self) -> u32;
2006
2007 fn num_samples(&self) -> u32;
2009
2010 fn format(&self) -> AudioFormat;
2012
2013 fn channel_stride_bytes(&self) -> usize;
2015
2016 fn timecode(&self) -> Timecode;
2018
2019 fn timestamp(&self) -> Option<ReceivedTimestamp>;
2021
2022 fn metadata(&self) -> Option<&str>;
2025
2026 fn metadata_status(&self) -> FrameMetadataStatus;
2028
2029 fn channel_data(&self, channel: usize) -> Option<&[f32]>;
2031
2032 fn channels(&self) -> AudioChannels<'_>;
2034
2035 fn data(&self) -> Option<&[f32]>;
2037
2038 fn to_owned(&self) -> AudioFrame;
2042
2043 fn copy_into(&self, destination: &mut AudioFrame);
2047}
2048
2049macro_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 #[inline]
2077 fn sample_rate(&self) -> u32 {
2078 AudioParts::layout(self).sample_rate()
2079 }
2080
2081 #[inline]
2083 fn num_channels(&self) -> u32 {
2084 AudioParts::layout(self).num_channels()
2085 }
2086
2087 #[inline]
2089 fn num_samples(&self) -> u32 {
2090 AudioParts::layout(self).num_samples()
2091 }
2092
2093 $(#[$timecode])*
2096 #[inline]
2097 fn timecode(&self) -> Timecode {
2098 AudioParts::audio_timecode(self)
2099 }
2100
2101 $(#[$timestamp])*
2104 #[inline]
2105 fn timestamp(&self) -> Option<ReceivedTimestamp> {
2106 AudioParts::sdk_timestamp(self)
2107 }
2108
2109 #[inline]
2114 fn format(&self) -> AudioFormat {
2115 AudioParts::layout(self).format()
2116 }
2117
2118 $(#[$channel_stride])*
2122 #[inline]
2123 fn channel_stride_bytes(&self) -> usize {
2124 AudioParts::layout(self).channel_stride_bytes()
2125 }
2126
2127 #[inline]
2133 fn metadata(&self) -> Option<&str> {
2134 AudioParts::frame_metadata(self).text().map(MetadataText::as_str)
2135 }
2136
2137 #[inline]
2140 fn metadata_status(&self) -> crate::FrameMetadataStatus {
2141 AudioParts::frame_metadata(self).status()
2142 }
2143
2144 $(#[$channel_data])*
2150 #[inline]
2151 fn channel_data(&self, channel: usize) -> Option<&[f32]> {
2152 AudioPartsExt::channel_view(self, channel)
2153 }
2154
2155 #[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#[derive(Clone)]
2206pub struct AudioFrame {
2207 timecode: Timecode,
2208 data: PackedStorage<PackedAudioLayout>,
2209 metadata: OwnedFrameMetadata,
2210 timestamp: Option<ReceivedTimestamp>,
2211}
2212
2213unsafe 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 }
2246 timestamp {
2247 }
2250 channel_stride_bytes {
2251 }
2253 channel_data {
2254 }
2256 data(self -> &[f32] => Some) {
2257 } {
2260 self.data.as_slice()
2261 }
2262 to_owned(self) {
2263 #[must_use]
2266 } {
2267 self.clone()
2268 }
2269 copy_into {
2270 }
2273
2274}
2275
2276impl AudioFrame {
2277 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 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 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 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 pub(crate) unsafe fn from_raw(raw: NDIlib_audio_frame_v3_t) -> Result<AudioFrame> {
2337 let frame = unsafe { ValidatedAudio::audio_descriptor(&raw)? };
2339 Ok(frame.owned_copy())
2340 }
2341
2342 pub fn set_timecode(&mut self, timecode: Timecode) {
2344 self.timecode = timecode;
2345 }
2346
2347 pub fn into_data(self) -> Vec<f32> {
2349 self.data.into_vec()
2350 }
2351
2352 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 pub fn data_mut(&mut self) -> &mut [f32] {
2367 self.data.as_mut_slice()
2368 }
2369
2370 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 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 pub fn clear_metadata(&mut self) {
2404 self.metadata.clear();
2405 }
2406
2407 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#[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 #[must_use]
2441 pub fn sample_rate(mut self, sample_rate: u32) -> Self {
2442 self.sample_rate = sample_rate;
2443 self
2444 }
2445
2446 #[must_use]
2448 pub fn num_channels(mut self, num_channels: u32) -> Self {
2449 self.num_channels = num_channels;
2450 self
2451 }
2452
2453 #[must_use]
2455 pub fn num_samples(mut self, num_samples: u32) -> Self {
2456 self.num_samples = num_samples;
2457 self
2458 }
2459
2460 #[must_use]
2462 pub fn timecode(mut self, timecode: Timecode) -> Self {
2463 self.timecode = timecode;
2464 self
2465 }
2466
2467 #[must_use]
2473 pub fn data(mut self, data: Vec<f32>) -> Self {
2474 self.data = Some(data);
2475 self
2476 }
2477
2478 #[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 pub fn supplied_data(&self) -> Option<&[f32]> {
2491 self.data.as_deref()
2492 }
2493
2494 pub fn take_data(&mut self) -> Option<Vec<f32>> {
2499 self.data.take()
2500 }
2501
2502 pub fn into_data(self) -> Option<Vec<f32>> {
2507 self.data
2508 }
2509
2510 #[must_use]
2514 pub fn clear_data(mut self) -> Self {
2515 self.data = None;
2516 self
2517 }
2518
2519 pub fn supplied_metadata(&self) -> Option<&str> {
2521 self.metadata.as_deref()
2522 }
2523
2524 pub fn take_metadata(&mut self) -> Option<String> {
2527 self.metadata.take()
2528 }
2529
2530 #[must_use]
2532 pub fn clear_metadata(mut self) -> Self {
2533 self.metadata = None;
2534 self
2535 }
2536
2537 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2609#[non_exhaustive]
2610pub enum AudioFormat {
2611 Fltp,
2613}
2614
2615crate::media::decoded_variants!(AudioFormat: Fltp);
2616
2617impl AudioFormat {
2618 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
2642const_assert!(widest_pixel_bytes() == PixelFormat::Nb4g.packed_bytes_per_pixel_ceil());
2644
2645pub const MAX_VIDEO_BYTES: usize =
2650 DCI_8K_WIDTH as usize * DCI_8K_HEIGHT as usize * widest_pixel_bytes();
2651
2652pub(crate) const MAX_AUDIO_BYTES: usize = 64 * 1024 * 1024;
2655
2656pub(crate) const MAX_METADATA_BYTES: usize = 4 * 1024 * 1024;
2659
2660#[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 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 #[must_use]
2715 pub fn with_timecode(mut self, timecode: Timecode) -> Self {
2716 self.timecode = timecode;
2717 self
2718 }
2719
2720 pub fn data(&self) -> &str {
2722 self.data.as_str()
2723 }
2724
2725 pub fn as_bytes(&self) -> &[u8] {
2727 self.data().as_bytes()
2728 }
2729
2730 #[must_use]
2732 pub fn to_owned(&self) -> Self {
2733 self.clone()
2734 }
2735
2736 pub fn copy_into(&self, destination: &mut Self) {
2739 copy_metadata_into(self, destination);
2740 }
2741
2742 pub fn into_data(self) -> String {
2744 self.data.into_string()
2745 }
2746
2747 pub fn timecode(&self) -> Timecode {
2752 self.timecode
2753 }
2754
2755 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 pub fn set_timecode(&mut self, timecode: Timecode) {
2775 self.timecode = timecode;
2776 }
2777
2778 #[cfg(test)]
2787 pub(crate) unsafe fn from_raw(raw: &NDIlib_metadata_frame_t) -> Result<Self> {
2788 let text = unsafe { validate_metadata_layout(raw)? };
2790 Ok(Self::copied(text, Timecode::from_ticks(raw.timecode)))
2791 }
2792
2793 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
2801pub(crate) unsafe trait MetadataParts {
2809 fn metadata_text_for_send(&self) -> Option<MetadataText<'_>>;
2810 fn metadata_timecode(&self) -> Timecode;
2811}
2812
2813pub(crate) trait MetadataPartsExt: MetadataParts {
2815 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#[allow(private_bounds)]
2842pub trait MetadataSource: MetadataParts {
2843 fn data(&self) -> &str;
2845
2846 fn as_bytes(&self) -> &[u8];
2848
2849 fn timecode(&self) -> Timecode;
2851
2852 fn to_owned(&self) -> MetadataFrame;
2854
2855 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
2881unsafe 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
2906#[non_exhaustive]
2907pub enum FrameMetadataStatus {
2908 Absent,
2910 Text,
2912 NotUtf8,
2914 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
2934pub(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 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 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 pub(crate) fn borrowed(frame: &'a F, ndi: &crate::Ndi) -> Result<Self> {
3026 Self::checked(frame, ndi).map_err(|(error, _)| error)
3027 }
3028}
3029
3030pub 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 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 }
3073 plane {}
3074 timestamp {
3075 }
3077 data(self -> Option<&[u8]>) {
3078 } {
3085 self.inner.active_data()
3086 }
3087 to_owned(self) {
3088 } {
3100 self.inner.owned_copy()
3101 }
3102 copy_into {
3103 }
3124 sends_in_place {
3125 }
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 }
3142 }
3143 };
3144}
3145borrowed_video_accessors!(VideoFrameRef, VideoKind);
3146borrowed_video_accessors!(FrameSyncVideoRef, FrameSyncVideoFree);
3147
3148pub 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 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 }
3197 timestamp {
3198 }
3202 channel_stride_bytes {
3203 }
3205 channel_data {}
3206 data(self -> Option<&[f32]>) {
3207 } {
3213 self.inner.contiguous_samples()
3214 }
3215 to_owned(self) {
3216 } {
3227 self.inner.owned_copy()
3228 }
3229 copy_into {
3230 }
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
3266pub struct MetadataFrameRef<'rx> {
3298 frame: MetadataLoan<'rx>,
3302}
3303
3304impl<'rx> MetadataFrameRef<'rx> {
3305 pub(crate) fn new(guard: RecvMetadataGuard<'rx>) -> Result<Self> {
3307 Ok(Self {
3308 frame: MetadataLoan::receiver(guard)?,
3309 })
3310 }
3311
3312 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 pub fn timecode(&self) -> Timecode {
3324 Timecode::from_ticks(self.frame.descriptor().timecode)
3325 }
3326
3327 pub fn data(&self) -> &str {
3332 self.frame.metadata().map_or("", MetadataText::as_str)
3333 }
3334
3335 pub fn as_bytes(&self) -> &[u8] {
3338 self.data().as_bytes()
3339 }
3340
3341 pub fn to_owned(&self) -> MetadataFrame {
3346 MetadataFrame::copied(self.frame.metadata(), self.timecode())
3347 }
3348
3349 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
3366unsafe 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 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 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 #[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 #[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 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 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 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 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 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 #[test]
3680 fn interleaved_audio_builds_exact_planar_output() {
3681 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 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 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 assert!(crate::audio_conversion::InterleavedAudioF32::new(48_000, 3, &[0.0; 11]).is_err());
3728 }
3729
3730 #[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 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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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()); }
4400 }
4401
4402 #[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 #[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 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]
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 let len = fmt.buffer_len(1920, 1080, Some(7680)).unwrap();
4638 assert_eq!(len, 7680 * 1080, "Format {:?} even dimensions", fmt);
4639
4640 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]
4648 fn test_pixel_format_info_packed_yuv() {
4649 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 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 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 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 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]
4699 fn test_pixel_format_info_planar_420_even() {
4700 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]
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]
4739 fn test_pixel_format_info_nv12_even() {
4740 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]
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 #[test]
4769 fn test_420_parity_is_consistent_across_paths() {
4770 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 assert_eq!(
4808 PixelFormat::Nv12
4809 .buffer_len(1920, 1080, Some(1921))
4810 .unwrap(),
4811 1921 * 1080 + 1921 * 540
4812 );
4813 }
4814
4815 #[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 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 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 assert_eq!(PixelFormat::Uyvy.line_stride_bytes(1920).unwrap(), 3840);
4896
4897 assert_eq!(PixelFormat::Uyva.line_stride_bytes(1920).unwrap(), 3840);
4899
4900 assert_eq!(PixelFormat::P216.line_stride_bytes(1920).unwrap(), 3840);
4902 assert_eq!(PixelFormat::Pa16.line_stride_bytes(1920).unwrap(), 3840);
4903
4904 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]
4912 fn test_pixel_format_buffer_size() {
4913 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 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 assert_eq!(
4935 PixelFormat::Nv12.buffer_len(1920, 1080, None).unwrap(),
4936 3_110_400
4937 );
4938
4939 assert_eq!(
4941 PixelFormat::Uyva.buffer_len(1920, 1080, None).unwrap(),
4942 6_220_800
4943 );
4944
4945 assert_eq!(
4947 PixelFormat::P216.buffer_len(1920, 1080, None).unwrap(),
4948 8_294_400
4949 );
4950
4951 assert_eq!(
4953 PixelFormat::Pa16.buffer_len(1920, 1080, None).unwrap(),
4954 12_441_600
4955 );
4956 }
4957
4958 #[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]
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 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 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 assert!(format.line_stride_bytes(6).is_ok());
5071 assert!(ValidatedVideoLayout::new_uncompressed(format, 6, 2, Some(128)).is_ok());
5072 }
5073 assert!(ValidatedVideoLayout::new_uncompressed(PixelFormat::Bgra, 2, 3, Some(9)).is_ok());
5075 }
5076
5077 #[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]
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]
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]
5133 fn test_videoframe_from_raw_nv12() {
5134 let width = 1920;
5136 let height = 1080;
5137 let y_stride = 1920;
5138 let expected_size = 3_110_400; let mut data = vec![0u8; expected_size];
5141 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]
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; 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 #[test]
5213 fn test_videoframe_from_raw_packed_regression() {
5214 let width = 1920;
5215 let height = 1080;
5216 let stride = 1920 * 4; 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]
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, 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 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]
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]
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 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, 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]
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]
5416 fn test_videoframeref_data_uses_validated_format() {
5417 use crate::capture::{Guard, VideoKind};
5418
5419 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 assert_eq!(
5450 frame_ref.data().unwrap().len(),
5451 expected_size,
5452 "data() should use validated pixel format for size calculation"
5453 );
5454
5455 assert_eq!(
5457 frame_ref.line_stride_bytes(),
5458 stride as usize,
5459 "line_stride_bytes() should use validated format"
5460 );
5461 }
5462
5463 #[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 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 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 #[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, 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 assert!(matches!(
5562 validate_video_frame(&raw(&mut recv_data)),
5563 Err(Error::InvalidFrame(_))
5564 ));
5565
5566 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 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]
5682 fn test_max_audio_bytes_constant() {
5683 assert_eq!(MAX_AUDIO_BYTES, 64 * 1024 * 1024);
5685 }
5686
5687 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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]
6699 fn test_audio_overflow_checked_mul() {
6700 let no_samples = 1024;
6702 let no_channels = i32::MAX;
6703 let mut dummy_data = vec![0f32; 1024]; 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]
6734 fn test_audio_within_bounds_succeeds() {
6735 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 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 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 #[test]
7101 fn test_validate_video_layout_valid_uncompressed() {
7102 let width = 1920;
7103 let height = 1080;
7104 let stride = width * 4; 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]
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]
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]
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]
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, },
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]
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]
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]
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, 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]
7399 fn test_validate_video_layout_exceeds_max() {
7400 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]
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 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]
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 #[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 #[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 #[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 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 #[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 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 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 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 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]
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]
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]
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, 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]
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]
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]
7946 fn test_video_frame_ref_uses_cached_length() {
7947 use crate::capture::{Guard, VideoKind};
7948
7949 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 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 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]
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 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 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 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 #[test]
8092 fn owned_frames_hold_the_room_the_sdk_reads_after_them() {
8093 for format in PixelFormat::ALL {
8094 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 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 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(©, "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 #[test]
8196 fn scan_type_changes_preserve_owned_send_room() {
8197 for format in PixelFormat::ALL {
8198 let room = format.send_tail_room();
8199 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 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 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 trait CopyDestination {
8265 fn buffer(&self) -> (*const (), usize, usize);
8267 fn room(&self) -> usize;
8270 fn text(&self) -> Option<&str>;
8271 fn text_capacity(&self) -> usize;
8272 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 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 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 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 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 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 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 let mut buffer = vec![0u8; 512 * 32];
8568 let mut spare = None;
8569 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#[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;