Skip to main content

grafton_ndi/
video_conversion.rs

1//! Checked native conversion between complete V210 groups and NDI P216.
2//!
3//! V210 is a utility buffer layout, not an NDI sendable pixel format. Each six
4//! pixels occupy four 32-bit words containing three 10-bit samples and two unused
5//! bits. Widths must be multiples of six; partial groups are deliberately rejected.
6//! These are sample-packing conversions, without color-space or HDR transforms.
7
8#[cfg(test)]
9use std::ptr;
10
11use crate::{
12    frames::{
13        FrameMetadataRef, ValidatedVideoLayout, VideoHeader, VideoParts, VideoPartsExt,
14        MAX_VIDEO_BYTES,
15    },
16    sys::{self, bindings::NDIlib_video_frame_v2_t},
17    Error, Ndi, PictureAspectRatio, PixelFormat, Result, ScanType, Timecode, VideoFrame,
18    VideoSource,
19};
20
21/// Validated V210 storage geometry, including optional initialized row padding.
22///
23/// Width must be positive and divisible by six. Height must be positive. Rows
24/// contain at least `width / 6 * 16` bytes; their stride must be divisible by four.
25/// Both the V210 storage and equivalent P216 frame must fit [`MAX_VIDEO_BYTES`].
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub struct V210Layout {
28    width: u32,
29    height: u32,
30    stride: usize,
31    words: usize,
32}
33
34impl V210Layout {
35    /// Create a tightly packed layout of complete six-pixel groups.
36    ///
37    /// # Errors
38    ///
39    /// [`Error::InvalidFrame`] for a width that is zero or not a multiple of
40    /// six, a zero height, or storage beyond the video limit.
41    pub fn new(width: u32, height: u32) -> Result<Self> {
42        Self::checked(width, height, None)
43    }
44
45    /// Create a layout with a byte stride that may include row padding.
46    ///
47    /// # Errors
48    ///
49    /// As for [`Self::new`], and for a stride that is not a multiple of four
50    /// or does not cover every complete pixel group.
51    pub fn with_line_stride_bytes(width: u32, height: u32, stride_bytes: usize) -> Result<Self> {
52        Self::checked(width, height, Some(stride_bytes))
53    }
54
55    fn checked(width: u32, height: u32, stride: Option<usize>) -> Result<Self> {
56        if width == 0 || !width.is_multiple_of(6) {
57            return Err(Error::InvalidFrame(crate::FrameDefect::V210Width));
58        }
59        // Validate the corresponding two full-height, 16-bit P216 planes
60        // before arithmetic. Their extent bounds width to MAX_VIDEO_BYTES / 4.
61        ValidatedVideoLayout::new_uncompressed(PixelFormat::P216, width, height, None)?;
62        const_assert!(MAX_VIDEO_BYTES / 4 <= usize::MAX / 16);
63        let active_words = width as usize / 6 * 4;
64        let stride_bytes = stride.unwrap_or(active_words * 4);
65        if stride_bytes == 0 || !stride_bytes.is_multiple_of(4) || stride_bytes / 4 < active_words {
66            return Err(Error::InvalidFrame(crate::FrameDefect::V210Stride));
67        }
68        let bytes = stride_bytes
69            .checked_mul(height as usize)
70            .filter(|bytes| *bytes <= MAX_VIDEO_BYTES)
71            .ok_or(Error::InvalidFrame(crate::FrameDefect::V210Storage))?;
72        Ok(Self {
73            width,
74            height,
75            stride: stride_bytes,
76            words: bytes / 4,
77        })
78    }
79
80    /// Pixel width, always a multiple of six.
81    pub const fn width(self) -> u32 {
82        self.width
83    }
84    /// Positive row count.
85    pub const fn height(self) -> u32 {
86        self.height
87    }
88    /// Byte stride between V210 rows.
89    pub const fn line_stride_bytes(self) -> usize {
90        self.stride
91    }
92    /// Complete required storage, including row padding, in 32-bit words.
93    pub const fn required_words(self) -> usize {
94        self.words
95    }
96    /// Active 32-bit words in each row, excluding padding.
97    pub const fn active_words_per_row(self) -> usize {
98        self.width as usize / 6 * 4
99    }
100
101    /// The SDK's `line_stride_in_bytes`.
102    fn sdk_line_stride(self) -> i32 {
103        // Lossless: the stride is at most the storage, which is within the
104        // video limit, below i32::MAX.
105        self.stride as i32
106    }
107
108    fn check_storage(self, words: usize) -> Result<()> {
109        if words < self.words {
110            return Err(Error::InvalidFrame(
111                crate::FrameDefect::V210BufferTooSmall {
112                    actual: words,
113                    minimum: self.words,
114                },
115            ));
116        }
117        Ok(())
118    }
119
120    /// Require validated P216 input with this layout's dimensions.
121    fn check_p216(self, frame: &(impl VideoSource + ?Sized)) -> Result<()> {
122        if frame.pixel_format() != PixelFormat::P216
123            || frame.width() != self.width
124            || frame.height() != self.height
125        {
126            return Err(Error::InvalidFrame(crate::FrameDefect::P216LayoutMismatch));
127        }
128        Ok(())
129    }
130
131    /// The SDK descriptor of the packed P216 frame of this layout's
132    /// dimensions, two full-height planes of 16-bit samples, over the borrowed
133    /// initialized bytes in `data`.
134    ///
135    /// The samples may start at any address. The NDI SDK documentation of
136    /// video frames gives a frame's `p_data` no alignment requirement, and
137    /// the crate itself reads P216 samples only as bytes, so their alignment
138    /// depends on nothing, including the global allocator.
139    ///
140    /// Tests supply exactly the validated size; application input is checked
141    /// by the public frame builders before reaching a descriptor helper.
142    #[cfg(test)]
143    fn p216_descriptor(self, data: &[u8]) -> Result<NDIlib_video_frame_v2_t> {
144        // `with_line_stride_bytes` validated this layout for these dimensions.
145        let p216 = ValidatedVideoLayout::new_uncompressed(
146            PixelFormat::P216,
147            self.width,
148            self.height,
149            None,
150        )?;
151        assert_eq!(
152            data.len(),
153            p216.data_len_bytes(),
154            "test supplies a complete P216 frame"
155        );
156        // BorrowedVideoFrame keeps geometry paired with the validated slice.
157        // Conversion needs no metadata and uses the builder's valid header.
158        let frame =
159            crate::BorrowedVideoFrame::builder(data, self.width, self.height, PixelFormat::P216)
160                .build()?;
161        Ok(frame.video_descriptor())
162    }
163
164    /// Borrow writable P216 storage without deriving the output pointer from
165    /// a shared slice: the native converter writes through the original
166    /// exclusive borrow's pointer.
167    fn p216_output_descriptor(self, destination: &mut VideoFrame) -> NDIlib_video_frame_v2_t {
168        P216Output::new(destination).video_descriptor()
169    }
170
171    /// The SDK descriptor of this layout's V210 words at `data`: `p216`, the
172    /// descriptor of the matching P216 frame, with the V210 FourCC, which the
173    /// native utilities ignore, and the V210 stride.
174    fn v210_descriptor(
175        self,
176        p216: NDIlib_video_frame_v2_t,
177        data: *const u32,
178    ) -> NDIlib_video_frame_v2_t {
179        let mut v210 = p216;
180        // V210 deliberately is not a PixelFormat variant, so it cannot enter
181        // the ordinary sending path.
182        v210.FourCC = u32::from_le_bytes(*b"V210");
183        v210.p_data = data.cast_mut().cast();
184        v210.__bindgen_anon_1.line_stride_in_bytes = self.sdk_line_stride();
185        v210
186    }
187}
188
189/// A view whose pixel pointer retains writable provenance from its exclusive
190/// input slice. It never exposes shared references to those pixels.
191struct P216Output<'a> {
192    layout: ValidatedVideoLayout,
193    header: VideoHeader,
194    pointer: *mut u8,
195    _borrow: std::marker::PhantomData<&'a mut [u8]>,
196}
197
198impl<'a> P216Output<'a> {
199    fn new(destination: &'a mut VideoFrame) -> Self {
200        let layout = *VideoParts::layout(destination);
201        // Derive the pointer from the exclusive borrow, preserving writable
202        // provenance; the frame's storage fills its own validated layout.
203        let pointer = destination.data_mut().as_mut_ptr();
204        Self {
205            layout,
206            header: VideoHeader::new(
207                crate::media::DEFAULT_VIDEO_FRAME_RATE,
208                PictureAspectRatio::SQUARE_PIXELS,
209                ScanType::Progressive,
210                Timecode::SYNTHESIZE,
211            ),
212            pointer,
213            _borrow: std::marker::PhantomData,
214        }
215    }
216}
217
218// SAFETY: construction copies the owned frame's validated layout and borrows
219// its exactly sized initialized storage exclusively. The borrow keeps it allocated and inaccessible until
220// the view is consumed; metadata is absent and the header is valid. Its
221// Initialized::Storage report claims zero room beyond that storage.
222unsafe impl VideoParts for P216Output<'_> {
223    fn layout(&self) -> &ValidatedVideoLayout {
224        &self.layout
225    }
226    fn header(&self) -> VideoHeader {
227        self.header
228    }
229    fn pixels(&self) -> *const u8 {
230        self.pointer.cast_const()
231    }
232    fn frame_metadata(&self) -> FrameMetadataRef<'_> {
233        FrameMetadataRef::Absent
234    }
235    fn sdk_timestamp(&self) -> Option<crate::ReceivedTimestamp> {
236        None
237    }
238    fn initialized(&self) -> crate::frames::Initialized {
239        crate::frames::Initialized::Storage { room_after: 0 }
240    }
241}
242
243/// Native V210/P216 conversion helpers retained with their selected runtime.
244///
245/// Both exports are resolved before construction succeeds. Operations use
246/// caller-owned initialized storage and do not allocate pixel buffers. Borrowed
247/// P216 inputs retain their original validated row and plane strides.
248pub struct VideoConverter {
249    conversion: crate::runtime::Bound<sys::VideoConversion>,
250}
251
252impl std::fmt::Debug for VideoConverter {
253    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
254        f.debug_struct("VideoConverter")
255            .field("runtime", self.conversion.ndi().info())
256            .finish_non_exhaustive()
257    }
258}
259
260impl VideoConverter {
261    /// Resolve both native utility functions from one initialized runtime.
262    ///
263    /// # Errors
264    ///
265    /// Returns [`Error::UnsupportedCapability`] when the runtime does not
266    /// provide both native V210/P216 conversion functions.
267    pub fn new(ndi: &Ndi) -> Result<Self> {
268        Ok(Self {
269            conversion: ndi.bind()?,
270        })
271    }
272
273    /// Unpack V210 into an existing P216 frame with matching dimensions.
274    ///
275    /// `source` contains native 32-bit V210 words and complete row storage. Only
276    /// samples are replaced: destination timecode, timestamps, metadata and frame
277    /// headers remain unchanged. P216 samples contain the ten bits shifted left
278    /// by six. Extra source words and row padding are ignored.
279    ///
280    /// # Errors
281    ///
282    /// [`Error::InvalidFrame`] when `destination` is not a P216 frame of the
283    /// layout's dimensions, or `source` is shorter than the layout's storage.
284    /// `destination` is then unchanged.
285    #[doc(alias = "NDIlib_util_V210_to_P216")]
286    pub fn v210_to_p216(
287        &self,
288        layout: V210Layout,
289        source: &[u32],
290        destination: &mut VideoFrame,
291    ) -> Result<()> {
292        layout.check_p216(destination)?;
293        self.unpack(layout, source, destination)
294    }
295
296    /// Unpack `source` into the checked destination frame's own P216 layout.
297    fn unpack(&self, layout: V210Layout, source: &[u32], p216: &mut VideoFrame) -> Result<()> {
298        layout.check_storage(source.len())?;
299        let mut output = layout.p216_output_descriptor(p216);
300        let input = layout.v210_descriptor(output, source.as_ptr());
301        // SAFETY: `source` holds every word of the layout's rows and `p216`
302        // exactly the P216 frame `output` describes, both initialized and
303        // borrowed apart for the call, which keeps no reference. The V210
304        // words are aligned `u32`s, and the NDI SDK documentation requires
305        // no alignment of a video frame's data, so the P216 bytes need none.
306        unsafe {
307            self.conversion
308                .NDIlib_util_V210_to_P216(&input, &mut output)
309        };
310        Ok(())
311    }
312
313    /// Pack P216 into reusable V210 storage, discarding each sample's low six bits.
314    ///
315    /// Active output words are initialized to zero before the native call because
316    /// the SDK preserves unused bits through read/modify/write operations. Their
317    /// two unused high bits therefore remain zero. Row padding and extra trailing
318    /// words are unchanged. V210 utility buffers carry no frame metadata.
319    ///
320    /// Accepts owned, captured, FrameSync and external borrowed [`VideoSource`]
321    /// inputs, including padded P216 planes. The native utility reads the original
322    /// active rows with their validated stride; no intermediate pixel copy or
323    /// wrapper allocation is made. The source borrow lasts through the call.
324    ///
325    /// # Errors
326    ///
327    /// [`Error::InvalidFrame`] when `source` is not a P216 frame of the
328    /// layout's dimensions, or `destination` is shorter than the layout's
329    /// storage. `destination` is then unchanged.
330    #[doc(alias = "NDIlib_util_P216_to_V210")]
331    pub fn p216_to_v210(
332        &self,
333        source: &(impl VideoSource + ?Sized),
334        layout: V210Layout,
335        destination: &mut [u32],
336    ) -> Result<()> {
337        layout.check_p216(source)?;
338        self.pack_descriptor(layout, source.video_descriptor(), destination)
339    }
340
341    /// Pack `p216`, the samples of the packed P216 frame of `layout`'s
342    /// dimensions, which may start at any address, into `destination`.
343    #[cfg(test)]
344    fn pack(&self, layout: V210Layout, p216: &[u8], destination: &mut [u32]) -> Result<()> {
345        let input = layout.p216_descriptor(p216)?;
346        self.pack_descriptor(layout, input, destination)
347    }
348
349    /// `input` borrows a validated P216 source, packed or strided, with the
350    /// dimensions of `layout`, for this entire synchronous native call.
351    fn pack_descriptor(
352        &self,
353        layout: V210Layout,
354        input: NDIlib_video_frame_v2_t,
355        destination: &mut [u32],
356    ) -> Result<()> {
357        layout.check_storage(destination.len())?;
358        let stride_words = layout.stride / 4;
359        let active = layout.active_words_per_row();
360        for row in destination[..layout.words].chunks_exact_mut(stride_words) {
361            row[..active].fill(0);
362        }
363        let mut output = layout.v210_descriptor(input, destination.as_mut_ptr());
364        // SAFETY: The sealed source lends the validated P216 planes `input`
365        // describes, with every active row initialized. Width is a complete
366        // six-pixel group; Processing.NDI.utilities.h P216_to_V210 consumes
367        // the source's row stride, so no row padding or extra pixels need be
368        // initialized. `destination` holds every word of its checked rows,
369        // borrowed apart for this call, which keeps no reference. The V210
370        // words are aligned `u32`s, and the NDI SDK documentation requires
371        // no alignment of a video frame's data, so the P216 bytes need none.
372        unsafe {
373            self.conversion
374                .NDIlib_util_P216_to_V210(&input, &mut output)
375        };
376        Ok(())
377    }
378}
379
380#[cfg(test)]
381mod tests {
382    use super::*;
383    use crate::Timecode;
384
385    #[test]
386    fn p216_output_reports_initialized_storage_without_extra_room() {
387        let mut frame = VideoFrame::builder()
388            .resolution(12, 4)
389            .pixel_format(PixelFormat::P216)
390            .build()
391            .unwrap();
392        let output = P216Output::new(&mut frame);
393        assert_eq!(
394            output.initialized(),
395            crate::frames::Initialized::Storage { room_after: 0 }
396        );
397        assert!(crate::frames::VideoPartsExt::can_send_direct(&output));
398    }
399
400    #[test]
401    fn p216_conversion_descriptor_fits_its_borrowed_storage() {
402        let layout = V210Layout::new(12, 32).unwrap();
403        let mut destination = VideoFrame::builder()
404            .resolution(12, 32)
405            .pixel_format(PixelFormat::P216)
406            .build()
407            .unwrap();
408        let raw = layout.p216_output_descriptor(&mut destination);
409        let storage = destination.data();
410        crate::frames::descriptor_tests::assert_extent(&raw, storage.as_ptr(), storage.len());
411        let raw = layout.p216_descriptor(storage).unwrap();
412        crate::frames::descriptor_tests::assert_extent(&raw, storage.as_ptr(), storage.len());
413        assert!(crate::BorrowedVideoFrame::builder(
414            &storage[..storage.len() - 1],
415            12,
416            32,
417            PixelFormat::P216,
418        )
419        .build()
420        .is_err());
421    }
422
423    #[test]
424    fn complete_group_geometry_and_checked_caps() {
425        let width = 4_294_967_292;
426        let Err(Error::InvalidFrame(crate::FrameDefect::Layout(expected))) =
427            ValidatedVideoLayout::new_uncompressed(PixelFormat::P216, width, 1, None)
428        else {
429            panic!("oversized P216 geometry must be refused");
430        };
431        for result in [
432            V210Layout::new(width, 1),
433            V210Layout::with_line_stride_bytes(width, 1, 4),
434        ] {
435            assert!(matches!(
436                result,
437                Err(Error::InvalidFrame(crate::FrameDefect::Layout(actual))) if actual == expected
438            ));
439        }
440        for width in [0, 1, 2, 4, 8, 10, i32::MAX.unsigned_abs(), u32::MAX] {
441            assert!(V210Layout::new(width, 1).is_err());
442        }
443        for height in [0, i32::MAX.unsigned_abs(), u32::MAX] {
444            assert!(V210Layout::new(6, height).is_err());
445        }
446        for stride in [0, 12, 17, 18, i32::MAX.unsigned_abs() as usize, usize::MAX] {
447            assert!(V210Layout::with_line_stride_bytes(6, 1, stride).is_err());
448        }
449        for width in [6u32, 12, 18, 48, 1920, 3840, 12_288] {
450            for height in [1u32, 3, 1080, 2160, 65_536] {
451                for padding in [0, 4, 128] {
452                    let stride = width as usize / 6 * 16 + padding;
453                    let actual = V210Layout::with_line_stride_bytes(width, height, stride);
454                    let packed = stride as i128 * i128::from(height);
455                    let planar = i128::from(width) * i128::from(height) * 4;
456                    assert_eq!(
457                        actual.is_ok(),
458                        packed <= MAX_VIDEO_BYTES as i128 && planar <= MAX_VIDEO_BYTES as i128
459                    );
460                    if let Ok(layout) = actual {
461                        assert_eq!(layout.width(), width);
462                        assert_eq!(layout.height(), height);
463                        assert_eq!(layout.required_words(), packed as usize / 4);
464                        assert_eq!(layout.line_stride_bytes(), stride);
465                        assert_eq!(layout.active_words_per_row(), width as usize / 6 * 4);
466                    }
467                }
468            }
469        }
470    }
471
472    fn triplet(a: u32, b: u32, c: u32) -> u32 {
473        a | b << 10 | c << 20
474    }
475
476    #[test]
477    fn native_complete_groups_roundtrip_with_independent_sample_oracle() {
478        let Some(ndi) = crate::test_support::ndi() else {
479            return;
480        };
481        let converter = VideoConverter::new(&ndi).unwrap();
482        let y = |x: usize, row: usize| ((x * 37 + row * 61 + 17) & 1023) as u32;
483        let u = |pair: usize, row: usize| ((pair * 53 + row * 19 + 101) & 1023) as u32;
484        let v = |pair: usize, row: usize| ((pair * 29 + row * 43 + 509) & 1023) as u32;
485        for width in [6, 12, 18, 48, 1920] {
486            for height in [1, 3] {
487                for padding_words in [0, 1, 4] {
488                    let layout = V210Layout::with_line_stride_bytes(
489                        width,
490                        height,
491                        width as usize / 6 * 16 + padding_words * 4,
492                    )
493                    .unwrap();
494                    let stride = layout.line_stride_bytes() / 4;
495                    let mut packed = vec![0xa5a5_a5a5u32; layout.required_words() + 2];
496                    let source = &mut packed[1..layout.required_words() + 1];
497                    for row in 0..height as usize {
498                        for x in (0..width as usize).step_by(6) {
499                            let words = &mut source[row * stride + x / 6 * 4..][..4];
500                            words.copy_from_slice(&[
501                                triplet(u(x / 2, row), y(x, row), v(x / 2, row)),
502                                triplet(y(x + 1, row), u(x / 2 + 1, row), y(x + 2, row)),
503                                triplet(v(x / 2 + 1, row), y(x + 3, row), u(x / 2 + 2, row)),
504                                triplet(y(x + 4, row), v(x / 2 + 2, row), y(x + 5, row)),
505                            ]);
506                            for word in words {
507                                *word |= 0xc000_0000;
508                            }
509                        }
510                    }
511                    let mut frame = VideoFrame::builder()
512                        .resolution(width, height)
513                        .pixel_format(PixelFormat::P216)
514                        .timecode(Timecode::from_ticks(123))
515                        .metadata("<preserve/>")
516                        .build()
517                        .unwrap();
518                    let address = frame.data().as_ptr();
519                    let (result, allocations) = crate::test_alloc::allocation_count(|| {
520                        converter.v210_to_p216(layout, source, &mut frame)
521                    });
522                    result.unwrap();
523                    assert_eq!(allocations, 0);
524                    assert_eq!(frame.data().as_ptr(), address);
525                    assert_eq!(frame.timecode(), Timecode::from_ticks(123));
526                    assert_eq!(frame.timestamp(), None);
527                    assert_eq!(frame.metadata(), Some("<preserve/>"));
528                    let plane_samples = width as usize * height as usize;
529                    for row in 0..height as usize {
530                        for x in 0..width as usize {
531                            let sample = row * width as usize + x;
532                            let read = |index: usize| {
533                                u16::from_ne_bytes(
534                                    frame.data()[index * 2..index * 2 + 2].try_into().unwrap(),
535                                )
536                            };
537                            assert_eq!(read(sample), (y(x, row) << 6) as u16);
538                            assert_eq!(
539                                read(plane_samples + sample),
540                                ((if x % 2 == 0 {
541                                    u(x / 2, row)
542                                } else {
543                                    v(x / 2, row)
544                                }) << 6) as u16
545                            );
546                        }
547                    }
548                    // Low six P216 bits are discarded; output unused V210 bits
549                    // are canonical zero rather than inherited from old storage.
550                    for bytes in frame.data_mut().as_chunks_mut::<2>().0 {
551                        let sample = u16::from_ne_bytes(*bytes) | 63;
552                        bytes.copy_from_slice(&sample.to_ne_bytes());
553                    }
554                    let mut back = vec![0x5a5a_5a5au32; layout.required_words() + 2];
555                    converter
556                        .p216_to_v210(&frame, layout, &mut back[1..layout.required_words() + 1])
557                        .unwrap();
558                    for row in 0..height as usize {
559                        for word in 0..layout.active_words_per_row() {
560                            assert_eq!(
561                                back[1 + row * stride + word],
562                                source[row * stride + word] & 0x3fff_ffff
563                            );
564                        }
565                        for word in layout.active_words_per_row()..stride {
566                            assert_eq!(back[1 + row * stride + word], 0x5a5a_5a5a);
567                        }
568                    }
569                    assert_eq!(packed[0], 0xa5a5_a5a5);
570                    assert_eq!(*packed.last().unwrap(), 0xa5a5_a5a5);
571                    assert_eq!(back[0], 0x5a5a_5a5a);
572                    assert_eq!(*back.last().unwrap(), 0x5a5a_5a5a);
573                }
574            }
575        }
576    }
577
578    /// P216 samples need no alignment: the SDK documents none for a video
579    /// frame's data, and the crate reads them only as bytes. Samples at an
580    /// odd address, which a frame's allocation may have under another global
581    /// allocator, convert exactly as the frame's own do; storage of the wrong
582    /// size is refused.
583    #[test]
584    fn p216_samples_at_an_odd_address_convert_like_a_frame() {
585        let Some(ndi) = crate::test_support::ndi() else {
586            return;
587        };
588        let converter = VideoConverter::new(&ndi).unwrap();
589        for (width, height) in [(6, 1), (48, 3), (1920, 4)] {
590            let layout = V210Layout::new(width, height).unwrap();
591            let source: Vec<u32> = (0..layout.required_words() as u32)
592                .map(|word| word.wrapping_mul(0x9e37_79b9) & 0x3fff_ffff)
593                .collect();
594            let mut frame = VideoFrame::builder()
595                .resolution(width, height)
596                .pixel_format(PixelFormat::P216)
597                .build()
598                .unwrap();
599            converter.v210_to_p216(layout, &source, &mut frame).unwrap();
600
601            let len = frame.data().len();
602            let mut storage = vec![0u8; len + 1];
603            let odd = usize::from(storage.as_ptr().addr().is_multiple_of(2));
604            let p216 = &mut storage[odd..odd + len];
605            assert!(!p216.as_ptr().addr().is_multiple_of(2));
606            // Test the native utility's odd-address output independently of
607            // the public API, whose destination is an owned frame. Substitute
608            // this equally sized exclusive slice into the validated descriptor.
609            let mut output = layout.p216_output_descriptor(&mut frame);
610            output.p_data = p216.as_mut_ptr();
611            crate::frames::descriptor_tests::assert_extent(&output, p216.as_ptr(), p216.len());
612            let input = layout.v210_descriptor(output, source.as_ptr());
613            // SAFETY: both descriptors retain their validated geometry; source
614            // covers the V210 words and p216 covers the output extent, with an
615            // exclusive writable pointer, for this synchronous call.
616            unsafe {
617                converter
618                    .conversion
619                    .NDIlib_util_V210_to_P216(&input, &mut output)
620            };
621            assert_eq!(&*p216, frame.data());
622
623            let mut packed = vec![0; layout.required_words()];
624            converter.pack(layout, p216, &mut packed).unwrap();
625            let mut expected = vec![0; layout.required_words()];
626            converter
627                .p216_to_v210(&frame, layout, &mut expected)
628                .unwrap();
629            assert_eq!(packed, expected);
630
631            assert!(crate::BorrowedVideoFrame::builder(
632                &p216[1..],
633                width,
634                height,
635                PixelFormat::P216,
636            )
637            .build()
638            .is_err());
639        }
640    }
641
642    #[test]
643    fn invalid_buffers_and_mismatched_frames_are_rejected_before_writes() {
644        let Some(ndi) = crate::test_support::ndi() else {
645            return;
646        };
647        let converter = VideoConverter::new(&ndi).unwrap();
648        let layout = V210Layout::new(6, 1).unwrap();
649        let mut output = [0x1234_5678; 4];
650        let wrong = VideoFrame::builder().resolution(6, 1).build().unwrap();
651        assert!(converter.p216_to_v210(&wrong, layout, &mut output).is_err());
652        assert_eq!(output, [0x1234_5678; 4]);
653        let mut frame = VideoFrame::builder()
654            .resolution(6, 1)
655            .pixel_format(PixelFormat::P216)
656            .build()
657            .unwrap();
658        assert!(converter.v210_to_p216(layout, &[0; 3], &mut frame).is_err());
659        assert!(converter
660            .p216_to_v210(&frame, layout, &mut output[..3])
661            .is_err());
662        assert_eq!(output, [0x1234_5678; 4]);
663        let other_size = V210Layout::new(12, 1).unwrap();
664        assert!(converter
665            .v210_to_p216(other_size, &[0; 8], &mut frame)
666            .is_err());
667        assert!(frame.data().iter().all(|byte| *byte == 0));
668    }
669
670    #[test]
671    fn strided_borrowed_and_captured_p216_convert_without_pixel_copies() {
672        use crate::{capture::Guard, BorrowedVideoFrame, FrameSyncVideoRef, VideoFrameRef};
673        let Some(ndi) = crate::test_support::ndi() else {
674            return;
675        };
676        let converter = VideoConverter::new(&ndi).unwrap();
677        for width in [6, 12, 48] {
678            for height in [1, 3] {
679                for padding in [0, 2, 8, 32] {
680                    let stride = width as usize * 2 + padding;
681                    let mut storage = vec![0xabu8; stride * height as usize * 2];
682                    for plane in 0..2 {
683                        for row in 0..height as usize {
684                            for sample in 0..width as usize {
685                                let offset = (plane * height as usize + row) * stride + sample * 2;
686                                let value =
687                                    ((plane * 97 + row * 53 + sample * 29) as u16 & 1023) << 6;
688                                storage[offset..offset + 2].copy_from_slice(&value.to_ne_bytes());
689                            }
690                        }
691                    }
692                    let borrowed =
693                        BorrowedVideoFrame::builder(&storage, width, height, PixelFormat::P216)
694                            .line_stride_bytes(stride)
695                            .metadata(c"<p216/>")
696                            .build()
697                            .unwrap();
698                    let raw = borrowed.video_descriptor();
699                    // SAFETY: Both synthetic guards borrow storage and static
700                    // metadata for this test, and neither callback frees them.
701                    let receiver = unsafe {
702                        VideoFrameRef::new(Guard::with_test_free(ptr::null_mut(), raw, |_, _| {}))
703                    }
704                    .unwrap();
705                    let framesync = unsafe {
706                        FrameSyncVideoRef::new(Guard::with_test_free(
707                            ptr::null_mut(),
708                            raw,
709                            |_, _| {},
710                        ))
711                    }
712                    .unwrap();
713                    let layout = V210Layout::with_line_stride_bytes(
714                        width,
715                        height,
716                        width as usize / 6 * 16 + 4,
717                    )
718                    .unwrap();
719                    let owned = VideoSource::to_owned(&borrowed);
720                    let mut expected = vec![0x9e37_79b9; layout.required_words() + 2];
721                    converter
722                        .p216_to_v210(&owned, layout, &mut expected[1..])
723                        .unwrap();
724                    for source in [&borrowed as &dyn VideoSource, &receiver, &framesync] {
725                        assert_eq!(source.video_descriptor().p_data, raw.p_data);
726                        let mut destination = vec![0x9e37_79b9; layout.required_words() + 2];
727                        let (result, allocations) = crate::test_alloc::allocation_count(|| {
728                            converter.p216_to_v210(source, layout, &mut destination[1..])
729                        });
730                        result.unwrap();
731                        assert_eq!(allocations, 0);
732                        assert_eq!(
733                            destination, expected,
734                            "width {width}, height {height}, padding {padding}"
735                        );
736                    }
737                }
738            }
739        }
740    }
741}