1use std::borrow::Cow;
33
34#[cfg(target_os = "linux")]
35use std::os::fd::{AsFd, AsRawFd, BorrowedFd, OwnedFd};
36#[cfg(target_os = "linux")]
37use std::sync::Arc;
38
39use moq_net::Timestamp;
40
41use yuv::{YuvChromaSubsampling, YuvConversionMode, YuvPlanarImageMut, rgba_to_yuv420};
42
43use crate::{Color, Error, Size};
44
45#[cfg(any(target_os = "windows", test))]
46mod processor;
47
48#[non_exhaustive]
55pub struct Frame {
56 pub timestamp: Timestamp,
61 pub surface: Surface,
63}
64
65impl Frame {
66 pub fn new(timestamp: Timestamp, surface: Surface) -> Self {
68 Self { timestamp, surface }
69 }
70
71 pub fn size(&self) -> Size {
73 Size::new(self.surface.width(), self.surface.height())
74 }
75
76 pub fn resize(&self, size: Size, config: &crate::resize::Config) -> Result<Frame, Error> {
82 Ok(Frame {
83 timestamp: self.timestamp,
84 surface: self.surface.resize(size, config)?,
85 })
86 }
87}
88
89#[cfg(target_os = "linux")]
94#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
95pub struct DrmFormat(u32);
96
97#[cfg(target_os = "linux")]
98impl DrmFormat {
99 pub const NV12: Self = Self::from_bytes(*b"NV12");
101 pub const YUV420: Self = Self::from_bytes(*b"YU12");
103 pub const XRGB8888: Self = Self::from_bytes(*b"XR24");
105 pub const ARGB8888: Self = Self::from_bytes(*b"AR24");
107 pub const XBGR8888: Self = Self::from_bytes(*b"XB24");
109 pub const ABGR8888: Self = Self::from_bytes(*b"AB24");
111
112 pub const fn from_bytes(bytes: [u8; 4]) -> Self {
114 Self(u32::from_le_bytes(bytes))
115 }
116
117 pub const fn as_raw(self) -> u32 {
119 self.0
120 }
121}
122
123#[cfg(target_os = "linux")]
125#[derive(Clone, Copy, Debug, PartialEq, Eq)]
126pub struct DmaBufPlane {
127 offset: u32,
128 stride: u32,
129}
130
131#[cfg(target_os = "linux")]
132impl DmaBufPlane {
133 pub const fn new(offset: u32, stride: u32) -> Self {
135 Self { offset, stride }
136 }
137
138 pub const fn offset(&self) -> u32 {
140 self.offset
141 }
142
143 pub const fn stride(&self) -> u32 {
145 self.stride
146 }
147}
148
149#[cfg(target_os = "linux")]
155pub struct DmaBufExport {
156 fd: OwnedFd,
157 #[cfg_attr(
158 not(feature = "render"),
159 allow(
160 dead_code,
161 reason = "the producer's lease, held so its buffer outlives the descriptor. Only the renderer ever reads it back out, through `into_parts`, so without that feature the field is pure keepalive rather than dead"
162 )
163 )]
164 inner: Arc<dyn DmaBufFrame>,
165}
166
167#[cfg(target_os = "linux")]
174const DMA_BUF_FENCE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(500);
175
176#[cfg(target_os = "linux")]
177pub(crate) fn wait_dma_buf_readable(fd: BorrowedFd<'_>) -> std::io::Result<()> {
178 let mut event = libc::pollfd {
179 fd: fd.as_raw_fd(),
180 events: libc::POLLIN,
181 revents: 0,
182 };
183 let deadline = kio::clock::now().saturating_add(DMA_BUF_FENCE_TIMEOUT);
184 loop {
185 let remaining = deadline.saturating_duration_since(kio::clock::now());
188 if remaining.is_zero() {
189 return Err(std::io::Error::from(std::io::ErrorKind::TimedOut));
190 }
191 let result = unsafe {
194 libc::poll(
195 &mut event,
196 1,
197 remaining.as_millis().min(i32::MAX as u128) as libc::c_int,
198 )
199 };
200 if result > 0 && event.revents & libc::POLLIN != 0 {
201 return Ok(());
202 }
203 if result == 0 {
204 return Err(std::io::Error::from(std::io::ErrorKind::TimedOut));
205 }
206 if result < 0 {
207 let error = std::io::Error::last_os_error();
208 if error.kind() == std::io::ErrorKind::Interrupted {
209 continue;
210 }
211 return Err(error);
212 }
213 return Err(std::io::Error::other(format!(
214 "DMA-BUF poll returned events {:#x}",
215 event.revents
216 )));
217 }
218}
219
220#[cfg(target_os = "linux")]
221impl DmaBufExport {
222 pub fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
224 std::os::fd::AsFd::as_fd(&self.fd)
225 }
226
227 #[cfg(feature = "render")]
230 pub(crate) fn into_parts(self) -> (OwnedFd, Arc<dyn DmaBufFrame>) {
231 (self.fd, self.inner)
232 }
233}
234
235#[cfg(target_os = "linux")]
236impl std::os::fd::AsFd for DmaBufExport {
237 fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
238 std::os::fd::AsFd::as_fd(&self.fd)
239 }
240}
241
242#[cfg(target_os = "linux")]
243impl std::fmt::Debug for DmaBufExport {
244 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245 f.debug_struct("DmaBufExport").finish_non_exhaustive()
246 }
247}
248
249#[cfg(target_os = "linux")]
257#[derive(Clone)]
258pub struct DmaBuf {
259 format: DrmFormat,
260 modifier: u64,
261 width: u32,
262 height: u32,
263 planes: Vec<DmaBufPlane>,
264 color: Option<Color>,
265 inner: Arc<dyn DmaBufFrame>,
266}
267
268#[cfg(target_os = "linux")]
269impl std::fmt::Debug for DmaBuf {
270 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
271 f.debug_struct("DmaBuf")
272 .field("format", &self.format)
273 .field("modifier", &format_args!("{:#x}", self.modifier))
274 .field("width", &self.width)
275 .field("height", &self.height)
276 .field("planes", &self.planes)
277 .finish_non_exhaustive()
278 }
279}
280
281#[cfg(target_os = "linux")]
282impl DmaBuf {
283 #[cfg_attr(
288 not(test),
289 allow(dead_code, reason = "only tests build one until an external producer needs it")
290 )]
291 pub(crate) fn new<T: Send + Sync + 'static>(fd: OwnedFd, layout: DmaBufLayout, owner: T) -> Result<Self, Error> {
292 Self::adopt(layout, Arc::new(ExternalDmaBuf { fd, _owner: owner }))
293 }
294
295 pub(crate) fn adopt(layout: DmaBufLayout, inner: Arc<dyn DmaBufFrame>) -> Result<Self, Error> {
296 let DmaBufLayout {
297 format,
298 modifier,
299 size,
300 planes,
301 color,
302 } = layout;
303 size.validate("DMA-BUF")?;
304 if planes.is_empty() || planes.len() > 4 || planes.iter().any(|plane| plane.stride == 0) {
305 return Err(Error::Unsupported(
306 "DMA-BUF requires one to four planes with non-zero strides".into(),
307 ));
308 }
309 Ok(Self {
310 format,
311 modifier,
312 width: size.width,
313 height: size.height,
314 planes,
315 color,
316 inner,
317 })
318 }
319
320 pub fn export(&self) -> std::io::Result<DmaBufExport> {
322 let fd = self.inner.export()?;
323 wait_dma_buf_readable(fd.as_fd())?;
324 Ok(DmaBufExport {
325 fd,
326 inner: self.inner.clone(),
327 })
328 }
329
330 pub const fn format(&self) -> DrmFormat {
332 self.format
333 }
334
335 pub const fn modifier(&self) -> u64 {
337 self.modifier
338 }
339
340 pub const fn width(&self) -> u32 {
346 self.width
347 }
348
349 pub const fn height(&self) -> u32 {
352 self.height
353 }
354
355 pub fn planes(&self) -> &[DmaBufPlane] {
357 &self.planes
358 }
359
360 pub const fn color(&self) -> Option<Color> {
366 self.color
367 }
368}
369
370#[cfg(target_os = "linux")]
372#[derive(Clone, Debug)]
373pub(crate) struct DmaBufLayout {
374 pub(crate) format: DrmFormat,
376 pub(crate) modifier: u64,
378 pub(crate) size: Size,
380 pub(crate) planes: Vec<DmaBufPlane>,
382 pub(crate) color: Option<Color>,
384}
385
386#[cfg(target_os = "linux")]
387impl DmaBufLayout {
388 #[cfg(test)]
390 pub(crate) fn new(format: DrmFormat, size: Size, planes: Vec<DmaBufPlane>) -> Self {
391 Self {
392 format,
393 modifier: 0,
394 size,
395 planes,
396 color: None,
397 }
398 }
399}
400
401#[cfg(target_os = "linux")]
402struct ExternalDmaBuf<T: Send + Sync + 'static> {
403 fd: OwnedFd,
404 _owner: T,
405}
406
407#[cfg(target_os = "linux")]
408impl<T: Send + Sync + 'static> DmaBufFrame for ExternalDmaBuf<T> {
409 fn export(&self) -> std::io::Result<OwnedFd> {
410 self.fd.try_clone()
411 }
412 fn download_i420(&self) -> Result<I420, Error> {
413 Err(Error::Unsupported(
414 "external DMA-BUF surfaces have no CPU download fallback".into(),
415 ))
416 }
417}
418
419#[cfg(target_os = "linux")]
424pub(crate) trait DmaBufFrame: Send + Sync {
425 fn export(&self) -> std::io::Result<OwnedFd>;
426 fn download_i420(&self) -> Result<I420, Error>;
427}
428
429#[non_exhaustive]
448pub enum Surface {
449 #[cfg(apple)]
452 PixelBuffer(apple::PixelBuffer),
453 #[cfg(target_os = "windows")]
455 Texture(d3d11::Texture),
456 #[cfg(all(target_os = "linux", feature = "nvidia"))]
459 Cuda(cuda::Frame),
460 #[cfg(target_os = "linux")]
462 Vulkan(vulkan::Frame),
463 #[cfg(target_os = "linux")]
465 DmaBuf(DmaBuf),
466 #[cfg(all(target_os = "android", feature = "mediacodec"))]
469 HardwareBuffer(android::HardwareBuffer),
470 I420(I420),
472}
473
474impl Surface {
475 pub fn width(&self) -> u32 {
477 match self {
478 #[cfg(apple)]
479 Surface::PixelBuffer(s) => s.width,
480 #[cfg(target_os = "windows")]
481 Surface::Texture(t) => t.width,
482 #[cfg(all(target_os = "linux", feature = "nvidia"))]
483 Surface::Cuda(c) => c.width,
484 #[cfg(target_os = "linux")]
485 Surface::Vulkan(v) => v.width(),
486 #[cfg(target_os = "linux")]
487 Surface::DmaBuf(d) => d.width,
488 #[cfg(all(target_os = "android", feature = "mediacodec"))]
489 Surface::HardwareBuffer(b) => b.width,
490 Surface::I420(i) => i.width,
491 }
492 }
493
494 pub fn height(&self) -> u32 {
496 match self {
497 #[cfg(apple)]
498 Surface::PixelBuffer(s) => s.height,
499 #[cfg(target_os = "windows")]
500 Surface::Texture(t) => t.height,
501 #[cfg(all(target_os = "linux", feature = "nvidia"))]
502 Surface::Cuda(c) => c.height,
503 #[cfg(target_os = "linux")]
504 Surface::Vulkan(v) => v.height(),
505 #[cfg(target_os = "linux")]
506 Surface::DmaBuf(d) => d.height,
507 #[cfg(all(target_os = "android", feature = "mediacodec"))]
508 Surface::HardwareBuffer(b) => b.height,
509 Surface::I420(i) => i.height,
510 }
511 }
512
513 #[cfg(feature = "capture")]
517 pub(crate) fn retain(&self) -> Option<Self> {
518 Some(match self {
519 #[cfg(apple)]
520 Surface::PixelBuffer(s) => Surface::PixelBuffer(apple::PixelBuffer {
521 buffer: s.buffer.clone(),
522 width: s.width,
523 height: s.height,
524 color: s.color,
525 }),
526 #[cfg(target_os = "windows")]
527 Surface::Texture(t) => Surface::Texture(d3d11::Texture {
528 device: t.device.clone(),
529 texture: t.texture.clone(),
530 width: t.width,
531 height: t.height,
532 color: t.color,
533 }),
534 #[cfg(all(target_os = "linux", feature = "nvidia"))]
535 Surface::Cuda(c) => Surface::Cuda(c.clone()),
536 #[cfg(target_os = "linux")]
537 Surface::Vulkan(v) => Surface::Vulkan(v.clone()),
538 #[cfg(target_os = "linux")]
539 Surface::DmaBuf(d) => Surface::DmaBuf(d.clone()),
540 #[cfg(all(target_os = "android", feature = "mediacodec"))]
541 Surface::HardwareBuffer(_) => return None,
542 Surface::I420(i) => Surface::I420(i.clone()),
543 })
544 }
545
546 pub fn rgba(rgba: &[u8], size: Size) -> Result<Self, Error> {
555 size.validate("RGBA frame")?;
556 let expected = size.byte_len(4, "RGBA frame")?;
557 if rgba.len() != expected {
558 return Err(Error::codec(anyhow::anyhow!(
559 "RGBA buffer is {} bytes, expected {expected} for {size}",
560 rgba.len()
561 )));
562 }
563 Ok(Surface::I420(I420::from_rgba(
564 rgba,
565 size.width.checked_mul(4).ok_or_else(|| {
566 Error::codec(anyhow::anyhow!(
567 "RGBA frame {size}: row stride is too large to represent"
568 ))
569 })?,
570 size,
571 )?))
572 }
573
574 pub fn resize(&self, size: Size, config: &crate::resize::Config) -> Result<Surface, Error> {
587 let output = config.output.resolve(self);
588 let _ = output;
590 size.validate("resize to")?;
591
592 let implied = self
593 .color()
594 .unwrap_or_else(|| Color::infer(Size::new(self.width(), self.height())));
595 let mut resized = match self {
596 Surface::I420(i420) => Surface::I420(i420.resize(size)?),
597 #[cfg(apple)]
598 Surface::PixelBuffer(pixels) if output == crate::Output::Cpu => Surface::I420(pixels.download_i420()?.resize(size)?),
599 #[cfg(apple)]
600 Surface::PixelBuffer(pixels) => match pixels.resize(size.width, size.height) {
601 Ok(scaled) => Surface::PixelBuffer(scaled),
602 Err(err) => {
605 static WARN_ONCE: std::sync::Once = std::sync::Once::new();
606 WARN_ONCE.call_once(|| tracing::warn!(%err, "GPU resize failed; falling back to the CPU"));
607 Surface::I420(pixels.download_i420()?.resize(size)?)
608 }
609 },
610 #[cfg(all(target_os = "linux", feature = "nvidia"))]
611 Surface::Cuda(cuda) if output == crate::Output::Cpu => Surface::I420(cuda.download_i420()?.resize(size)?),
612 #[cfg(all(target_os = "linux", feature = "nvidia"))]
613 Surface::Cuda(cuda) => match cuda.resize(size) {
614 Ok(scaled) => Surface::Cuda(scaled),
615 Err(err) => {
618 static WARN_ONCE: std::sync::Once = std::sync::Once::new();
619 WARN_ONCE.call_once(|| tracing::warn!(%err, "GPU resize failed; falling back to the CPU"));
620 Surface::I420(cuda.download_i420()?.resize(size)?)
621 }
622 },
623 #[cfg(target_os = "linux")]
624 Surface::Vulkan(_) => {
625 return Err(Error::Unsupported(
626 "External Vulkan surfaces require a GPU consumer and cannot be resized or downloaded".into(),
627 ));
628 }
629 #[cfg(target_os = "windows")]
630 Surface::Texture(texture) if output == crate::Output::Cpu => Surface::I420(texture.download_i420()?.resize(size)?),
631 #[cfg(target_os = "windows")]
632 Surface::Texture(texture) => match texture.resize(size.width, size.height) {
633 Ok(scaled) => Surface::Texture(scaled),
634 Err(err) => {
638 static WARN_ONCE: std::sync::Once = std::sync::Once::new();
639 WARN_ONCE.call_once(|| tracing::warn!(%err, "GPU resize failed; falling back to the CPU"));
640 Surface::I420(texture.download_i420()?.resize(size)?)
641 }
642 },
643 #[cfg(all(target_os = "linux", feature = "vaapi"))]
648 Surface::DmaBuf(buffer) if output == crate::Output::Native => {
649 match vaapi::resize(buffer, size, config.device.render()) {
650 Ok(scaled) => Surface::DmaBuf(scaled),
651 Err(err) => {
652 static WARN_ONCE: std::sync::Once = std::sync::Once::new();
653 WARN_ONCE.call_once(|| tracing::warn!(%err, "GPU resize failed; falling back to the CPU"));
654 Surface::I420(buffer.inner.download_i420()?.resize(size)?)
655 }
656 }
657 }
658 #[allow(
659 unreachable_patterns,
660 reason = "the other surfaces exist only on some platforms and features"
661 )]
662 other => Surface::I420(other.to_i420()?.into_owned().resize(size)?),
663 };
664 resized.label(implied);
665 Ok(resized)
666 }
667
668 pub fn into_i420(self) -> Result<I420, Error> {
676 match self {
677 Surface::I420(i420) => Ok(i420),
678 #[allow(
679 unreachable_patterns,
680 reason = "the other surfaces exist only on some platforms and features"
681 )]
682 other => Ok(other.to_i420()?.into_owned()),
683 }
684 }
685
686 pub fn to_rgba(&self, config: &crate::convert::Config) -> Result<crate::convert::Rgba, Error> {
693 crate::convert::rgba(self, config)
694 }
695
696 #[cfg(apple)]
710 pub fn into_pixel_buffer(
711 self,
712 ) -> Result<objc2_core_foundation::CFRetained<objc2_core_video::CVPixelBuffer>, Error> {
713 match self {
714 Surface::PixelBuffer(pixels) => Ok(pixels.buffer),
715 Surface::I420(i420) => apple::upload_i420(&i420),
716 }
717 }
718
719 pub fn color(&self) -> Option<Color> {
730 match self {
731 #[cfg(apple)]
732 Surface::PixelBuffer(s) => s.color(),
733 #[cfg(target_os = "windows")]
734 Surface::Texture(texture) => texture.color,
735 #[cfg(all(target_os = "linux", feature = "nvidia"))]
736 Surface::Cuda(c) => c.color(),
737 #[cfg(target_os = "linux")]
738 Surface::Vulkan(_) => None,
739 #[cfg(target_os = "linux")]
740 Surface::DmaBuf(d) => d.color,
741 #[cfg(all(target_os = "android", feature = "mediacodec"))]
742 Surface::HardwareBuffer(b) => b.color,
743 Surface::I420(i) => i.color(),
744 }
745 }
746
747 pub(crate) fn label(&mut self, color: Color) {
754 let slot = match self {
755 #[cfg(apple)]
756 Surface::PixelBuffer(buffer) => &mut buffer.color,
757 #[cfg(target_os = "windows")]
758 Surface::Texture(texture) => &mut texture.color,
759 #[cfg(all(target_os = "linux", feature = "nvidia"))]
760 Surface::Cuda(cuda) => &mut cuda.color,
761 #[cfg(target_os = "linux")]
762 Surface::Vulkan(_) => return,
763 #[cfg(target_os = "linux")]
764 Surface::DmaBuf(buffer) => &mut buffer.color,
765 #[cfg(all(target_os = "android", feature = "mediacodec"))]
766 Surface::HardwareBuffer(buffer) => &mut buffer.color,
767 Surface::I420(i420) => &mut i420.color,
768 };
769 slot.get_or_insert(color);
770 }
771
772 pub fn to_i420(&self) -> Result<Cow<'_, I420>, Error> {
781 match self {
782 #[cfg(apple)]
783 Surface::PixelBuffer(s) => Ok(Cow::Owned(s.download_i420()?)),
784 #[cfg(target_os = "windows")]
785 Surface::Texture(t) => Ok(Cow::Owned(t.download_i420()?)),
786 #[cfg(all(target_os = "linux", feature = "nvidia"))]
787 Surface::Cuda(c) => Ok(Cow::Owned(c.download_i420()?)),
788 #[cfg(target_os = "linux")]
789 Surface::Vulkan(_) => Err(Error::Unsupported(
790 "External Vulkan surfaces have no CPU mapping or download fallback".into(),
791 )),
792 #[cfg(target_os = "linux")]
793 Surface::DmaBuf(d) => Ok(Cow::Owned(d.inner.download_i420()?)),
794 #[cfg(all(target_os = "android", feature = "mediacodec"))]
795 Surface::HardwareBuffer(b) => Ok(Cow::Owned(b.download_i420()?)),
796 Surface::I420(i) => Ok(Cow::Borrowed(i)),
797 }
798 }
799}
800
801#[derive(Clone)]
804pub struct I420 {
805 pub(crate) width: u32,
806 pub(crate) height: u32,
807 pub(crate) data: Vec<u8>,
809 pub(crate) color: Option<Color>,
814}
815
816impl I420 {
817 pub fn new(size: Size, data: Vec<u8>) -> Result<Self, Error> {
824 size.validate("I420")?;
825 let expected = Self::len(size)?;
826 if data.len() != expected {
827 return Err(Error::codec(anyhow::anyhow!(
828 "I420 {size} needs {expected} bytes, got {}",
829 data.len()
830 )));
831 }
832 Ok(Self {
833 width: size.width,
834 height: size.height,
835 data,
836 color: None,
837 })
838 }
839
840 pub fn size(&self) -> Size {
842 Size::new(self.width, self.height)
843 }
844
845 pub fn width(&self) -> u32 {
847 self.width
848 }
849
850 pub fn height(&self) -> u32 {
852 self.height
853 }
854
855 pub fn data(&self) -> &[u8] {
857 &self.data
858 }
859
860 pub fn into_data(self) -> Vec<u8> {
862 self.data
863 }
864
865 pub fn color(&self) -> Option<Color> {
873 self.color
874 }
875
876 pub fn with_color(mut self, color: Color) -> Self {
879 self.color = Some(color);
880 self
881 }
882
883 pub fn len(size: Size) -> Result<usize, Error> {
885 size.validate("I420")?;
886 let luma = size.byte_len(1, "I420")?;
887 luma.checked_add(luma / 2)
888 .ok_or_else(|| Error::codec(anyhow::anyhow!("I420 {size}: byte length is too large to represent")))
889 }
890
891 pub(crate) fn from_rgba(rgba: &[u8], stride: u32, size: Size) -> Result<Self, Error> {
896 size.validate("RGBA frame")?;
897 let Size { width, height } = size;
898 let color = Color::infer(size);
899 let (range, matrix) = color.yuv();
900 let mut planar = YuvPlanarImageMut::alloc(width, height, YuvChromaSubsampling::Yuv420);
901 rgba_to_yuv420(&mut planar, rgba, stride, range, matrix, YuvConversionMode::Balanced)
902 .map_err(|e| Error::codec(anyhow::anyhow!("rgba_to_yuv420 failed for {width}x{height}: {e}")))?;
903 Self::pack(&planar, size, Some(color))
904 }
905
906 #[cfg(all(target_os = "linux", feature = "pipewire"))]
911 pub(crate) fn from_bgra(bgra: &[u8], stride: u32, size: Size) -> Result<Self, Error> {
912 use yuv::bgra_to_yuv420;
913
914 size.validate("BGRA frame")?;
915 let Size { width, height } = size;
916 let color = Color::infer(size);
917 let (range, matrix) = color.yuv();
918 let mut planar = YuvPlanarImageMut::alloc(width, height, YuvChromaSubsampling::Yuv420);
919 bgra_to_yuv420(&mut planar, bgra, stride, range, matrix, YuvConversionMode::Balanced)
920 .map_err(|e| Error::codec(anyhow::anyhow!("bgra_to_yuv420 failed for {width}x{height}: {e}")))?;
921 Self::pack(&planar, size, Some(color))
922 }
923
924 #[cfg_attr(
930 not(feature = "openh264"),
931 allow(dead_code, reason = "only the `openh264` feature uses it")
932 )]
933 pub(crate) fn from_planes(
934 y: &[u8],
935 u: &[u8],
936 v: &[u8],
937 y_stride: usize,
938 uv_stride: usize,
939 size: Size,
940 ) -> Result<Self, Error> {
941 size.validate("I420 planes")?;
942 let Size { width, height } = size;
943 let (w, h) = (width as usize, height as usize);
944 let (cw, ch) = (w / 2, h / 2);
945 if y_stride < w || uv_stride < cw {
946 return Err(Error::codec(anyhow::anyhow!(
947 "I420 {size}: strides {y_stride}/{uv_stride} are smaller than plane widths {w}/{cw}"
948 )));
949 }
950 let y_need = y_stride
951 .checked_mul(h)
952 .ok_or_else(|| Error::codec(anyhow::anyhow!("I420 {size}: luma plane length overflows")))?;
953 let uv_need = uv_stride
954 .checked_mul(ch)
955 .ok_or_else(|| Error::codec(anyhow::anyhow!("I420 {size}: chroma plane length overflows")))?;
956 if y.len() < y_need || u.len() < uv_need || v.len() < uv_need {
957 return Err(Error::codec(anyhow::anyhow!(
958 "I420 {size}: source planes are shorter than their declared strides"
959 )));
960 }
961
962 let mut data = vec![0u8; Self::len(size)?];
963 let (luma, chroma) = data.split_at_mut(w * h);
964 let (u_dst, v_dst) = chroma.split_at_mut(cw * ch);
965
966 for row in 0..h {
967 luma[row * w..row * w + w].copy_from_slice(&y[row * y_stride..row * y_stride + w]);
968 }
969 for row in 0..ch {
970 u_dst[row * cw..row * cw + cw].copy_from_slice(&u[row * uv_stride..row * uv_stride + cw]);
971 v_dst[row * cw..row * cw + cw].copy_from_slice(&v[row * uv_stride..row * uv_stride + cw]);
972 }
973
974 Ok(Self {
975 width,
976 height,
977 data,
978 color: None,
979 })
980 }
981
982 #[cfg(all(target_os = "linux", feature = "capture"))]
985 pub(crate) fn from_rgb(rgb: &[u8], size: Size) -> Result<Self, Error> {
986 use yuv::rgb_to_yuv420;
987
988 size.validate("RGB frame")?;
989 let Size { width, height } = size;
990 let stride = width.checked_mul(3).ok_or_else(|| {
991 Error::codec(anyhow::anyhow!(
992 "RGB frame {size}: row stride is too large to represent"
993 ))
994 })?;
995 let color = Color::infer(size);
996 let (range, matrix) = color.yuv();
997 let mut planar = YuvPlanarImageMut::alloc(width, height, YuvChromaSubsampling::Yuv420);
998 rgb_to_yuv420(&mut planar, rgb, stride, range, matrix, YuvConversionMode::Balanced)
999 .map_err(|e| Error::codec(anyhow::anyhow!("rgb_to_yuv420 failed for {width}x{height}: {e}")))?;
1000 Self::pack(&planar, size, Some(color))
1001 }
1002
1003 #[cfg(all(target_os = "linux", feature = "capture"))]
1010 pub(crate) fn from_mjpeg(jpeg: &[u8], size: Size) -> Result<Self, Error> {
1011 use zune_jpeg::zune_core::bytestream::ZCursor;
1012
1013 let mut decoder = zune_jpeg::JpegDecoder::new(ZCursor::new(jpeg));
1015 let rgb = decoder
1016 .decode()
1017 .map_err(|e| Error::codec(anyhow::anyhow!("MJPEG decode: {e:?}")))?;
1018 let (w, h) = decoder
1019 .dimensions()
1020 .ok_or_else(|| Error::codec(anyhow::anyhow!("MJPEG frame had no dimensions")))?;
1021 if w as u32 != size.width || h as u32 != size.height {
1022 return Err(Error::codec(anyhow::anyhow!(
1023 "MJPEG frame is {w}x{h}, not the negotiated {size}"
1024 )));
1025 }
1026 Self::from_rgb(&rgb, size)
1027 }
1028
1029 #[cfg(all(target_os = "linux", feature = "capture"))]
1033 pub(crate) fn from_yuyv(yuyv: &[u8], stride: u32, size: Size) -> Result<Self, Error> {
1034 use yuv::{YuvPackedImage, yuyv422_to_yuv420};
1035
1036 size.validate("YUYV frame")?;
1037 let Size { width, height } = size;
1038 let mut planar = YuvPlanarImageMut::alloc(width, height, YuvChromaSubsampling::Yuv420);
1039 let packed = YuvPackedImage {
1040 yuy: yuyv,
1041 yuy_stride: stride,
1042 width,
1043 height,
1044 };
1045 yuyv422_to_yuv420(&mut planar, &packed)
1046 .map_err(|e| Error::codec(anyhow::anyhow!("yuyv422_to_yuv420 failed for {width}x{height}: {e}")))?;
1047 Self::pack(&planar, size, None)
1050 }
1051
1052 #[cfg(any(
1057 target_os = "windows",
1058 all(target_os = "linux", any(feature = "pipewire", feature = "vaapi"))
1059 ))]
1060 pub(crate) fn from_nv12(nv12: &[u8], size: Size) -> Result<Self, Error> {
1061 size.validate("NV12 frame")?;
1062 let Size { width, height } = size;
1063 let luma = size.byte_len(1, "NV12 frame")?;
1064 let chroma = luma / 4;
1065 let need = Self::len(size)?;
1066 if nv12.len() < need {
1067 return Err(Error::codec(anyhow::anyhow!(
1068 "NV12 buffer too small: {} < {need} for {width}x{height}",
1069 nv12.len()
1070 )));
1071 }
1072
1073 let mut data = vec![0u8; need];
1074 data[..luma].copy_from_slice(&nv12[..luma]);
1075 let (u_dst, v_dst) = data[luma..].split_at_mut(chroma);
1076 deinterleave_uv(&nv12[luma..need], u_dst, v_dst);
1077 Ok(Self {
1078 width,
1079 height,
1080 data,
1081 color: None,
1082 })
1083 }
1084
1085 pub(crate) fn resize(&self, size: Size) -> Result<Self, Error> {
1089 use std::cell::RefCell;
1090
1091 use fast_image_resize::images::{Image, ImageRef};
1092 use fast_image_resize::{FilterType, PixelType, ResizeAlg, ResizeOptions, Resizer};
1093
1094 thread_local! {
1098 static RESIZER: RefCell<Resizer> = RefCell::new(Resizer::new());
1099 }
1100
1101 let options = ResizeOptions::new().resize_alg(ResizeAlg::Convolution(FilterType::Bilinear));
1104
1105 let plane = |resizer: &mut Resizer,
1106 src: &[u8],
1107 sw: u32,
1108 sh: u32,
1109 dst: &mut [u8],
1110 dw: u32,
1111 dh: u32|
1112 -> Result<(), Error> {
1113 let src = ImageRef::new(sw, sh, src, PixelType::U8)
1114 .map_err(|e| Error::codec(anyhow::anyhow!("resize source: {e}")))?;
1115 let mut dst = Image::from_slice_u8(dw, dh, dst, PixelType::U8)
1116 .map_err(|e| Error::codec(anyhow::anyhow!("resize destination: {e}")))?;
1117 resizer
1118 .resize(&src, &mut dst, &options)
1119 .map_err(|e| Error::codec(anyhow::anyhow!("resize: {e}")))
1120 };
1121
1122 let Size { width, height } = size;
1123 let luma = size.byte_len(1, "I420 resize")?;
1124 let mut data = vec![0u8; Self::len(size)?];
1125 let (y_dst, chroma) = data.split_at_mut(luma);
1126 let (u_dst, v_dst) = chroma.split_at_mut(luma / 4);
1127
1128 RESIZER.with_borrow_mut(|resizer| {
1129 plane(resizer, self.y(), self.width, self.height, y_dst, width, height)?;
1130 let (sw2, sh2) = (self.width / 2, self.height / 2);
1131 let (dw2, dh2) = (width / 2, height / 2);
1132 plane(resizer, self.u(), sw2, sh2, u_dst, dw2, dh2)?;
1133 plane(resizer, self.v(), sw2, sh2, v_dst, dw2, dh2)
1134 })?;
1135
1136 Ok(Self {
1138 width,
1139 height,
1140 data,
1141 color: self.color,
1142 })
1143 }
1144
1145 fn pack(planar: &YuvPlanarImageMut<u8>, size: Size, color: Option<Color>) -> Result<Self, Error> {
1151 let mut data = Vec::with_capacity(Self::len(size)?);
1152 data.extend_from_slice(planar.y_plane.borrow());
1153 data.extend_from_slice(planar.u_plane.borrow());
1154 data.extend_from_slice(planar.v_plane.borrow());
1155 let mut packed = Self::new(size, data)?;
1156 packed.color = color;
1157 Ok(packed)
1158 }
1159
1160 fn luma_len(&self) -> usize {
1161 self.width as usize * self.height as usize
1162 }
1163
1164 fn chroma_len(&self) -> usize {
1165 self.luma_len() / 4
1166 }
1167
1168 pub fn y(&self) -> &[u8] {
1170 &self.data[..self.luma_len()]
1171 }
1172
1173 pub fn u(&self) -> &[u8] {
1175 let start = self.luma_len();
1176 &self.data[start..start + self.chroma_len()]
1177 }
1178
1179 pub fn v(&self) -> &[u8] {
1181 let start = self.luma_len() + self.chroma_len();
1182 &self.data[start..start + self.chroma_len()]
1183 }
1184}
1185
1186#[cfg(any(target_os = "windows", all(target_os = "linux", feature = "nvidia")))]
1189pub(crate) fn interleave_uv(u: &[u8], v: &[u8], uv: &mut [u8]) {
1190 for (pair, (u, v)) in uv.as_chunks_mut::<2>().0.iter_mut().zip(u.iter().zip(v)) {
1191 pair[0] = *u;
1192 pair[1] = *v;
1193 }
1194}
1195
1196#[cfg(any(
1199 target_os = "windows",
1200 all(target_os = "linux", any(feature = "pipewire", feature = "vaapi"))
1201))]
1202pub(crate) fn deinterleave_uv(uv: &[u8], u: &mut [u8], v: &mut [u8]) {
1203 for (pair, (u, v)) in uv.as_chunks::<2>().0.iter().zip(u.iter_mut().zip(v)) {
1204 *u = pair[0];
1205 *v = pair[1];
1206 }
1207}
1208
1209#[cfg(any(apple, target_os = "windows"))]
1217struct Cache<K, T> {
1218 values: std::collections::HashMap<K, std::sync::Arc<std::sync::Mutex<T>>>,
1219 order: std::collections::VecDeque<K>,
1220 capacity: usize,
1221}
1222
1223#[cfg(any(apple, target_os = "windows"))]
1224impl<K: Clone + Eq + std::hash::Hash, T> Cache<K, T> {
1225 fn new(capacity: usize) -> Self {
1226 Self {
1227 values: std::collections::HashMap::new(),
1228 order: std::collections::VecDeque::new(),
1229 capacity,
1230 }
1231 }
1232
1233 fn get_or_insert_with<E>(
1234 &mut self,
1235 key: K,
1236 create: impl FnOnce() -> Result<T, E>,
1237 ) -> Result<std::sync::Arc<std::sync::Mutex<T>>, E> {
1238 if let Some(value) = self.values.get(&key).cloned() {
1239 self.touch(&key);
1240 return Ok(value);
1241 }
1242
1243 let value = std::sync::Arc::new(std::sync::Mutex::new(create()?));
1244 self.values.insert(key.clone(), std::sync::Arc::clone(&value));
1245 self.touch(&key);
1246 self.prune();
1247 Ok(value)
1248 }
1249
1250 fn touch(&mut self, key: &K) {
1251 self.order.retain(|entry| entry != key);
1252 self.order.push_back(key.clone());
1253 }
1254
1255 fn prune(&mut self) {
1256 let mut remaining = self.order.len();
1257 while self.values.len() > self.capacity && remaining > 0 {
1258 let key = self.order.pop_front().expect("remaining entries");
1259 let idle = self
1260 .values
1261 .get(&key)
1262 .is_some_and(|value| std::sync::Arc::strong_count(value) == 1);
1263 if idle {
1264 self.values.remove(&key);
1265 } else {
1266 self.order.push_back(key);
1267 }
1268 remaining -= 1;
1269 }
1270 }
1271}
1272
1273#[cfg(all(test, any(apple, target_os = "windows")))]
1274mod cache_tests {
1275 use super::Cache;
1276
1277 #[test]
1278 fn evicts_the_least_recently_used_idle_value() {
1279 let mut cache = Cache::new(2);
1280
1281 let first = cache.get_or_insert_with((1, 1), || Ok::<_, ()>(())).unwrap();
1282 drop(first);
1283 let second = cache.get_or_insert_with((2, 2), || Ok::<_, ()>(())).unwrap();
1284 drop(second);
1285
1286 let first = cache
1287 .get_or_insert_with((1, 1), || Err::<(), _>("cached value was recreated"))
1288 .unwrap();
1289 drop(first);
1290 let third = cache.get_or_insert_with((3, 3), || Ok::<_, ()>(())).unwrap();
1291 drop(third);
1292
1293 assert!(cache.values.contains_key(&(1, 1)));
1294 assert!(!cache.values.contains_key(&(2, 2)));
1295 assert!(cache.values.contains_key(&(3, 3)));
1296 assert_eq!(cache.values.len(), 2);
1297 }
1298
1299 #[test]
1300 fn defers_eviction_until_an_active_value_is_released() {
1301 let mut cache = Cache::new(1);
1302 let first = cache.get_or_insert_with((1, 1), || Ok::<_, ()>(())).unwrap();
1303 let second = cache.get_or_insert_with((2, 2), || Ok::<_, ()>(())).unwrap();
1304 assert_eq!(cache.values.len(), 2);
1305
1306 drop(first);
1307 cache.prune();
1308 assert!(!cache.values.contains_key(&(1, 1)));
1309 assert!(cache.values.contains_key(&(2, 2)));
1310 assert_eq!(cache.values.len(), 1);
1311 drop(second);
1312 }
1313
1314 #[test]
1315 fn caches_failure_markers() {
1316 let mut attempts = 0;
1317 let mut cache = Cache::new(1);
1318 let failed = cache
1319 .get_or_insert_with(1, || {
1320 attempts += 1;
1321 Ok::<_, ()>(Err::<(), _>("unsupported"))
1322 })
1323 .unwrap();
1324 drop(failed);
1325 let failed = cache
1326 .get_or_insert_with(1, || {
1327 attempts += 1;
1328 Ok::<_, ()>(Ok::<_, &str>(()))
1329 })
1330 .unwrap();
1331
1332 assert_eq!(attempts, 1);
1333 assert!(failed.lock().unwrap().is_err());
1334 }
1335}
1336
1337#[cfg(all(target_os = "android", feature = "mediacodec"))]
1338pub mod android {
1339 use std::sync::Arc;
1343
1344 use ndk::hardware_buffer::HardwareBufferRef;
1345 use ndk::media::image_reader::{Image, ImageReader};
1346
1347 use super::I420;
1348 use crate::{Color, Error, Size};
1349
1350 const Y: i32 = 0;
1355 const U: i32 = 1;
1356 const V: i32 = 2;
1357
1358 pub(crate) struct Reader(ImageReader);
1364
1365 impl Reader {
1371 pub(crate) fn new(reader: ImageReader) -> Self {
1372 Self(reader)
1373 }
1374 }
1375
1376 impl std::ops::Deref for Reader {
1377 type Target = ImageReader;
1378
1379 fn deref(&self) -> &ImageReader {
1380 &self.0
1381 }
1382 }
1383
1384 pub struct HardwareBuffer {
1396 _reader: Arc<Reader>,
1400 image: Image,
1401 pub(crate) left: u32,
1402 pub(crate) top: u32,
1403 pub(crate) width: u32,
1404 pub(crate) height: u32,
1405 pub(crate) color: Option<Color>,
1407 }
1408
1409 unsafe impl Send for HardwareBuffer {}
1417 unsafe impl Sync for HardwareBuffer {}
1418
1419 impl HardwareBuffer {
1420 pub(crate) fn new(reader: Arc<Reader>, image: Image, left: u32, top: u32, width: u32, height: u32) -> Self {
1421 Self {
1422 _reader: reader,
1423 image,
1424 left,
1425 top,
1426 width,
1427 height,
1428 color: None,
1429 }
1430 }
1431
1432 pub fn left(&self) -> u32 {
1434 self.left
1435 }
1436
1437 pub fn top(&self) -> u32 {
1439 self.top
1440 }
1441
1442 pub fn width(&self) -> u32 {
1444 self.width
1445 }
1446
1447 pub fn height(&self) -> u32 {
1449 self.height
1450 }
1451
1452 pub fn buffer(&self) -> Result<HardwareBufferRef, Error> {
1468 let buffer = self
1469 .image
1470 .hardware_buffer()
1471 .map_err(|e| Error::codec(anyhow::anyhow!("AImage_getHardwareBuffer failed: {e}")))?;
1472 Ok(buffer.acquire())
1475 }
1476
1477 pub(crate) fn download_i420(&self) -> Result<I420, Error> {
1484 let (w, h) = (self.width as usize, self.height as usize);
1485 let (cw, ch) = (w / 2, h / 2);
1486
1487 let mut data = vec![0u8; I420::len(Size::new(self.width, self.height))?];
1488 let (luma, chroma) = data.split_at_mut(w * h);
1489 let (u_dst, v_dst) = chroma.split_at_mut(cw * ch);
1490
1491 self.plane(Y)?
1492 .gather(luma, self.left as usize, self.top as usize, w, h)?;
1493 self.plane(U)?
1494 .gather(u_dst, self.left as usize / 2, self.top as usize / 2, cw, ch)?;
1495 self.plane(V)?
1496 .gather(v_dst, self.left as usize / 2, self.top as usize / 2, cw, ch)?;
1497
1498 Ok(I420 {
1499 width: self.width,
1500 height: self.height,
1501 data,
1502 color: self.color,
1503 })
1504 }
1505
1506 fn plane(&self, index: i32) -> Result<Plane<'_>, Error> {
1508 let fail = |what: &str, e: ndk::media_error::MediaError| {
1509 Error::codec(anyhow::anyhow!("AImage_getPlane{what} failed for plane {index}: {e}"))
1510 };
1511 Ok(Plane {
1512 data: self.image.plane_data(index).map_err(|e| fail("Data", e))?,
1513 row: self.image.plane_row_stride(index).map_err(|e| fail("RowStride", e))? as usize,
1514 pixel: self
1515 .image
1516 .plane_pixel_stride(index)
1517 .map_err(|e| fail("PixelStride", e))? as usize,
1518 })
1519 }
1520 }
1521
1522 struct Plane<'a> {
1525 data: &'a [u8],
1526 row: usize,
1527 pixel: usize,
1528 }
1529
1530 impl Plane<'_> {
1531 fn gather(&self, dst: &mut [u8], left: usize, top: usize, width: usize, height: usize) -> Result<(), Error> {
1538 let (Some(rows), Some(cols)) = (height.checked_sub(1), width.checked_sub(1)) else {
1539 return Ok(());
1540 };
1541 let needed = top
1542 .checked_add(rows)
1543 .and_then(|row| row.checked_mul(self.row))
1544 .and_then(|offset| {
1545 left.checked_add(cols)
1546 .and_then(|col| col.checked_mul(self.pixel))
1547 .and_then(|col| offset.checked_add(col))
1548 })
1549 .and_then(|offset| offset.checked_add(1))
1550 .ok_or_else(|| Error::codec(anyhow::anyhow!("image plane strides overflow the address space")))?;
1551 if self.data.len() < needed {
1552 return Err(Error::codec(anyhow::anyhow!(
1553 "image plane is {} bytes, needs {needed} for {width}x{height} at ({left}, {top}), row stride {}, and pixel stride {}",
1554 self.data.len(),
1555 self.row,
1556 self.pixel
1557 )));
1558 }
1559
1560 for (row, out) in dst.chunks_exact_mut(width).enumerate().take(height) {
1561 let offset = (top + row) * self.row + left * self.pixel;
1562 let src = &self.data[offset..];
1563 if self.pixel == 1 {
1564 out.copy_from_slice(&src[..width]);
1565 } else {
1566 for (col, sample) in out.iter_mut().enumerate() {
1567 *sample = src[col * self.pixel];
1568 }
1569 }
1570 }
1571 Ok(())
1572 }
1573 }
1574
1575 #[cfg(test)]
1576 mod tests {
1577 use super::*;
1578
1579 #[test]
1580 fn plane_gather_applies_the_crop_origin() {
1581 let data: Vec<u8> = (0..24).collect();
1582 let plane = Plane {
1583 data: &data,
1584 row: 6,
1585 pixel: 2,
1586 };
1587 let mut out = [0; 4];
1588 plane.gather(&mut out, 1, 1, 2, 2).unwrap();
1589 assert_eq!(out, [8, 10, 14, 16]);
1590 }
1591 }
1592}
1593
1594#[cfg(apple)]
1595pub mod apple {
1596 use std::ffi::c_void;
1601 use std::ptr;
1602 use std::ptr::NonNull;
1603 use std::sync::{LazyLock, Mutex};
1604
1605 use objc2_core_foundation::{CFDictionary, CFNumber, CFNumberType, CFRetained, CFString};
1606 use objc2_core_video::{
1607 CVPixelBuffer, CVPixelBufferCreate, CVPixelBufferGetBaseAddressOfPlane, CVPixelBufferGetBytesPerRowOfPlane,
1608 CVPixelBufferGetHeightOfPlane, CVPixelBufferGetPixelFormatType, CVPixelBufferGetPlaneCount,
1609 CVPixelBufferLockBaseAddress, CVPixelBufferLockFlags, CVPixelBufferPool, CVPixelBufferUnlockBaseAddress,
1610 kCVImageBufferYCbCrMatrix_ITU_R_601_4, kCVImageBufferYCbCrMatrix_ITU_R_709_2, kCVImageBufferYCbCrMatrixKey,
1611 kCVPixelBufferHeightKey, kCVPixelBufferIOSurfacePropertiesKey, kCVPixelBufferPixelFormatTypeKey,
1612 kCVPixelBufferWidthKey, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange,
1613 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, kCVPixelFormatType_420YpCbCr8Planar,
1614 };
1615 use objc2_video_toolbox::VTPixelTransferSession;
1616
1617 use super::{Cache, I420};
1618 use crate::{Color, Error, Size};
1619
1620 const LOCK_READ_ONLY: CVPixelBufferLockFlags = CVPixelBufferLockFlags(1);
1622
1623 const SCALER_CACHE_CAPACITY: usize = 16;
1626
1627 type ScalerCache = Mutex<Cache<(u32, u32), Scaler>>;
1631 static SCALERS: LazyLock<ScalerCache> = LazyLock::new(|| Mutex::new(Cache::new(SCALER_CACHE_CAPACITY)));
1632
1633 pub struct PixelBuffer {
1636 pub(crate) buffer: CFRetained<CVPixelBuffer>,
1637 pub(crate) width: u32,
1638 pub(crate) height: u32,
1639 pub(crate) color: Option<Color>,
1642 }
1643
1644 unsafe impl Send for PixelBuffer {}
1654 unsafe impl Sync for PixelBuffer {}
1655
1656 impl PixelBuffer {
1657 pub fn buffer(&self) -> &CVPixelBuffer {
1660 &self.buffer
1661 }
1662
1663 pub fn width(&self) -> u32 {
1665 self.width
1666 }
1667
1668 pub fn height(&self) -> u32 {
1670 self.height
1671 }
1672
1673 pub(crate) fn new(buffer: CFRetained<CVPixelBuffer>, width: u32, height: u32) -> Self {
1674 Self {
1675 buffer,
1676 width,
1677 height,
1678 color: None,
1679 }
1680 }
1681
1682 pub(crate) fn resize(&self, width: u32, height: u32) -> Result<Self, Error> {
1684 let scaler = {
1685 let mut scalers = SCALERS
1686 .lock()
1687 .map_err(|_| Error::codec(anyhow::anyhow!("pixel-transfer scaler cache lock poisoned")))?;
1688 scalers.get_or_insert_with((width, height), || Scaler::new(width, height))?
1689 };
1690
1691 let result = scaler
1692 .lock()
1693 .map_err(|_| Error::codec(anyhow::anyhow!("pixel-transfer scaler lock poisoned")))?
1694 .resize(self);
1695 drop(scaler);
1696 if let Ok(mut scalers) = SCALERS.lock() {
1697 scalers.prune();
1698 }
1699 result
1700 }
1701
1702 fn matrix(&self) -> Color {
1710 let inferred = Color::infer(Size::new(self.width, self.height));
1711 let Some(value) = (unsafe { self.buffer.attachment(kCVImageBufferYCbCrMatrixKey, ptr::null_mut()) }) else {
1713 return inferred;
1714 };
1715 let Some(name) = value.downcast_ref::<CFString>() else {
1716 return inferred;
1717 };
1718
1719 if name == unsafe { kCVImageBufferYCbCrMatrix_ITU_R_709_2 } {
1722 Color::BT709
1723 } else if name == unsafe { kCVImageBufferYCbCrMatrix_ITU_R_601_4 } {
1724 Color::BT601
1725 } else {
1726 inferred
1729 }
1730 }
1731
1732 pub(crate) fn color(&self) -> Option<Color> {
1737 let format = CVPixelBufferGetPixelFormatType(&self.buffer);
1738 let range = if format == kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange {
1739 crate::color::Range::Limited
1740 } else if format == kCVPixelFormatType_420YpCbCr8BiPlanarFullRange {
1741 crate::color::Range::Full
1742 } else {
1743 return None;
1744 };
1745 Some(self.color.unwrap_or_else(|| self.matrix()).with_range(range))
1746 }
1747
1748 pub(crate) fn download_i420(&self) -> Result<I420, Error> {
1755 let format = CVPixelBufferGetPixelFormatType(&self.buffer);
1756 if format != kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
1757 && format != kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
1758 {
1759 return Err(Error::codec(anyhow::anyhow!(
1760 "cannot download pixel format {format:#x}; expected NV12"
1761 )));
1762 }
1763
1764 let color = self.color();
1765
1766 let (w, h) = (self.width as usize, self.height as usize);
1767 let (cw, ch) = (w / 2, h / 2);
1768
1769 let locked = Locked::new(&self.buffer, LOCK_READ_ONLY)?;
1770
1771 let mut data = vec![0u8; I420::len(Size::new(self.width, self.height))?];
1772 let (luma, chroma) = data.split_at_mut(w * h);
1773 let (u_plane, v_plane) = chroma.split_at_mut(cw * ch);
1774
1775 let (y_base, y_stride) = locked.plane(0, w, h)?;
1777 for row in 0..h {
1778 unsafe {
1779 ptr::copy_nonoverlapping(y_base.add(row * y_stride), luma[row * w..].as_mut_ptr(), w);
1780 }
1781 }
1782
1783 let (uv_base, uv_stride) = locked.plane(1, cw * 2, ch)?;
1785 for row in 0..ch {
1786 let src = unsafe { uv_base.add(row * uv_stride) };
1787 for col in 0..cw {
1788 unsafe {
1789 u_plane[row * cw + col] = *src.add(col * 2);
1790 v_plane[row * cw + col] = *src.add(col * 2 + 1);
1791 }
1792 }
1793 }
1794
1795 Ok(I420 {
1796 width: self.width,
1797 height: self.height,
1798 data,
1799 color,
1800 })
1801 }
1802 }
1803
1804 struct Scaler {
1806 session: CFRetained<VTPixelTransferSession>,
1807 pool: CFRetained<CVPixelBufferPool>,
1808 width: u32,
1809 height: u32,
1810 }
1811
1812 unsafe impl Send for Scaler {}
1816
1817 impl Scaler {
1818 fn new(width: u32, height: u32) -> Result<Self, Error> {
1819 let mut session_ptr: *mut VTPixelTransferSession = std::ptr::null_mut();
1820 let status = unsafe {
1821 VTPixelTransferSession::create(None, NonNull::new(&mut session_ptr).expect("stack pointer is non-null"))
1822 };
1823 let session = NonNull::new(session_ptr)
1824 .filter(|_| status == 0)
1825 .map(|ptr| unsafe { CFRetained::from_raw(ptr) })
1826 .ok_or_else(|| Error::codec(anyhow::anyhow!("VTPixelTransferSessionCreate failed: {status}")))?;
1827
1828 let attributes = pool_attributes(width, height)?;
1829 let mut pool_ptr: *mut CVPixelBufferPool = std::ptr::null_mut();
1830 let status = unsafe {
1831 CVPixelBufferPool::create(
1832 None,
1833 None,
1834 Some(&attributes),
1835 NonNull::new(&mut pool_ptr).expect("stack pointer is non-null"),
1836 )
1837 };
1838 let pool = NonNull::new(pool_ptr)
1839 .filter(|_| status == 0)
1840 .map(|ptr| unsafe { CFRetained::from_raw(ptr) })
1841 .ok_or_else(|| Error::codec(anyhow::anyhow!("CVPixelBufferPoolCreate failed: {status}")))?;
1842
1843 Ok(Self {
1844 session,
1845 pool,
1846 width,
1847 height,
1848 })
1849 }
1850
1851 fn resize(&mut self, source: &PixelBuffer) -> Result<PixelBuffer, Error> {
1852 let mut output_ptr: *mut CVPixelBuffer = std::ptr::null_mut();
1853 let status = unsafe {
1854 CVPixelBufferPool::create_pixel_buffer(
1855 None,
1856 &self.pool,
1857 NonNull::new(&mut output_ptr).expect("stack pointer is non-null"),
1858 )
1859 };
1860 let output = NonNull::new(output_ptr)
1861 .filter(|_| status == 0)
1862 .map(|ptr| unsafe { CFRetained::from_raw(ptr) })
1863 .ok_or_else(|| Error::codec(anyhow::anyhow!("CVPixelBufferPoolCreatePixelBuffer failed: {status}")))?;
1864
1865 let status = unsafe { self.session.transfer_image(&source.buffer, &output) };
1866 if status != 0 {
1867 return Err(Error::codec(anyhow::anyhow!(
1868 "VTPixelTransferSessionTransferImage failed: {status}"
1869 )));
1870 }
1871
1872 Ok(PixelBuffer::new(output, self.width, self.height))
1873 }
1874 }
1875
1876 fn pool_attributes(width: u32, height: u32) -> Result<CFRetained<CFDictionary>, Error> {
1878 let width =
1879 i32::try_from(width).map_err(|_| Error::codec(anyhow::anyhow!("pixel-buffer width is too large")))?;
1880 let height =
1881 i32::try_from(height).map_err(|_| Error::codec(anyhow::anyhow!("pixel-buffer height is too large")))?;
1882 let format = kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange as i32;
1883
1884 let width = cf_number(width)?;
1885 let height = cf_number(height)?;
1886 let format = cf_number(format)?;
1887 let iosurface = unsafe {
1888 CFDictionary::new(
1889 None,
1890 std::ptr::null_mut(),
1891 std::ptr::null_mut(),
1892 0,
1893 &objc2_core_foundation::kCFTypeDictionaryKeyCallBacks,
1894 &objc2_core_foundation::kCFTypeDictionaryValueCallBacks,
1895 )
1896 }
1897 .ok_or_else(|| Error::codec(anyhow::anyhow!("failed to build IOSurface attributes dictionary")))?;
1898
1899 let mut keys = [
1900 (unsafe { kCVPixelBufferPixelFormatTypeKey } as *const CFString).cast::<c_void>(),
1901 (unsafe { kCVPixelBufferWidthKey } as *const CFString).cast::<c_void>(),
1902 (unsafe { kCVPixelBufferHeightKey } as *const CFString).cast::<c_void>(),
1903 (unsafe { kCVPixelBufferIOSurfacePropertiesKey } as *const CFString).cast::<c_void>(),
1904 ];
1905 let mut values = [
1906 (format.as_ref() as *const CFNumber).cast::<c_void>(),
1907 (width.as_ref() as *const CFNumber).cast::<c_void>(),
1908 (height.as_ref() as *const CFNumber).cast::<c_void>(),
1909 (iosurface.as_ref() as *const CFDictionary).cast::<c_void>(),
1910 ];
1911 unsafe {
1912 CFDictionary::new(
1913 None,
1914 keys.as_mut_ptr(),
1915 values.as_mut_ptr(),
1916 4,
1917 &objc2_core_foundation::kCFTypeDictionaryKeyCallBacks,
1918 &objc2_core_foundation::kCFTypeDictionaryValueCallBacks,
1919 )
1920 }
1921 .ok_or_else(|| {
1922 Error::codec(anyhow::anyhow!(
1923 "failed to build pixel-buffer pool attributes dictionary"
1924 ))
1925 })
1926 }
1927
1928 fn cf_number(value: i32) -> Result<CFRetained<CFNumber>, Error> {
1929 unsafe { CFNumber::new(None, CFNumberType::SInt32Type, (&value as *const i32).cast::<c_void>()) }
1930 .ok_or_else(|| Error::codec(anyhow::anyhow!("failed to build CFNumber")))
1931 }
1932
1933 struct Locked<'a> {
1936 buffer: &'a CVPixelBuffer,
1937 flags: CVPixelBufferLockFlags,
1938 }
1939
1940 impl<'a> Locked<'a> {
1941 fn new(buffer: &'a CVPixelBuffer, flags: CVPixelBufferLockFlags) -> Result<Self, Error> {
1942 let status = unsafe { CVPixelBufferLockBaseAddress(buffer, flags) };
1943 if status != 0 {
1944 return Err(Error::codec(anyhow::anyhow!(
1945 "CVPixelBufferLockBaseAddress failed: {status}"
1946 )));
1947 }
1948 Ok(Self { buffer, flags })
1949 }
1950
1951 fn plane(&self, index: usize, row_bytes: usize, rows: usize) -> Result<(*mut u8, usize), Error> {
1954 let planes = CVPixelBufferGetPlaneCount(self.buffer);
1955 if index >= planes {
1956 return Err(Error::codec(anyhow::anyhow!(
1957 "pixel buffer has {planes} planes, not plane {index}"
1958 )));
1959 }
1960 let base = CVPixelBufferGetBaseAddressOfPlane(self.buffer, index).cast::<u8>();
1961 let stride = CVPixelBufferGetBytesPerRowOfPlane(self.buffer, index);
1962 let height = CVPixelBufferGetHeightOfPlane(self.buffer, index);
1963 if base.is_null() {
1964 return Err(Error::codec(anyhow::anyhow!(
1965 "pixel buffer plane {index} has no base address"
1966 )));
1967 }
1968 if stride < row_bytes || height < rows {
1969 return Err(Error::codec(anyhow::anyhow!(
1970 "pixel buffer plane {index} is {stride} bytes by {height} rows, too small for {row_bytes} by {rows}"
1971 )));
1972 }
1973 Ok((base, stride))
1974 }
1975 }
1976
1977 impl Drop for Locked<'_> {
1978 fn drop(&mut self) {
1979 unsafe { CVPixelBufferUnlockBaseAddress(self.buffer, self.flags) };
1980 }
1981 }
1982
1983 #[cfg(test)]
1987 pub(crate) fn nv12_surface(frame: &I420) -> PixelBuffer {
1988 use std::ptr::{self, NonNull};
1989
1990 use objc2_core_foundation::CFRetained;
1991 use objc2_core_video::{
1992 CVPixelBuffer, CVPixelBufferCreate, CVPixelBufferGetBaseAddressOfPlane, CVPixelBufferGetBytesPerRowOfPlane,
1993 CVPixelBufferLockBaseAddress, CVPixelBufferLockFlags, CVPixelBufferUnlockBaseAddress,
1994 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
1995 };
1996
1997 let mut raw: *mut CVPixelBuffer = ptr::null_mut();
1998 let status = unsafe {
1999 CVPixelBufferCreate(
2000 None,
2001 frame.width as usize,
2002 frame.height as usize,
2003 kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange,
2004 None,
2005 NonNull::new(&mut raw).expect("stack pointer is non-null"),
2006 )
2007 };
2008 assert_eq!(status, 0, "CVPixelBufferCreate failed");
2009 let buffer = unsafe { CFRetained::from_raw(NonNull::new(raw).expect("CoreVideo returned a buffer")) };
2010
2011 let flags = CVPixelBufferLockFlags(0);
2012 assert_eq!(unsafe { CVPixelBufferLockBaseAddress(&buffer, flags) }, 0);
2013 let width = frame.width as usize;
2014 let height = frame.height as usize;
2015 let y_base = CVPixelBufferGetBaseAddressOfPlane(&buffer, 0) as *mut u8;
2016 let y_stride = CVPixelBufferGetBytesPerRowOfPlane(&buffer, 0);
2017 for row in 0..height {
2018 unsafe {
2019 ptr::copy_nonoverlapping(frame.y()[row * width..].as_ptr(), y_base.add(row * y_stride), width);
2020 }
2021 }
2022
2023 let (chroma_width, chroma_height) = (width / 2, height / 2);
2024 let uv_base = CVPixelBufferGetBaseAddressOfPlane(&buffer, 1) as *mut u8;
2025 let uv_stride = CVPixelBufferGetBytesPerRowOfPlane(&buffer, 1);
2026 for row in 0..chroma_height {
2027 let output = unsafe { uv_base.add(row * uv_stride) };
2028 for col in 0..chroma_width {
2029 unsafe {
2030 *output.add(col * 2) = frame.u()[row * chroma_width + col];
2031 *output.add(col * 2 + 1) = frame.v()[row * chroma_width + col];
2032 }
2033 }
2034 }
2035 unsafe { CVPixelBufferUnlockBaseAddress(&buffer, flags) };
2036
2037 PixelBuffer::new(buffer, frame.width, frame.height)
2038 }
2039
2040 pub(crate) fn upload_i420(frame: &I420) -> Result<CFRetained<CVPixelBuffer>, Error> {
2046 let (w, h) = (frame.width as usize, frame.height as usize);
2047 let (cw, ch) = (w / 2, h / 2);
2048
2049 let mut ptr: *mut CVPixelBuffer = std::ptr::null_mut();
2050 let status = unsafe {
2051 CVPixelBufferCreate(
2052 None,
2053 w,
2054 h,
2055 kCVPixelFormatType_420YpCbCr8Planar,
2056 None,
2057 NonNull::new(&mut ptr).unwrap(),
2058 )
2059 };
2060 let buffer = NonNull::new(ptr)
2061 .filter(|_| status == 0)
2062 .map(|p| unsafe { CFRetained::from_raw(p) })
2063 .ok_or_else(|| Error::codec(anyhow::anyhow!("CVPixelBufferCreate failed: {status}")))?;
2064
2065 {
2066 let locked = Locked::new(&buffer, CVPixelBufferLockFlags(0))?;
2067 copy_plane(&locked, 0, frame.y(), w, h)?;
2068 copy_plane(&locked, 1, frame.u(), cw, ch)?;
2069 copy_plane(&locked, 2, frame.v(), cw, ch)?;
2070 }
2071 Ok(buffer)
2072 }
2073
2074 fn copy_plane(locked: &Locked, plane: usize, src: &[u8], row_bytes: usize, rows: usize) -> Result<(), Error> {
2077 let (base, stride) = locked.plane(plane, row_bytes, rows)?;
2078 for y in 0..rows {
2079 let row = &src[y * row_bytes..(y + 1) * row_bytes];
2080 unsafe { std::ptr::copy_nonoverlapping(row.as_ptr(), base.add(y * stride), row_bytes) };
2082 }
2083 Ok(())
2084 }
2085}
2086
2087#[cfg(target_os = "linux")]
2088#[path = "frame/vulkan.rs"]
2089pub mod vulkan;
2090
2091#[cfg(all(target_os = "linux", feature = "nvidia"))]
2092#[path = "frame/cuda_vulkan.rs"]
2093mod cuda_vulkan;
2094
2095#[cfg(all(target_os = "linux", feature = "nvidia"))]
2096#[path = "frame/cuda.rs"]
2097pub mod cuda;
2098
2099#[cfg(all(target_os = "linux", feature = "vaapi"))]
2100#[path = "frame/vaapi.rs"]
2101pub(crate) mod vaapi;
2102
2103#[cfg(any(test, all(target_os = "linux", feature = "nvidia")))]
2105#[path = "frame/pool.rs"]
2106mod pool;
2107
2108#[cfg(target_os = "windows")]
2109pub mod d3d11 {
2110 use std::ffi::c_void;
2114 use std::ptr;
2115 use std::sync::{LazyLock, Mutex};
2116
2117 use windows::Win32::Foundation::{HMODULE, RECT};
2118 use windows::Win32::Graphics::Direct3D::{D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_UNKNOWN};
2119 use windows::Win32::Graphics::Direct3D10::ID3D10Multithread;
2120 use windows::Win32::Graphics::Direct3D11::{
2121 D3D11_BIND_RENDER_TARGET, D3D11_BIND_SHADER_RESOURCE, D3D11_BIND_VIDEO_ENCODER, D3D11_BOX,
2122 D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
2123 D3D11_FORMAT_SUPPORT, D3D11_FORMAT_SUPPORT_RENDER_TARGET, D3D11_FORMAT_SUPPORT_SHADER_SAMPLE,
2124 D3D11_FORMAT_SUPPORT_VIDEO_ENCODER, D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION,
2125 D3D11_TEX2D_VPIV, D3D11_TEX2D_VPOV, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT, D3D11_USAGE_STAGING,
2126 D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE, D3D11_VIDEO_PROCESSOR_COLOR_SPACE, D3D11_VIDEO_PROCESSOR_CONTENT_DESC,
2127 D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT_INPUT, D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT_OUTPUT,
2128 D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC, D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC_0,
2129 D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC, D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0, D3D11_VIDEO_PROCESSOR_STREAM,
2130 D3D11_VIDEO_USAGE_PLAYBACK_NORMAL, D3D11_VPIV_DIMENSION_TEXTURE2D, D3D11_VPOV_DIMENSION_TEXTURE2D,
2131 D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext, ID3D11Texture2D, ID3D11VideoContext, ID3D11VideoDevice,
2132 ID3D11VideoProcessor, ID3D11VideoProcessorEnumerator, ID3D11VideoProcessorInputView,
2133 ID3D11VideoProcessorOutputView,
2134 };
2135 use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT, DXGI_RATIONAL, DXGI_SAMPLE_DESC};
2136 use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_FORMAT_NV12};
2137 use windows::Win32::Graphics::Dxgi::IDXGIAdapter;
2138 use windows::Win32::Media::MediaFoundation::{IMFDXGIBuffer, IMFSample};
2139 use windows::core::Interface;
2140
2141 use super::processor::Plan;
2142 use super::{Cache, I420};
2143 use crate::{Color, Error, Size};
2144
2145 fn err(ctx: &str, e: windows::core::Error) -> Error {
2146 Error::codec(anyhow::anyhow!("{ctx}: {e}"))
2147 }
2148
2149 pub(crate) fn create_device(adapter: Option<&IDXGIAdapter>) -> Result<ID3D11Device, Error> {
2155 let driver = match adapter {
2157 Some(_) => D3D_DRIVER_TYPE_UNKNOWN,
2158 None => D3D_DRIVER_TYPE_HARDWARE,
2159 };
2160 let mut device: Option<ID3D11Device> = None;
2161 unsafe {
2162 D3D11CreateDevice(
2163 adapter,
2164 driver,
2165 HMODULE::default(),
2166 D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
2167 None,
2168 D3D11_SDK_VERSION,
2169 Some(&mut device),
2170 None,
2171 None,
2172 )
2173 .map_err(|e| err("D3D11CreateDevice", e))?;
2174 }
2175 let device = device.ok_or_else(|| Error::codec(anyhow::anyhow!("D3D11CreateDevice returned null")))?;
2176
2177 let multithread = device
2178 .cast::<ID3D10Multithread>()
2179 .map_err(|e| err("query ID3D10Multithread", e))?;
2180 unsafe {
2181 let _ = multithread.SetMultithreadProtected(true);
2182 }
2183 Ok(device)
2184 }
2185
2186 pub struct Texture {
2192 pub(crate) device: ID3D11Device,
2193 pub(crate) texture: ID3D11Texture2D,
2194 pub(crate) width: u32,
2195 pub(crate) height: u32,
2196 pub(crate) color: Option<Color>,
2197 }
2198
2199 impl Texture {
2200 pub(crate) fn copy_from_sample(
2223 device: &ID3D11Device,
2224 sample: &IMFSample,
2225 width: u32,
2226 height: u32,
2227 ) -> Result<Self, Error> {
2228 let (source, subresource) = resolve(sample)?;
2229
2230 let mut desc = D3D11_TEXTURE2D_DESC::default();
2232 unsafe { source.GetDesc(&mut desc) };
2233 let texture = alloc(device, width, height, desc.Format)?;
2234
2235 let region = D3D11_BOX {
2238 left: 0,
2239 top: 0,
2240 front: 0,
2241 right: width,
2242 bottom: height,
2243 back: 1,
2244 };
2245 let context = unsafe { device.GetImmediateContext() }.map_err(|e| err("GetImmediateContext", e))?;
2246 unsafe {
2247 context.CopySubresourceRegion(&texture, 0, 0, 0, 0, &source, subresource, Some(®ion));
2248 }
2249
2250 Ok(Self {
2251 device: device.clone(),
2252 texture,
2253 width,
2254 height,
2255 color: None,
2256 })
2257 }
2258
2259 #[cfg(any(feature = "capture", feature = "render"))]
2262 pub(crate) fn capture(device: &ID3D11Device, source: &ID3D11Texture2D, size: Size) -> Result<Self, Error> {
2263 let plan = Plan::capture(size)?;
2264 let mut desc = D3D11_TEXTURE2D_DESC::default();
2265 unsafe { source.GetDesc(&mut desc) };
2266 if desc.Format != DXGI_FORMAT_B8G8R8A8_UNORM || desc.Width < size.width || desc.Height < size.height {
2267 return Err(Error::codec(anyhow::anyhow!(
2268 "invalid WGC BGRA surface geometry or format"
2269 )));
2270 }
2271 Ok(Self {
2272 device: device.clone(),
2273 texture: process(device, source, plan)?,
2274 width: plan.target.width,
2275 height: plan.target.height,
2276 color: Some(Color::infer(plan.target)),
2277 })
2278 }
2279
2280 pub fn texture(&self) -> &ID3D11Texture2D {
2289 &self.texture
2290 }
2291
2292 pub fn device(&self) -> &ID3D11Device {
2295 &self.device
2296 }
2297
2298 pub fn width(&self) -> u32 {
2300 self.width
2301 }
2302
2303 pub fn height(&self) -> u32 {
2305 self.height
2306 }
2307
2308 pub(crate) fn download_i420(&self) -> Result<I420, Error> {
2312 let context = unsafe { self.device.GetImmediateContext() }.map_err(|e| err("GetImmediateContext", e))?;
2313
2314 let mut desc = D3D11_TEXTURE2D_DESC::default();
2316 unsafe { self.texture.GetDesc(&mut desc) };
2317 desc.ArraySize = 1;
2318 desc.MipLevels = 1;
2319 desc.Usage = D3D11_USAGE_STAGING;
2320 desc.BindFlags = 0;
2321 desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0 as u32;
2322 desc.MiscFlags = 0;
2323
2324 let mut staging: Option<ID3D11Texture2D> = None;
2325 unsafe {
2326 self.device
2327 .CreateTexture2D(&desc, None, Some(&mut staging))
2328 .map_err(|e| err("CreateTexture2D (staging)", e))?;
2329 }
2330 let staging = staging.ok_or_else(|| Error::codec(anyhow::anyhow!("CreateTexture2D returned null")))?;
2331
2332 unsafe {
2333 context.CopySubresourceRegion(&staging, 0, 0, 0, 0, &self.texture, 0, None);
2334 }
2335
2336 let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();
2337 unsafe {
2338 context
2339 .Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))
2340 .map_err(|e| err("Map (staging)", e))?;
2341 }
2342 let _guard = UnmapGuard {
2343 context: &context,
2344 resource: &staging,
2345 };
2346
2347 let (w, h) = (self.width as usize, self.height as usize);
2348 let (cw, ch) = (w / 2, h / 2);
2349 let pitch = mapped.RowPitch as usize;
2350 let base = mapped.pData as *const u8;
2351 let tex_height = desc.Height as usize;
2357
2358 let mut data = vec![0u8; I420::len(Size::new(self.width, self.height))?];
2359 let (luma, chroma) = data.split_at_mut(w * h);
2360 let (u_plane, v_plane) = chroma.split_at_mut(cw * ch);
2361
2362 for row in 0..h {
2364 unsafe {
2365 ptr::copy_nonoverlapping(base.add(row * pitch), luma[row * w..].as_mut_ptr(), w);
2366 }
2367 }
2368 let uv_base = unsafe { base.add(pitch * tex_height) };
2370 for row in 0..ch {
2371 let src = unsafe { uv_base.add(row * pitch) };
2372 for col in 0..cw {
2373 unsafe {
2374 u_plane[row * cw + col] = *src.add(col * 2);
2375 v_plane[row * cw + col] = *src.add(col * 2 + 1);
2376 }
2377 }
2378 }
2379
2380 Ok(I420 {
2381 width: self.width,
2382 height: self.height,
2383 data,
2384 color: self.color,
2385 })
2386 }
2387
2388 pub(crate) fn resize(&self, width: u32, height: u32) -> Result<Self, Error> {
2398 let source = Size::new(self.width, self.height);
2399 let target = Size::new(width, height);
2400 let texture = process(&self.device, &self.texture, Plan::resize(source, target, self.color)?)?;
2401 Ok(Self {
2402 device: self.device.clone(),
2403 texture,
2404 width,
2405 height,
2406 color: self.color,
2407 })
2408 }
2409 }
2410
2411 fn process(device: &ID3D11Device, source: &ID3D11Texture2D, plan: Plan) -> Result<ID3D11Texture2D, Error> {
2412 let key = ScalerKey {
2413 device: device.as_raw() as usize,
2414 plan,
2415 };
2416 let scaler = {
2417 let mut scalers = SCALERS
2418 .lock()
2419 .map_err(|_| Error::codec(anyhow::anyhow!("video-processor cache lock poisoned")))?;
2420 scalers
2421 .get_or_insert_with(key, || {
2422 Ok::<_, std::convert::Infallible>(ScalerState::discover(device, plan))
2423 })
2424 .expect("processor discovery is infallible")
2425 };
2426 let mut state = scaler
2427 .lock()
2428 .map_err(|_| Error::codec(anyhow::anyhow!("video processor lock poisoned")))?;
2429 let result = match &*state {
2430 ScalerState::Ready(scaler) => scaler.scale(source),
2431 ScalerState::Unsupported { reason, .. } => {
2432 return Err(Error::codec(anyhow::anyhow!("GPU processing is unsupported: {reason}")));
2433 }
2434 };
2435 let texture = match result {
2436 Ok(texture) => texture,
2437 Err(ScaleError::Unsupported(err)) => {
2438 *state = ScalerState::Unsupported {
2439 _device: device.clone(),
2440 reason: err.to_string(),
2441 };
2442 return Err(err);
2443 }
2444 Err(ScaleError::Transient(err)) => return Err(err),
2445 };
2446 drop(state);
2447 drop(scaler);
2448 if let Ok(mut scalers) = SCALERS.lock() {
2449 scalers.prune();
2450 }
2451 Ok(texture)
2452 }
2453
2454 const SCALER_CACHE_CAPACITY: usize = 16;
2457
2458 static SCALERS: LazyLock<Mutex<Cache<ScalerKey, ScalerState>>> =
2463 LazyLock::new(|| Mutex::new(Cache::new(SCALER_CACHE_CAPACITY)));
2464
2465 enum ScalerState {
2467 Ready(Scaler),
2468 Unsupported {
2469 _device: ID3D11Device,
2471 reason: String,
2472 },
2473 }
2474
2475 impl ScalerState {
2476 fn discover(device: &ID3D11Device, plan: Plan) -> Self {
2477 match Scaler::new(device, plan) {
2478 Ok(scaler) => Self::Ready(scaler),
2479 Err(err) => Self::Unsupported {
2480 _device: device.clone(),
2481 reason: err.to_string(),
2482 },
2483 }
2484 }
2485 }
2486
2487 #[derive(Clone, PartialEq, Eq, Hash)]
2494 struct ScalerKey {
2495 device: usize,
2496 plan: Plan,
2497 }
2498
2499 struct Scaler {
2502 device: ID3D11Device,
2504 video: ID3D11VideoDevice,
2505 context: ID3D11VideoContext,
2506 enumerator: ID3D11VideoProcessorEnumerator,
2507 processor: ID3D11VideoProcessor,
2508 target: Size,
2509 input_format: DXGI_FORMAT,
2510 }
2511
2512 enum ScaleError {
2514 Unsupported(Error),
2515 Transient(Error),
2516 }
2517
2518 impl Scaler {
2519 fn new(device: &ID3D11Device, plan: Plan) -> Result<Self, Error> {
2520 let (source, target) = (plan.source, plan.target);
2521 let video = device
2522 .cast::<ID3D11VideoDevice>()
2523 .map_err(|e| err("query ID3D11VideoDevice", e))?;
2524 let immediate = unsafe { device.GetImmediateContext() }.map_err(|e| err("GetImmediateContext", e))?;
2525 let context = immediate
2526 .cast::<ID3D11VideoContext>()
2527 .map_err(|e| err("query ID3D11VideoContext", e))?;
2528
2529 let rate = DXGI_RATIONAL {
2532 Numerator: 30,
2533 Denominator: 1,
2534 };
2535 let desc = D3D11_VIDEO_PROCESSOR_CONTENT_DESC {
2536 InputFrameFormat: D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE,
2537 InputFrameRate: rate,
2538 InputWidth: source.width,
2539 InputHeight: source.height,
2540 OutputFrameRate: rate,
2541 OutputWidth: target.width,
2542 OutputHeight: target.height,
2543 Usage: D3D11_VIDEO_USAGE_PLAYBACK_NORMAL,
2544 };
2545
2546 let enumerator = unsafe { video.CreateVideoProcessorEnumerator(&desc) }
2547 .map_err(|e| err("CreateVideoProcessorEnumerator", e))?;
2548 let input_format = if plan.bgra {
2549 DXGI_FORMAT_B8G8R8A8_UNORM
2550 } else {
2551 DXGI_FORMAT_NV12
2552 };
2553 for (format, required) in [
2554 (input_format, D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT_INPUT),
2555 (DXGI_FORMAT_NV12, D3D11_VIDEO_PROCESSOR_FORMAT_SUPPORT_OUTPUT),
2556 ] {
2557 let support = unsafe { enumerator.CheckVideoProcessorFormat(format) }
2558 .map_err(|e| err("CheckVideoProcessorFormat", e))?;
2559 if support & required.0 as u32 == 0 {
2560 return Err(Error::codec(anyhow::anyhow!(
2561 "video processor does not support {format:?} as {required:?}"
2562 )));
2563 }
2564 }
2565 let processor =
2566 unsafe { video.CreateVideoProcessor(&enumerator, 0) }.map_err(|e| err("CreateVideoProcessor", e))?;
2567
2568 let full = RECT {
2569 left: 0,
2570 top: 0,
2571 right: plan.picture.width as i32,
2572 bottom: plan.picture.height as i32,
2573 };
2574 let scaled = RECT {
2575 left: 0,
2576 top: 0,
2577 right: target.width as i32,
2578 bottom: target.height as i32,
2579 };
2580 unsafe {
2581 context.VideoProcessorSetStreamFrameFormat(&processor, 0, D3D11_VIDEO_FRAME_FORMAT_PROGRESSIVE);
2582 context.VideoProcessorSetStreamSourceRect(&processor, 0, true, Some(&full));
2584 context.VideoProcessorSetStreamDestRect(&processor, 0, true, Some(&scaled));
2585 context.VideoProcessorSetStreamAutoProcessingMode(&processor, 0, false);
2589 let input = D3D11_VIDEO_PROCESSOR_COLOR_SPACE {
2590 _bitfield: plan.input_space(),
2591 };
2592 let output = D3D11_VIDEO_PROCESSOR_COLOR_SPACE { _bitfield: plan.space };
2593 context.VideoProcessorSetStreamColorSpace(&processor, 0, &input);
2594 context.VideoProcessorSetOutputColorSpace(&processor, &output);
2595 context.VideoProcessorSetOutputTargetRect(&processor, true, Some(&scaled));
2596 }
2597
2598 Ok(Self {
2599 device: device.clone(),
2600 video,
2601 context,
2602 enumerator,
2603 processor,
2604 target,
2605 input_format,
2606 })
2607 }
2608
2609 fn scale(&self, source: &ID3D11Texture2D) -> Result<ID3D11Texture2D, ScaleError> {
2611 let mut desc = D3D11_TEXTURE2D_DESC::default();
2612 unsafe { source.GetDesc(&mut desc) };
2613 if desc.Format != self.input_format {
2614 return Err(ScaleError::Transient(Error::codec(anyhow::anyhow!(
2615 "video processor input format changed"
2616 ))));
2617 }
2618 let output = alloc(&self.device, self.target.width, self.target.height, DXGI_FORMAT_NV12)
2619 .map_err(ScaleError::Transient)?;
2620
2621 let input_desc = D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC {
2622 FourCC: 0,
2623 ViewDimension: D3D11_VPIV_DIMENSION_TEXTURE2D,
2624 Anonymous: D3D11_VIDEO_PROCESSOR_INPUT_VIEW_DESC_0 {
2625 Texture2D: D3D11_TEX2D_VPIV {
2626 MipSlice: 0,
2627 ArraySlice: 0,
2628 },
2629 },
2630 };
2631 let mut input: Option<ID3D11VideoProcessorInputView> = None;
2632 unsafe {
2633 self.video
2634 .CreateVideoProcessorInputView(source, &self.enumerator, &input_desc, Some(&mut input))
2635 .map_err(|e| ScaleError::Unsupported(err("CreateVideoProcessorInputView", e)))?;
2636 }
2637 let input =
2638 input.ok_or_else(|| ScaleError::Unsupported(Error::codec(anyhow::anyhow!("input view is null"))))?;
2639
2640 let output_desc = D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC {
2641 ViewDimension: D3D11_VPOV_DIMENSION_TEXTURE2D,
2642 Anonymous: D3D11_VIDEO_PROCESSOR_OUTPUT_VIEW_DESC_0 {
2643 Texture2D: D3D11_TEX2D_VPOV { MipSlice: 0 },
2644 },
2645 };
2646 let mut view: Option<ID3D11VideoProcessorOutputView> = None;
2647 unsafe {
2648 self.video
2649 .CreateVideoProcessorOutputView(&output, &self.enumerator, &output_desc, Some(&mut view))
2650 .map_err(|e| ScaleError::Unsupported(err("CreateVideoProcessorOutputView", e)))?;
2651 }
2652 let view =
2653 view.ok_or_else(|| ScaleError::Unsupported(Error::codec(anyhow::anyhow!("output view is null"))))?;
2654
2655 let streams = [D3D11_VIDEO_PROCESSOR_STREAM {
2656 Enable: true.into(),
2657 OutputIndex: 0,
2658 InputFrameOrField: 0,
2659 PastFrames: 0,
2660 FutureFrames: 0,
2661 ppPastSurfaces: ptr::null_mut(),
2662 pInputSurface: std::mem::ManuallyDrop::new(Some(input)),
2663 ppFutureSurfaces: ptr::null_mut(),
2664 ppPastSurfacesRight: ptr::null_mut(),
2665 pInputSurfaceRight: std::mem::ManuallyDrop::new(None),
2666 ppFutureSurfacesRight: ptr::null_mut(),
2667 }];
2668 let result = unsafe { self.context.VideoProcessorBlt(&self.processor, &view, 0, &streams) };
2669 drop(std::mem::ManuallyDrop::into_inner(unsafe {
2673 ptr::read(&streams[0].pInputSurface)
2674 }));
2675 result.map_err(|e| ScaleError::Transient(err("VideoProcessorBlt", e)))?;
2676
2677 Ok(output)
2678 }
2679 }
2680
2681 fn alloc(device: &ID3D11Device, width: u32, height: u32, format: DXGI_FORMAT) -> Result<ID3D11Texture2D, Error> {
2684 let desc = D3D11_TEXTURE2D_DESC {
2685 Width: width,
2686 Height: height,
2687 MipLevels: 1,
2688 ArraySize: 1,
2689 Format: format,
2690 SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0 },
2691 Usage: D3D11_USAGE_DEFAULT,
2692 BindFlags: bind_flags(device, format),
2693 CPUAccessFlags: 0,
2694 MiscFlags: 0,
2695 };
2696
2697 let mut texture: Option<ID3D11Texture2D> = None;
2698 unsafe {
2699 device
2700 .CreateTexture2D(&desc, None, Some(&mut texture))
2701 .map_err(|e| err("CreateTexture2D", e))?;
2702 }
2703 texture.ok_or_else(|| Error::codec(anyhow::anyhow!("CreateTexture2D returned null")))
2704 }
2705
2706 #[cfg(test)]
2710 pub(crate) fn upload_i420(device: &ID3D11Device, frame: &I420) -> Result<Texture, Error> {
2711 let (width, height) = (frame.width, frame.height);
2712 let texture = alloc(device, width, height, DXGI_FORMAT_NV12)?;
2713
2714 let (w, h) = (width as usize, height as usize);
2715 let mut nv12 = vec![0u8; w * h * 3 / 2];
2716 let (luma, chroma) = nv12.split_at_mut(w * h);
2717 luma.copy_from_slice(frame.y());
2718 super::interleave_uv(frame.u(), frame.v(), chroma);
2719
2720 let context = unsafe { device.GetImmediateContext() }.map_err(|e| err("GetImmediateContext", e))?;
2721 unsafe {
2724 context.UpdateSubresource(
2725 &texture,
2726 0,
2727 None,
2728 nv12.as_ptr().cast::<c_void>(),
2729 width,
2730 nv12.len() as u32,
2731 );
2732 }
2733
2734 Ok(Texture {
2735 device: device.clone(),
2736 texture,
2737 width,
2738 height,
2739 color: frame.color,
2740 })
2741 }
2742
2743 #[cfg(all(test, feature = "capture"))]
2745 pub(crate) fn upload_bgra(device: &ID3D11Device, size: Size, pixels: &[u8]) -> ID3D11Texture2D {
2746 assert_eq!(pixels.len(), size.pixels() as usize * 4);
2747 let texture = alloc(device, size.width, size.height, DXGI_FORMAT_B8G8R8A8_UNORM).unwrap();
2748 let context = unsafe { device.GetImmediateContext() }.unwrap();
2749 unsafe {
2750 context.UpdateSubresource(
2751 &texture,
2752 0,
2753 None,
2754 pixels.as_ptr().cast(),
2755 size.width * 4,
2756 pixels.len() as u32,
2757 );
2758 }
2759 texture
2760 }
2761
2762 fn resolve(sample: &IMFSample) -> Result<(ID3D11Texture2D, u32), Error> {
2765 let buffer = unsafe { sample.GetBufferByIndex(0) }.map_err(|e| err("get sample buffer", e))?;
2766 let dxgi = buffer
2767 .cast::<IMFDXGIBuffer>()
2768 .map_err(|e| err("sample buffer is not a DXGI surface", e))?;
2769
2770 let mut raw: *mut c_void = ptr::null_mut();
2772 unsafe {
2773 dxgi.GetResource(&ID3D11Texture2D::IID, &mut raw)
2774 .map_err(|e| err("get DXGI resource", e))?;
2775 }
2776 let texture = unsafe { ID3D11Texture2D::from_raw(raw) };
2777 let subresource = unsafe { dxgi.GetSubresourceIndex() }.map_err(|e| err("get subresource index", e))?;
2778 Ok((texture, subresource))
2779 }
2780
2781 fn bind_flags(device: &ID3D11Device, format: DXGI_FORMAT) -> u32 {
2791 let support = unsafe { device.CheckFormatSupport(format) }.unwrap_or_default();
2792 let supports = |flag: D3D11_FORMAT_SUPPORT| support & flag.0 as u32 != 0;
2793
2794 let mut flags = 0;
2795 if supports(D3D11_FORMAT_SUPPORT_SHADER_SAMPLE) {
2796 flags |= D3D11_BIND_SHADER_RESOURCE.0 as u32;
2797 }
2798 if supports(D3D11_FORMAT_SUPPORT_RENDER_TARGET) {
2799 flags |= D3D11_BIND_RENDER_TARGET.0 as u32;
2800 }
2801 if supports(D3D11_FORMAT_SUPPORT_VIDEO_ENCODER) {
2802 flags |= D3D11_BIND_VIDEO_ENCODER.0 as u32;
2803 }
2804 flags
2805 }
2806
2807 #[cfg(test)]
2809 pub(crate) fn supports_nv12_render_target(device: &ID3D11Device) -> bool {
2810 let support = unsafe { device.CheckFormatSupport(DXGI_FORMAT_NV12) }.unwrap_or_default();
2811 support & D3D11_FORMAT_SUPPORT_RENDER_TARGET.0 as u32 != 0
2812 }
2813
2814 struct UnmapGuard<'a> {
2815 context: &'a ID3D11DeviceContext,
2816 resource: &'a ID3D11Texture2D,
2817 }
2818
2819 impl Drop for UnmapGuard<'_> {
2820 fn drop(&mut self) {
2821 unsafe { self.context.Unmap(self.resource, 0) };
2822 }
2823 }
2824
2825 #[cfg(all(test, feature = "capture"))]
2826 mod tests {
2827 use super::*;
2828
2829 #[test]
2830 #[ignore = "requires a Windows GPU with BGRA-to-NV12 video processing"]
2831 fn wgc_conversion_crops_odd_edges_and_preserves_color() {
2832 let device = create_device(None).expect("D3D11 hardware device");
2833 for size in [Size::new(641, 481), Size::new(1281, 721)] {
2834 let mut pixels = Vec::with_capacity(size.pixels() as usize * 4);
2835 for y in 0..size.height {
2836 for x in 0..size.width {
2837 pixels.extend_from_slice(if x + 1 == size.width || y + 1 == size.height {
2839 &[0, 255, 0, 255]
2840 } else {
2841 &[0, 0, 255, 255]
2842 });
2843 }
2844 }
2845 let source = upload_bgra(&device, size, &pixels);
2846 let output = Texture::capture(&device, &source, size).expect("BGRA to NV12");
2847 let expected_size = Size::new(size.width & !1, size.height & !1);
2848 let color = Color::infer(expected_size);
2849 assert_eq!(Size::new(output.width, output.height), expected_size);
2850 assert_eq!(output.color, Some(color));
2851 assert_eq!(output.device.as_raw(), device.as_raw());
2852 assert_ne!(output.texture.as_raw(), source.as_raw(), "must own the output");
2853
2854 pixels.fill(0);
2856 unsafe {
2857 device.GetImmediateContext().unwrap().UpdateSubresource(
2858 &source,
2859 0,
2860 None,
2861 pixels.as_ptr().cast(),
2862 size.width * 4,
2863 pixels.len() as u32,
2864 );
2865 }
2866 drop(source);
2867 assert_red(&output.download_i420().unwrap(), color);
2868 let scaled = output.resize(320, 240).expect("NV12 GPU resize");
2870 assert_eq!(scaled.color, Some(color));
2871 assert_red(&scaled.download_i420().unwrap(), color);
2872 }
2873 }
2874
2875 fn assert_red(frame: &I420, color: Color) {
2876 assert_eq!(frame.color(), Some(color));
2877 let expected = color.coefficients().apply([255, 0, 0]);
2878 for (plane, value) in [frame.y(), frame.u(), frame.v()].into_iter().zip(expected) {
2879 assert!(
2880 plane.iter().all(|sample| sample.abs_diff(value) <= 3),
2881 "{color:?}: expected {value}"
2882 );
2883 }
2884 }
2885
2886 #[test]
2887 #[ignore = "Windows GPU workload; reports submission and batch completion, not capture latency"]
2888 #[expect(
2889 clippy::disallowed_methods,
2890 clippy::disallowed_types,
2891 reason = "the workload measures itself on the host clock"
2892 )]
2893 fn wgc_conversion_workload() {
2894 let device = create_device(None).expect("D3D11 hardware device");
2895 for size in [Size::new(640, 480), Size::new(1280, 720), Size::new(1920, 1080)] {
2896 let pixels = [0, 0, 255, 255].repeat(size.pixels() as usize);
2897 let source = upload_bgra(&device, size, &pixels);
2898 Texture::capture(&device, &source, size)
2899 .unwrap()
2900 .download_i420()
2901 .unwrap();
2902 let start = std::time::Instant::now();
2903 let mut output = None;
2904 for _ in 0..32 {
2905 output = Some(Texture::capture(&device, &source, size).unwrap());
2906 }
2907 let submitted = start.elapsed();
2908 output.unwrap().download_i420().unwrap();
2910 eprintln!(
2911 "WGC {size}: 32 frames, submit={submitted:?}, complete_with_one_readback={:?}",
2912 start.elapsed()
2913 );
2914 }
2915 }
2916 }
2917}
2918
2919#[cfg(test)]
2920mod tests {
2921 #[test]
2930 fn only_a_real_color_conversion_labels_its_output() {
2931 use super::I420;
2932 use crate::{Color, Size};
2933
2934 let size = Size::new(64, 64);
2935 let rgba = vec![0u8; size.pixels() as usize * 4];
2936 let converted = I420::from_rgba(&rgba, size.width * 4, size).expect("rgba to i420");
2937 assert_eq!(
2938 converted.color(),
2939 Some(Color::BT601),
2940 "an RGB conversion knows the matrix it used"
2941 );
2942
2943 let resized = converted.resize(Size::new(32, 32)).expect("resize");
2945 assert_eq!(resized.color(), Some(Color::BT601), "resize preserves the space");
2946
2947 let size = Size::new(64, 64);
2949 let raw = I420::new(size, vec![0; I420::len(size).unwrap()]).expect("i420");
2950 assert_eq!(raw.color(), None);
2951 assert_eq!(
2952 raw.with_color(Color::BT709.with_range(crate::color::Range::Full))
2953 .color(),
2954 Some(Color::BT709.with_range(crate::color::Range::Full))
2955 );
2956 }
2957
2958 #[test]
2961 fn resize_labels_the_space_an_unlabelled_source_implied() {
2962 use super::{I420, Surface};
2963 use crate::{Color, Size};
2964
2965 let hd = Size::new(1280, 720);
2966 let sd = Size::new(640, 480);
2967 let raw = Surface::I420(I420::new(hd, vec![0x80; I420::len(hd).unwrap()]).unwrap());
2968 assert_eq!(raw.color(), None);
2969
2970 let config = crate::resize::Config::default();
2971 let scaled = raw.resize(sd, &config).unwrap();
2972 assert_eq!(scaled.color(), Some(Color::BT709));
2973
2974 let full = Surface::I420(
2976 I420::new(hd, vec![0x80; I420::len(hd).unwrap()])
2977 .unwrap()
2978 .with_color(Color::BT601.with_range(crate::color::Range::Full)),
2979 );
2980 assert_eq!(
2981 full.resize(sd, &config).unwrap().color(),
2982 Some(Color::BT601.with_range(crate::color::Range::Full))
2983 );
2984 }
2985
2986 #[cfg(all(target_os = "linux", feature = "capture"))]
2991 #[test]
2992 fn yuyv_capture_keeps_its_color_space_open() {
2993 let (width, height) = (1280, 720);
2994 let yuyv = vec![0u8; width as usize * height as usize * 2];
2996 let frame = super::I420::from_yuyv(&yuyv, width * 2, Size::new(width, height)).expect("yuyv to i420");
2997 assert_eq!(frame.color(), None, "a chroma resample names no color space");
2998 }
2999
3000 #[cfg(all(target_os = "linux", feature = "capture"))]
3004 #[test]
3005 fn mjpeg_capture_decodes_at_the_negotiated_size() {
3006 const RED: &[u8] = include_bytes!("frame/test_data/red_32x16.jpg");
3007 let size = Size::new(32, 16);
3008 let frame = super::I420::from_mjpeg(RED, size).expect("mjpeg to i420");
3009 assert_eq!(frame.size(), size);
3010 let luma = size.pixels() as usize;
3011 let (u, v) = frame.data()[luma..].split_at(luma / 4);
3012 assert!(
3013 u.iter().all(|&u| u < 128) && v.iter().all(|&v| v > 192),
3014 "red decodes to low U and high V"
3015 );
3016
3017 assert!(
3018 super::I420::from_mjpeg(RED, Size::new(16, 16)).is_err(),
3019 "size mismatch"
3020 );
3021 assert!(
3022 super::I420::from_mjpeg(&RED[..RED.len() / 2], size).is_err(),
3023 "truncated"
3024 );
3025 }
3026
3027 #[cfg(all(target_os = "linux", feature = "capture"))]
3034 #[test]
3035 fn mjpeg_capture_decodes_a_real_camera_frame() {
3036 const FRAME: &[u8] = include_bytes!("frame/test_data/zv_e10_1280x720.jpg");
3037 #[rustfmt::skip]
3038 const FFMPEG_LUMA: [u8; 144] = [
3039 18, 17, 19, 25, 39, 34, 33, 27, 21, 19, 20, 19, 23, 31, 30, 24,
3040 18, 18, 20, 24, 29, 26, 35, 28, 56, 21, 36, 25, 27, 30, 31, 27,
3041 18, 19, 20, 20, 20, 40, 51, 55, 66, 19, 32, 17, 24, 31, 30, 24,
3042 18, 18, 19, 17, 20, 36, 114, 54, 30, 18, 32, 19, 28, 29, 29, 24,
3043 17, 18, 17, 18, 19, 48, 121, 69, 39, 20, 26, 21, 23, 26, 20, 22,
3044 17, 17, 16, 28, 24, 35, 80, 62, 53, 24, 24, 25, 28, 25, 19, 21,
3045 17, 17, 16, 34, 43, 61, 86, 62, 20, 22, 24, 27, 26, 24, 20, 18,
3046 19, 18, 16, 21, 38, 27, 54, 30, 18, 18, 24, 20, 22, 19, 17, 20,
3047 19, 19, 16, 16, 19, 18, 54, 23, 17, 17, 19, 17, 19, 17, 17, 17,
3048 ];
3049 let size = Size::new(1280, 720);
3050 let frame = super::I420::from_mjpeg(FRAME, size).expect("camera frame to i420");
3051 assert_eq!(frame.size(), size);
3052 let luma = size.pixels() as usize;
3053 let (width, block) = (1280, 80);
3054 for (index, want) in FFMPEG_LUMA.iter().enumerate() {
3055 let (column, row) = (index % 16, index / 16);
3056 let sum: usize = (0..block)
3057 .flat_map(|y| (0..block).map(move |x| (row * block + y) * width + column * block + x))
3058 .map(|offset| usize::from(frame.data()[offset]))
3059 .sum();
3060 let got = sum / (block * block);
3061 assert!(
3062 got.abs_diff(usize::from(*want)) <= 4,
3063 "block {column},{row}: {got}, ffmpeg {want}"
3064 );
3065 }
3066 let chroma = luma / 4;
3067 let mean = |plane: &[u8]| plane.iter().map(|&c| usize::from(c)).sum::<usize>() / chroma;
3068 let (u, v) = frame.data()[luma..].split_at(chroma);
3069 assert!(
3070 mean(u).abs_diff(125) <= 1 && mean(v).abs_diff(133) <= 1,
3071 "chroma {} {}",
3072 mean(u),
3073 mean(v)
3074 );
3075 }
3076
3077 #[test]
3081 fn i420_new_rejects_a_short_buffer() {
3082 use super::I420;
3083
3084 let size = crate::Size::new(64, 32);
3085 let len = I420::len(size).unwrap();
3086 assert!(I420::new(size, vec![0; len]).is_ok());
3087 assert!(I420::new(size, vec![0; len - 1]).is_err());
3088 assert!(I420::new(size, Vec::new()).is_err());
3089 assert!(I420::len(crate::Size::new(63, 32)).is_err());
3091 assert!(I420::new(crate::Size::new(0, 32), Vec::new()).is_err());
3092 }
3093
3094 #[test]
3097 fn public_pixel_boundaries_reject_overflow() {
3098 use super::{I420, Surface};
3099
3100 let huge = crate::Size::new(u32::MAX - 1, u32::MAX - 1);
3101 assert!(I420::len(huge).is_err());
3102 assert!(I420::new(huge, Vec::new()).is_err());
3103 assert!(Surface::rgba(&[], huge).is_err());
3104 }
3105
3106 use super::{Frame, I420, Surface};
3107 use crate::Size;
3108
3109 #[test]
3112 fn surface_rgba_rejects_a_mismatched_buffer() {
3113 let ok = vec![0x80u8; 64 * 32 * 4];
3114 assert!(Surface::rgba(&ok, Size::new(64, 32)).is_ok());
3115 assert!(Surface::rgba(&ok[..ok.len() - 4], Size::new(64, 32)).is_err());
3116 assert!(Surface::rgba(&ok, Size::new(32, 32)).is_err());
3117 assert!(Surface::rgba(&ok, Size::new(0, 32)).is_err());
3118 }
3119
3120 #[test]
3124 fn consuming_i420_preserves_type_metadata_and_allocation() {
3125 use crate::Color;
3126
3127 let size = Size::new(64, 32);
3128 let transposed = Size::new(32, 64);
3129 assert_eq!(I420::len(size).unwrap(), I420::len(transposed).unwrap());
3130
3131 let pixels = I420::new(size, vec![0x80; I420::len(size).unwrap()])
3132 .unwrap()
3133 .with_color(Color::BT709.with_range(crate::color::Range::Full));
3134 let allocation = pixels.data().as_ptr();
3135 let pixels = Surface::I420(pixels).into_i420().unwrap();
3136
3137 assert_eq!(pixels.size(), size);
3138 assert_ne!(pixels.size(), transposed);
3139 assert_eq!(pixels.color(), Some(Color::BT709.with_range(crate::color::Range::Full)));
3140 assert_eq!(pixels.data().as_ptr(), allocation);
3141 assert_eq!(pixels.into_data().len(), I420::len(size).unwrap());
3142 }
3143
3144 #[test]
3148 fn to_i420_distinguishes_borrowed_and_owned_pixels() {
3149 use std::borrow::Cow;
3150
3151 let size = Size::new(64, 32);
3152 let surface = Surface::I420(I420::new(size, vec![0x80; I420::len(size).unwrap()]).unwrap());
3153 assert!(matches!(surface.to_i420().unwrap(), Cow::Borrowed(_)));
3154 }
3155
3156 #[cfg(target_os = "linux")]
3157 #[test]
3158 fn to_i420_owns_downloaded_native_pixels() {
3159 use std::borrow::Cow;
3160 use std::sync::Arc;
3161
3162 use super::{DmaBuf, DmaBufFrame, DmaBufPlane, DrmFormat};
3163
3164 struct Native(I420);
3165
3166 impl DmaBufFrame for Native {
3167 fn export(&self) -> std::io::Result<std::os::fd::OwnedFd> {
3168 Err(std::io::Error::from(std::io::ErrorKind::Unsupported))
3169 }
3170
3171 fn download_i420(&self) -> Result<I420, crate::Error> {
3172 Ok(self.0.clone())
3173 }
3174 }
3175
3176 let size = Size::new(64, 32);
3177 let pixels = I420::new(size, vec![0x80; I420::len(size).unwrap()]).unwrap();
3178 let surface = Surface::DmaBuf(DmaBuf {
3179 format: DrmFormat::YUV420,
3180 modifier: 0,
3181 width: size.width,
3182 height: size.height,
3183 planes: vec![DmaBufPlane::new(0, size.width)],
3184 color: None,
3185 inner: Arc::new(Native(pixels)),
3186 });
3187
3188 assert!(matches!(surface.to_i420().unwrap(), Cow::Owned(_)));
3189 }
3190
3191 #[test]
3194 fn decoder_planes_discard_row_padding() {
3195 let y = [
3196 1, 2, 3, 4, 200, 201, 202, 5, 6, 7, 8, 203, 204, 205, 9, 10, 11, 12, 206, 207, 208, 13, 14, 15, 16, 209,
3197 210, 211,
3198 ];
3199 let u = [21, 22, 220, 221, 23, 24, 222, 223];
3200 let v = [31, 32, 230, 231, 33, 34, 232, 233];
3201
3202 let frame = I420::from_planes(&y, &u, &v, 7, 4, Size::new(4, 4)).unwrap();
3203 assert_eq!(frame.y(), &(1..=16).collect::<Vec<_>>());
3204 assert_eq!(frame.u(), &[21, 22, 23, 24]);
3205 assert_eq!(frame.v(), &[31, 32, 33, 34]);
3206 }
3207
3208 #[test]
3216 fn rgb_conversion_follows_the_size_heuristic() {
3217 use yuv::{YuvPlanarImage, yuv420_to_rgba};
3218
3219 use crate::Color;
3220
3221 let red = |size: Size| {
3222 let rgba = [255u8, 0, 0, 255].repeat(size.pixels() as usize);
3223 I420::from_rgba(&rgba, size.width * 4, size).unwrap()
3224 };
3225
3226 let decode = |i420: &I420| {
3229 let (w, h) = (i420.width, i420.height);
3230 let (range, matrix) = Color::infer(Size::new(w, h)).yuv();
3231 let planar = YuvPlanarImage {
3232 y_plane: i420.y(),
3233 y_stride: w,
3234 u_plane: i420.u(),
3235 u_stride: w / 2,
3236 v_plane: i420.v(),
3237 v_stride: w / 2,
3238 width: w,
3239 height: h,
3240 };
3241 let mut rgba = vec![0u8; (w * h * 4) as usize];
3242 yuv420_to_rgba(&planar, &mut rgba, w * 4, range, matrix).unwrap();
3243 let px = ((h / 2 * w + w / 2) * 4) as usize;
3244 [rgba[px], rgba[px + 1], rgba[px + 2]]
3245 };
3246
3247 for (size, expected) in [
3248 (Size::new(720, 480), Color::BT601),
3249 (Size::new(720, 576), Color::BT601),
3250 (Size::new(1280, 720), Color::BT709),
3251 (Size::new(1920, 1080), Color::BT709),
3252 ] {
3253 let i420 = red(size);
3254 assert_eq!(i420.color(), Some(expected), "{size} reported color");
3255
3256 let rgb = decode(&i420);
3259 assert!(
3260 rgb[1] <= 2 && rgb[2] <= 2,
3261 "{size} red came back as {rgb:?}, so the matrix and the label disagree"
3262 );
3263 }
3264 }
3265
3266 #[test]
3269 fn frame_size_follows_the_surface() {
3270 let rgba = vec![0x80u8; 64 * 32 * 4];
3271 let surface = Surface::rgba(&rgba, Size::new(64, 32)).unwrap();
3272
3273 let frame = Frame::new(moq_net::Timestamp::from_micros(1234).unwrap(), surface);
3274 assert_eq!(frame.size(), Size::new(64, 32));
3275
3276 let scaled = frame
3277 .resize(Size::new(32, 16), &crate::resize::Config::default())
3278 .unwrap();
3279 assert_eq!(scaled.size(), Size::new(32, 16));
3280 assert_eq!(scaled.timestamp, frame.timestamp);
3281 }
3282
3283 #[cfg(apple)]
3287 #[test]
3288 fn into_pixel_buffer_uploads_a_cpu_frame() {
3289 use objc2_core_video::{CVPixelBufferGetHeight, CVPixelBufferGetWidth};
3290
3291 let size = Size::new(64, 32);
3292 let i420 = I420::new(size, vec![0x80; I420::len(size).unwrap()]).unwrap();
3293 let frame = Frame::new(moq_net::Timestamp::from_micros(0).unwrap(), Surface::I420(i420));
3294
3295 let buffer = frame.surface.into_pixel_buffer().expect("upload a CPU frame");
3296 assert_eq!(CVPixelBufferGetWidth(&buffer), 64);
3297 assert_eq!(CVPixelBufferGetHeight(&buffer), 32);
3298 }
3299
3300 fn gradient_i420(width: u32, height: u32) -> I420 {
3303 let (w, h) = (width as usize, height as usize);
3304 let (cw, ch) = (w / 2, h / 2);
3305 let mut data = vec![0u8; I420::len(Size::new(width, height)).unwrap()];
3306 let (y, chroma) = data.split_at_mut(w * h);
3307 let (u, v) = chroma.split_at_mut(cw * ch);
3308 for row in 0..h {
3309 for col in 0..w {
3310 y[row * w + col] = ((col * 255) / w) as u8;
3311 }
3312 }
3313 for row in 0..ch {
3314 for col in 0..cw {
3315 u[row * cw + col] = ((row * 255) / ch) as u8;
3316 v[row * cw + col] = (((row + col) * 255) / (ch + cw)) as u8;
3317 }
3318 }
3319 I420 {
3320 width,
3321 height,
3322 data,
3323 color: None,
3324 }
3325 }
3326
3327 fn mae(a: &[u8], b: &[u8]) -> u64 {
3329 assert_eq!(a.len(), b.len());
3330 a.iter().zip(b).map(|(x, y)| x.abs_diff(*y) as u64).sum::<u64>() / a.len() as u64
3331 }
3332
3333 #[test]
3336 fn i420_resize_follows_gradients() {
3337 let src = gradient_i420(320, 240);
3338 let dst = src.resize(Size::new(128, 96)).unwrap();
3339 assert_eq!((dst.width, dst.height), (128, 96));
3340
3341 let expected = gradient_i420(128, 96);
3343 assert!(mae(dst.y(), expected.y()) < 4, "luma ramp drifted");
3344 assert!(mae(dst.u(), expected.u()) < 4, "u ramp drifted");
3345 assert!(mae(dst.v(), expected.v()) < 4, "v ramp drifted");
3346 }
3347
3348 #[cfg(apple)]
3351 #[test]
3352 fn pixel_buffer_resize_matches_cpu() {
3353 let src_i420 = gradient_i420(320, 240);
3354 let src = Surface::PixelBuffer(nv12_surface(&src_i420));
3355 let scaled = src
3356 .resize(Size::new(160, 120), &crate::resize::Config::default())
3357 .unwrap();
3358 let Surface::PixelBuffer(scaled) = scaled else {
3359 panic!("VideoToolbox resize downloaded to the CPU");
3360 };
3361
3362 let gpu = scaled.download_i420().unwrap();
3363 let cpu = src_i420.resize(Size::new(160, 120)).unwrap();
3364
3365 assert_eq!((gpu.width, gpu.height), (160, 120));
3366 assert!(mae(gpu.y(), cpu.y()) < 4, "GPU and CPU luma disagree");
3367 assert!(mae(gpu.u(), cpu.u()) < 4, "GPU and CPU u disagree");
3368 assert!(mae(gpu.v(), cpu.v()) < 4, "GPU and CPU v disagree");
3369 }
3370
3371 #[cfg(apple)]
3373 #[test]
3374 fn pixel_buffer_resize_can_force_the_cpu() {
3375 let config = crate::resize::Config {
3376 output: crate::Output::Cpu,
3377 ..Default::default()
3378 };
3379 let source = Surface::PixelBuffer(nv12_surface(&gradient_i420(320, 240)));
3380 let scaled = source.resize(Size::new(160, 120), &config).unwrap();
3381
3382 assert!(matches!(scaled, Surface::I420(_)), "CPU resize stayed on the GPU");
3383 }
3384
3385 #[cfg(apple)]
3388 #[test]
3389 fn pixel_buffer_converts_to_rgba() {
3390 let source = gradient_i420(322, 242);
3391 let expected = Surface::I420(source.clone())
3392 .to_rgba(&crate::convert::Config::default())
3393 .unwrap();
3394 let actual = Surface::PixelBuffer(nv12_surface(&source))
3395 .to_rgba(&crate::convert::Config::default())
3396 .unwrap();
3397
3398 assert_eq!(actual.width(), 322);
3399 assert_eq!(actual.height(), 242);
3400 assert_eq!(actual.stride(), 322 * 4);
3401 assert_eq!(actual.data(), expected.data());
3402 }
3403
3404 #[cfg(apple)]
3407 #[test]
3408 fn pixel_buffer_download_refuses_a_size_past_its_planes() {
3409 let surface = nv12_surface(&gradient_i420(64, 48));
3410 let oversized = super::apple::PixelBuffer::new(surface.buffer.clone(), 64, 480);
3411 assert!(oversized.download_i420().is_err());
3412
3413 assert_eq!(surface.download_i420().unwrap().height, 48);
3415 }
3416
3417 #[cfg(apple)]
3418 use super::apple::nv12_surface;
3419
3420 #[cfg(target_os = "windows")]
3422 #[test]
3423 #[ignore = "D3D11 GPU reproducer; VideoProcessorBlt can hang on affected drivers"]
3424 fn d3d11_resize_defaults_to_the_gpu() {
3425 let Ok(device) = super::d3d11::create_device(None) else {
3426 eprintln!("skipping: no Direct3D11 hardware device");
3427 return;
3428 };
3429 let Ok(texture) = super::d3d11::upload_i420(&device, &gradient_i420(320, 240)) else {
3430 eprintln!("skipping: driver will not allocate a usable NV12 texture");
3431 return;
3432 };
3433 if !super::d3d11::supports_nv12_render_target(&device) {
3434 eprintln!("skipping: driver cannot render to NV12");
3435 return;
3436 }
3437
3438 let scaled = Surface::Texture(texture)
3439 .resize(crate::Size::new(160, 120), &crate::resize::Config::default())
3440 .unwrap();
3441 assert!(
3442 matches!(scaled, Surface::Texture(_)),
3443 "Direct3D11 resize downloaded to the CPU"
3444 );
3445 assert_eq!((scaled.width(), scaled.height()), (160, 120));
3446 }
3447
3448 #[cfg(target_os = "windows")]
3450 #[test]
3451 fn d3d11_resize_can_force_the_cpu() {
3452 let Ok(device) = super::d3d11::create_device(None) else {
3453 eprintln!("skipping: no Direct3D11 hardware device");
3454 return;
3455 };
3456 let Ok(texture) = super::d3d11::upload_i420(&device, &gradient_i420(320, 240)) else {
3457 eprintln!("skipping: driver will not allocate a usable NV12 texture");
3458 return;
3459 };
3460
3461 let config = crate::resize::Config {
3462 output: crate::Output::Cpu,
3463 ..Default::default()
3464 };
3465 let scaled = Surface::Texture(texture)
3466 .resize(crate::Size::new(160, 120), &config)
3467 .unwrap();
3468 assert!(matches!(scaled, Surface::I420(_)), "Direct3D11 resize ignored CPU mode");
3469 }
3470
3471 #[cfg(target_os = "windows")]
3475 #[test]
3476 #[ignore = "explicit D3D11 GPU probe; VideoProcessorBlt can hang on affected drivers"]
3477 fn d3d11_resize_matches_cpu() {
3478 let Ok(device) = super::d3d11::create_device(None) else {
3479 eprintln!("skipping: no Direct3D11 hardware device");
3480 return;
3481 };
3482 let source = gradient_i420(320, 240);
3483 let Ok(texture) = super::d3d11::upload_i420(&device, &source) else {
3484 eprintln!("skipping: driver will not allocate a usable NV12 texture");
3485 return;
3486 };
3487 if !super::d3d11::supports_nv12_render_target(&device) {
3488 eprintln!("skipping: driver cannot render to NV12");
3489 return;
3490 }
3491
3492 let gpu = texture.resize(160, 120).unwrap().download_i420().unwrap();
3493 let cpu = source.resize(crate::Size::new(160, 120)).unwrap();
3494
3495 assert_eq!((gpu.width, gpu.height), (160, 120));
3496 assert!(mae(gpu.y(), cpu.y()) < 4, "GPU and CPU luma disagree");
3497 assert!(mae(gpu.u(), cpu.u()) < 4, "GPU and CPU u disagree");
3498 assert!(mae(gpu.v(), cpu.v()) < 4, "GPU and CPU v disagree");
3499 }
3500
3501 #[cfg(all(target_os = "linux", feature = "nvidia"))]
3504 #[test]
3505 fn cuda_resize_matches_cpu() {
3506 use std::sync::Arc;
3507
3508 use cudarc::driver::{CudaContext, result};
3509
3510 use super::cuda;
3511
3512 if unsafe { libloading::Library::new("libcuda.so.1") }.is_err() {
3514 return;
3515 }
3516 let Ok(ctx): Result<Arc<CudaContext>, _> = CudaContext::new(0) else {
3517 return;
3518 };
3519
3520 let (w, h) = (322u32, 242u32); let src_i420 = gradient_i420(w, h);
3522
3523 let pitch = 512u32;
3525 let frame = cuda::Frames::new(&ctx).alloc(Size::new(w, h), pitch).unwrap();
3526 let mut host = vec![0u8; pitch as usize * h as usize * 3 / 2];
3527 for row in 0..h as usize {
3528 let dst = row * pitch as usize;
3529 host[dst..dst + w as usize].copy_from_slice(&src_i420.y()[row * w as usize..(row + 1) * w as usize]);
3530 }
3531 let (cw, ch) = (w as usize / 2, h as usize / 2);
3532 for row in 0..ch {
3533 let dst = (h as usize + row) * pitch as usize;
3534 for col in 0..cw {
3535 host[dst + 2 * col] = src_i420.u()[row * cw + col];
3536 host[dst + 2 * col + 1] = src_i420.v()[row * cw + col];
3537 }
3538 }
3539 unsafe { result::memcpy_htod_sync(frame.device_ptr(), &host) }.unwrap();
3541
3542 let scaled = frame.resize(Size::new(160, 120)).unwrap();
3543 let gpu = scaled.download_i420().unwrap();
3544 let cpu = src_i420.resize(crate::Size::new(160, 120)).unwrap();
3545
3546 assert_eq!((gpu.width, gpu.height), (160, 120));
3547 assert!(mae(gpu.y(), cpu.y()) < 4, "GPU and CPU luma disagree");
3548 assert!(mae(gpu.u(), cpu.u()) < 4, "GPU and CPU u disagree");
3549 assert!(mae(gpu.v(), cpu.v()) < 4, "GPU and CPU v disagree");
3550 }
3551}
3552
3553#[cfg(all(test, target_os = "linux"))]
3554mod external_dmabuf_tests {
3555 use super::*;
3556 use std::sync::atomic::{AtomicUsize, Ordering};
3557
3558 #[test]
3559 fn external_buffer_retains_lease_and_refuses_cpu_download() {
3560 struct Guard(Arc<AtomicUsize>);
3561 impl Drop for Guard {
3562 fn drop(&mut self) {
3563 self.0.fetch_add(1, Ordering::SeqCst);
3564 }
3565 }
3566 let released = Arc::new(AtomicUsize::new(0));
3567 let layout = DmaBufLayout::new(
3568 DrmFormat::NV12,
3569 Size::new(4, 2),
3570 vec![DmaBufPlane::new(0, 4), DmaBufPlane::new(8, 4)],
3571 );
3572 let buffer = DmaBuf::new(
3573 std::fs::File::open("/dev/zero").unwrap().into(),
3574 layout,
3575 Guard(released.clone()),
3576 )
3577 .unwrap();
3578 assert!(Surface::DmaBuf(buffer.clone()).to_i420().is_err());
3579 let export = buffer.export().unwrap();
3580 drop(buffer);
3581 assert_eq!(released.load(Ordering::SeqCst), 0);
3582 drop(export);
3583 assert_eq!(released.load(Ordering::SeqCst), 1);
3584 }
3585
3586 #[test]
3587 fn external_buffer_refuses_empty_or_zero_stride_planes() {
3588 for planes in [vec![], vec![DmaBufPlane::new(0, 0)]] {
3589 let layout = DmaBufLayout::new(DrmFormat::NV12, Size::new(4, 2), planes);
3590 assert!(DmaBuf::new(std::fs::File::open("/dev/zero").unwrap().into(), layout, ()).is_err());
3591 }
3592 }
3593}