1#[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#[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 pub fn new(width: u32, height: u32) -> Result<Self> {
42 Self::checked(width, height, None)
43 }
44
45 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 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 pub const fn width(self) -> u32 {
82 self.width
83 }
84 pub const fn height(self) -> u32 {
86 self.height
87 }
88 pub const fn line_stride_bytes(self) -> usize {
90 self.stride
91 }
92 pub const fn required_words(self) -> usize {
94 self.words
95 }
96 pub const fn active_words_per_row(self) -> usize {
98 self.width as usize / 6 * 4
99 }
100
101 fn sdk_line_stride(self) -> i32 {
103 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 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 #[cfg(test)]
143 fn p216_descriptor(self, data: &[u8]) -> Result<NDIlib_video_frame_v2_t> {
144 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 let frame =
159 crate::BorrowedVideoFrame::builder(data, self.width, self.height, PixelFormat::P216)
160 .build()?;
161 Ok(frame.video_descriptor())
162 }
163
164 fn p216_output_descriptor(self, destination: &mut VideoFrame) -> NDIlib_video_frame_v2_t {
168 P216Output::new(destination).video_descriptor()
169 }
170
171 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.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
189struct 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 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
218unsafe 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
243pub 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 pub fn new(ndi: &Ndi) -> Result<Self> {
268 Ok(Self {
269 conversion: ndi.bind()?,
270 })
271 }
272
273 #[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 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 unsafe {
307 self.conversion
308 .NDIlib_util_V210_to_P216(&input, &mut output)
309 };
310 Ok(())
311 }
312
313 #[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 #[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 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 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 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 #[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 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 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 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}